0
public class Test {


    public static void main(String[] args) {

        String s1 = "Hey";
        String s2 = "How are you?";
        String s3 = null;
        String s4 = null;


        String[] s = {s3, s4};
        s3 = s1;
        s2 = s4;

        for(String str : s) {
            System.out.println(str);
        }
    }
}

I Tried this, to give s3 and s4 in array s, the value's of s1 and s2, in another project. Output is null null. I don't understand why it isn't working.

DT7
  • 1,615
  • 14
  • 26
  • See http://stackoverflow.com/questions/5835386/java-string-variable-setting-reference-or-value – Bit Nov 25 '13 at 15:17

7 Answers7

4

Strings in Java are immutable. There's no way you can change the String objects s3 and s4 are referencing. When you're doing s3 = s1 you're making the local variable s3 reference the same String instance as s1, but the value the array is holding is still the old value referenced by s3.

You could think of the String variables like some sort of a pointer to a String object. You can change where is the variable pointing to (which instance it is referencing), but you can't change the referenced object.

You need to add assign new (or alrady existing) String instances to the array:

s[0]=s1

The s2 = s4 statement would just make the s2 local variable reference the object already referenced by s4 (which is a null reference).

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161
2

You must change the value directly from the array:

s[0] = s1;
s[1] = s4;
Josh M
  • 11,611
  • 7
  • 39
  • 49
1

You have to be careful with order of statements. So change:

String[] s = {s3, s4};
s3 = s1;
s2 = s4;

to:

s3 = s1;
s2 = s4;
String[] s = {s3, s4};
user987339
  • 10,519
  • 8
  • 40
  • 45
1

You have to modify the actual array not the reference.

s[0]=s1
s[1]=s2
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

make it

s[0] = s1; 
s[1] = s4;

If you are the array, then the values must be changed from the array.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
0

s3 and s4 are only reference to an Object. You are changing your local reference not objects itself.

homik
  • 553
  • 5
  • 9
0

Hi i think the problem is the assigment of the values.

Try something like this:

public static void main(String[] args) {
    String s1 = "Hey";
    String s2 = "How are you?";
    String s3 = null;
    String s4 = null;


    String[] s = {s3, s4};
    s[0] = s1;
    s[1] = s2;

    for(String str : s) {
        System.out.println(str);
    }
}    

Also you need to change this

s2 = s4;

Regards

ELavicount
  • 429
  • 3
  • 16