0

i have tried to assign directly and by creating new instance also. it is assigning values fine.but if i try to modify the normal string array,static string array is also modifying.can anyone help on this

chaithu
  • 23
  • 5

2 Answers2

1

If you create a new string array, it wont share the reference.

Example with String:

String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // same reference
String s4 = new String("Hello");  // String object
String s5 = new String("Hello");  // String object

enter image description here

More info: https://www3.ntu.edu.sg/home/ehchua/programming/java/J3d_String.html

Gonz
  • 1,198
  • 12
  • 26
0

Use Arrays.copyOf which not only copy elements, but also creates a new array.
See the below code, it solves your problem:-

 static  String[] array=new String[]{"1","2"};

    public static void main(String[] args) {
        String[] array2=Arrays.copyOf(array, array.length);
       System.out.println("Printing array2:-");
        for(String elem:array2){
            System.out.print(elem+"|");
        }
        System.out.println("\nPrinting array:-");
        array[0]="4";
        for(String elem:array){
            System.out.print(elem+"|");
        }
        System.out.println("\nPrinting array2:-");
        for(String elem:array2){
            System.out.print(elem+"|");
        }
    }

Output:-

Printing array2:-
1|2|
Printing array:-
4|2|
Printing array2:-
1|2|
Amit Bhati
  • 5,569
  • 1
  • 24
  • 45