This content has been marked as final. Show 8 replies
Will print true
String test = "This is a String"; String test2 = test; System.out.println(test == test2);
This works because both string variables are pointing at the same String Object. If you do this instead
It prints false, because the new String() creates a new String Object and sets its value to the value of test.
String test = "This is a String"; String test2 = new String(test); System.out.println(test == test2);
Compare Objects for equality by using theirI know i should use:
to compare the character contents of the two strings.
s1= = s2 to compare two object references to check if they refer to the same instance.
BUT what im trying to say is when will two objects ever refer to the same instance???? I mean why was the answer to te question that i posted false and not true?
Im new to java and these concepts are new to me.
Thanks for bearing with me
In your example you are creating 2 different objects, so they are not equal when using == to compare (they are references to 2 different objects)
if you do this
it prints true, because java will create a String object with the value "test" and intern it, so when you compare "test" to "test" both strings are pointing at the same Object, thus it prints true.
System.out.println("test" == "test");
Hope that helps to clarify it for you.