+ 3

It checks references or values?

String a = "text"; String b = "text"; System.out.print(a == b);

25th Jun 2019, 6:45 AM
Shubham Tandale
Shubham Tandale - avatar
7 ответов
+ 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.
26th Jun 2019, 4:26 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 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.
26th Jun 2019, 6:44 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 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
26th Jun 2019, 2:36 AM
Shubham Tandale
Shubham Tandale - avatar
+ 2
You can't compare strings like that, you should use the equals method: System.out.println(a.equals(b); //true
25th Jun 2019, 6:50 AM
Airree
Airree - avatar
+ 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 ==.
25th Jun 2019, 7:13 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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
26th Jun 2019, 2:39 AM
Shubham Tandale
Shubham Tandale - avatar