+ 3
It checks references or values?
String a = "text"; String b = "text"; System.out.print(a == b);
7 Respuestas
+ 12
== tests for reference equality,
(whether they are the same object)
.equals( ) tests for value equality,
(whether they are logically "equal")
equals() is a method used to compare two objects for equality.
+ 11
• Requirement of String Pool
String pool (String intern pool) is a special storage area in Method Area. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
String string1 = "abcd";
String string2 = "abcd";
If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
+ 3
I got the answer.
Whenever we define direct string it stores it on SCP (string constant pool) and then if same string is assigned for other object it did not create another but the object points to same string location of SCP.
EXAMPLE: here "text" object is created on SCP when a is declared so a is pointing to "text" object on SCP. When b is declared , b also points to same object on SCP i.e. "text" because if there is already present object on SCP JVM not creates another one.
if a and b pointing to same object, so definitely they have same reference/location address hold (lets say "text" has address 1000) so a=1000, b =1000
So a==b gives 1000=1000 which returns true.
On the other hand if we declare
String a = new String("text");
String b = new String("text");
There will be two objects and they will be on heap not on SCP(string constant pool).
So a points to another object and b points to another.
Here a==b does not work because a and b have different references so we have to use a.equals(b) returns true
+ 2
You can't compare strings like that, you should use the equals method:
System.out.println(a.equals(b);
//true
+ 2
Memory location.
You would only get true if String a and String b are stored in the same memory address.
For all objects -> use equals() instead of ==.
+ 2
What I want to say is that
obj1==obj2 is used for checking references are same or not of obj1 and obj2.
obj1.equals(obj2) is used for checking values/contents are same or not hold by obj1 and obj2