This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi everyone !
Hope you all are fine . Today in field of programming i face a very new and basic problem, i declare two Strings
Now initiate these string with same sentence like
s1 = "Hello";
s2 = "Hello";
now i check
it will return true but when i make an object like
String s1 = new String("Hello");
String s2 = new String("Hello");
it will return false. Here i am little bit confused, what the actually scene behind both cases, and one thing more when i check through ".equal" in both cases it return true, please give me some concept.
The == operator always compares references. If two references point to the same object, or are both null, then == evaluates to true. Otherwise, it evaluates to false.
The equals() method does whatever we tell it to do. It is meant to determine if the states (contents) of two objects are "equal" according to whatever the semantics of equality are for the class in question. For Object, equals() just uses ==, but for other classes, it does things that make sense for that class. For String, equals() looks at the character sequences of the two objects.
So why did == give true in one case and false in the other? If you read my very first sentence above, you already know what the answer must be. It's that in one case the two references pointed to the same object, and in the other case, they didn't.
When we do new Xxx(), that always creates a new object, so obviously the new String() case will have to give us a result of false for ==, since we can see we're creating 2 new objects.
However, for certain objects of certain classes--String literals and small values of primitive wrappers--the objects are cached, and our code sometimes refers to the objects in the cache (also known as a constant pool) instead of creating new objects. When we do String s = "abc"; it doesn't create a new String object, just gives us a reference to the one in the String pool.
Note, however, that you should never rely on this behavior as a shortcut for checking equality. ALWAYS use equals() if you want to know if two references point to objects with equal contents.
Salman Mushtaq wrote:Here i am little bit confused, what the actually scene behind both cases, and one thing more when i check through ".equal" in both cases it return true, please give me some concept.