What you have demonstrated in the code below is 1) With sl1 and sl2 equality
As a string is an immutable object, you have sl1 and sl2 pointing to the same object, == compares addresses where as .equals(object) compares equality. If the addresses are the same then you know its the same object with the same values.
2) With sob1 and sob2 you have compared values
You have explicitly called NEW which created two new objects. These will have new address which will return a boolean false when compared using a == operator but true when compared for equivalent value using .equals
Try playing around with your code to use both the == and .equals for each example and you will see the difference.
You should notice that "...if (sob1==sob2).." returns false! [ February 11, 2008: Message edited by: Robert Elbourn ]
Hi Gopal, The answer to your question of why it doesn't print the addresses but prints the values of the strings are that - whenever you call the system.out.println() on any object,in this case a String,it calls the toString() method on that object. In this case,that of an object of class String,the toString() method is overridden to print the String literal that the reference refers to. Hope you got it. tc
This is the main point you have to look at in the SCJP,The comparision operator is used for comparing the references and if you want to compare the objects you have to use equals() method.
In your current code if(sl1 == sl2) is true as you are comparing the references, and in the second piece of code you are creating new two objects with different string and obvious you used equals() it is fine.
So as and when the first IF condition is satified it prints the first set of strings,and second IF condition is satisfied it prints the new set of strings created using new object.
Joined: Mar 29, 2007
Thanks for spending your precious time to clear my doubt. Have a great day.