sparsh khandelwal wrote:
please give a clear cut clarification about line 7 and line 8 : outputs
one is true its ok
but why other one is false?
The == operator evaluates to true only if both references point to the same object (or both are null). Based on the discussion in your other thread, you should now understand why it's false.
When you creating a String using "" only, JVM creates the same String only one time. That means no duplicate Strings are created.(Therefore here both s and s1 refers the same object)
But when you are using new command to create a String object, duplication is allowed. Therefore here JVM creates 2 equal objects in the memory heep. As s and s1 refers 2 objects, s==s1 returns false...
sparsh khandelwal wrote:
In Java there are two different ways to check for equality.
1. == operator
2. equals() method (a part of Object which is a parent class to every other class)
While equals() works with object types only == works with primitives as well.
equals() checks the equality using the value contained by two objects (you can also do that with the same object though)
== gives a true result only when the two primitives have the same value (downcasting and upcasting should be considered also) or two references point to the exact same object.
you can override the equals() in your class and give meaning to it as to how you want your class objects to be checked for equality.
Also, in your code s1.concat("a") won't do any change to s1 itself which is why at line 7 the result of equals() is true.
Strings are immutable objects and whenever you operate on a String object it gives you another String object.
Phew ... this much for now ...
That is not quite correct. It does have meaning, in that is creates a new String "xyza". But that String is not used and disappears into cyber‑limbo never to be seen again. It would have been helpful to explain to the OP why you still get true from the equals() method later on. Lalit Mehra does actually supply that explanation.
Ramesh Pramuditha Rathnayake wrote:There is no meaning in line 5. . . .
The right way and the wrong way.
Lalit Mehra wrote: . . .
In Java there are two different ways to check for equality. . . .
The right way is to use the equals() method, which of course does not work on primitives. The == operator can produce incorrect and misleading results on reference types, and can even give incorrect results on primitives (see no 20).
Campbell Ritchie wrote:That is not quite correct...
I mean that no need of that line. Returning a new String object is correct...
== checks whether the object references are equal.
Here s ans s1 both refer the same object. Therefore the references are equal. (That means s==s1 is true)
But equals() method returns true if the 2 objects are equivalent. This equality has to be defined by the creator of the class. If not, equals() method in Object class is running..