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
            Asked
            
        
        
            Active
            
        
            Viewed 165 times
        
    0
            
            
        - 
                    2Can you share your code, please? – Konstantin Yovkov Aug 20 '15 at 06:31
- 
                    defensive copy. create a new array with the same values, instead of a shared reference. – Stultuske Aug 20 '15 at 06:31
- 
                    i think a deep copy will help... http://stackoverflow.com/questions/1564832/how-do-i-do-a-deep-copy-of-a-2d-array-in-java – thomas Aug 20 '15 at 06:35
2 Answers
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
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
 
    