0

Possible Duplicate:
what is String pool in java?

1. I know that == checks if two object are pointing to same memory location also the default definition of equals uses == to do the checking, means both are same.

2. String class overrides equals method to check if two string have same value.

Consider S1 = "test" and S2 = S1;

Now S1 and S2 are two different objects so as per point 1 S1==S2 should be false and as per point 2 S1.equals(S2) should be true but when I ran this small program in eclipse both return true. Is there any special thing about string objects that S1 == S2 is also true.

Community
  • 1
  • 1
Sandeep Kumar
  • 13,799
  • 21
  • 74
  • 110

4 Answers4

3

Consider S1 = "test" and S2 = S1; Now S1 and S2 are two different objects

Nope. This is where your argument fails.

You created one string object, and both your variables refer to the same string object. Assignment does not make a new copy of the string.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3

When you write

s1 = s2;

s1 and s2 are references to the same object, so s1 == s2 will always return true.

More confusing - if you write:

s1 = "test";
s2 = "test";
s3 = new String("test");

you will find out that s1 == s2 is true but s1 == s3 is false. This is explained in more details in this post.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
2

Wiritng S1 = S2 results in them pointing towards the same object

Writing

String S1 = "test"
String S2 = "test"

Will yield the same results as you have now. This is due to compiler optimisation, the compiler notices the string class which is immutable, therefore he will optimise the code to both use the same instance. You can force him to make new strings by instaniating them with a constructor

String s1  = new String("test");
String s2  = new String("test");
System.out.println(s1 == s2) // false
System.out.println(s1.equals(s2)) //true
G-Man
  • 1,321
  • 8
  • 15
1

when you initialize

S2=S1 

they both point to same memory location.

try

S1 = "test"; 
S2 = "test";

this will give you

 S1==S2 //false
Mohd Mufiz
  • 2,236
  • 17
  • 28