== and .equals() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

== and .equals()

Why is the output true? String a = "hi"; String b = "hi"; System.out.println(a == b); A String is an object, when using == it compares the memory location.. so how is it true? Does it mean that they point to the same location? So why do we need .equals() if the == works ?

2nd Jul 2021, 3:33 PM
Yahel
Yahel - avatar
12 Answers
+ 2
Yahel Yes. This tutorial explains it well: https://www.baeldung.com/java-string-pool
2nd Jul 2021, 7:19 PM
Denise Roßberg
Denise Roßberg - avatar
+ 7
Hello Yahel If you create a String in this way: String a = "hi"; Then it is stored in the string pool. If you now create another String "hi" it takes it from the string pool. So in this case you do not really create a new String. As far as I know it is the only example where == returns true String a = "hi"; String b = new String("hi"); a == b returns false So a "hi" from user input or any other source will normally return false.
2nd Jul 2021, 6:42 PM
Denise Roßberg
Denise Roßberg - avatar
+ 4
Yahel Because here you are not creating a literal. next() and nextLine() returns a String Object.
2nd Jul 2021, 7:48 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Denise Roßberg thanks! Finally I get it :)
2nd Jul 2021, 7:33 PM
Yahel
Yahel - avatar
+ 1
Denise Roßberg ohhh, makes sense. Thanks
2nd Jul 2021, 7:49 PM
Yahel
Yahel - avatar
+ 1
pool saves memory, by intern() if String is in pool is used, else added and used String h1 = "hi"; String h2 = new String("hi").intern(); System.out.println( System.identityHashCode(h1) ); System.out.println( System.identityHashCode(h2) ); // returns same number
3rd Jul 2021, 4:16 PM
zemiak
0
String h = "h", i = "i"; System.out.println( "hi" == h+i); //false System.out.println( "hi".equals(h+i) ); //true
2nd Jul 2021, 5:09 PM
zemiak
0
zemiak so why does my example output true ?
2nd Jul 2021, 5:24 PM
Yahel
Yahel - avatar
0
Denise Roßberg can you elaborate about the "String pool"? Is it just pointing to the same value? When assigning a String without the "new" keyword, does it just point to an existing value (if there is one), and doesn't create a new one (assigning extra memory for this value)?
2nd Jul 2021, 7:15 PM
Yahel
Yahel - avatar
0
Denise Roßberg oh, so why doesn't it output true? Scanner scan = new Scanner(System.in); String a = scan.next(); String b = "hi"; System.out.println(a == b);
2nd Jul 2021, 7:42 PM
Yahel
Yahel - avatar
0
if you want ensure of use String pool, you can use .intern() String hi = new String("hi").intern(); System.out.println( "hi" == hi ); //true
3rd Jul 2021, 3:37 PM
zemiak
0
zemiak Ok, thanks. I read that there obviously can't be duplicates in the String pool, so what happens if you call the intern function on a String that already exists in the String pool? What is the String variable pointing to ?
3rd Jul 2021, 3:53 PM
Yahel
Yahel - avatar