There is no meaning in line 5. No matter if you omit it. You will get the same answer..
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...
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.
Ramesh Pramuditha Rathnayake wrote:There is no meaning in line 5. . . .
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.
posted 5 years ago
Lalit Mehra wrote: . . .
In Java there are two different ways to check for equality. . . .
The right way and the wrong way.
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).