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

3
  • 2
    Can you share your code, please? Commented Aug 20, 2015 at 6:31
  • defensive copy. create a new array with the same values, instead of a shared reference. Commented Aug 20, 2015 at 6:31
  • i think a deep copy will help... stackoverflow.com/questions/1564832/… Commented Aug 20, 2015 at 6:35

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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|

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.