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 ?
12 Réponses
+ 2
Yahel
Yes.
This tutorial explains it well:
https://www.baeldung.com/java-string-pool
+ 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.
+ 4
Yahel
Because here you are not creating a literal. next() and nextLine() returns a String Object.
+ 1
Denise Roßberg thanks! Finally I get it :)
+ 1
Denise Roßberg ohhh, makes sense. Thanks
+ 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
0
String h = "h", i = "i";
System.out.println( "hi" == h+i); //false
System.out.println( "hi".equals(h+i) ); //true
0
zemiak so why does my example output true ?
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)?
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);
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
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 ?