Str = "A"; lStr = "A"; System.out.println(Str.equals(lStr)); System.out.println(Str == lStr); //line 2 ---------------------------------- In code:1 the Str n lStr are differents string objects. From your reply i understood that the String is reassign then the NEW reference to that String object will lost. Then it is same as the String Str?
No object is created, str is a reference variable of type String that can refer to the String object.
One String object created using new operator and another created at compile time (without new) will yield false result when you apply ==.
Inside a method or block code, writing String str; and String str =null; have different meanings. You can't use the precious one (because it is neither initialized nor set to null) whereas you can use the further one as System.out.println(str); //prints null
Note: using equals() will always return true if the content of two strings match irrespective of whether they are same or not.
First of all the "==" tests if the two references point to the same object. So in code 1:
Str and lStr does not point to the same object because when you use the "new" operator a new object is created rather than looking in the String pool, so there are two different objects and therefore false.
in code 2:
Str and lStr ( Str = "A"; lStr = "A"; ) points to the same value in the String pool so the "==" returns true.