When I wrote this article about 3 years ago (and since updated), I was using DrJava which has a REPL interface (not JShell) that lets you run code line by line. In that interface, string pooling doesn't take effect:
Since your comment, I decided to test this out in a few places beyond DrJava (which still returns false). As far as I can tell, the expression returns true as you mentioned pretty much everywhere else (JShell, JDoodle, etc.).
Do you know if there's a version tied to this optimization and how reliable it is? In other words, can I always assume == will work on strings like .equals()?
For instance, I just saw this code snippet which apparently doesn't leverage interning:
Strings1="Test";Strings2=newString("Test");System.out.println(s1==s2);// Prints false
Hey! Good question.
When I wrote this article about 3 years ago (and since updated), I was using DrJava which has a REPL interface (not JShell) that lets you run code line by line. In that interface, string pooling doesn't take effect:
Since your comment, I decided to test this out in a few places beyond DrJava (which still returns false). As far as I can tell, the expression returns
true
as you mentioned pretty much everywhere else (JShell, JDoodle, etc.).Do you know if there's a version tied to this optimization and how reliable it is? In other words, can I always assume
==
will work on strings like.equals()
?For instance, I just saw this code snippet which apparently doesn't leverage interning:
I think string pooling generally does not apply when the variable is created using ... = new String("bla");
In your example :
String a = new String("Leroy");
String b = new String("Leroy");
a == b // this is now false;
Here is a good article on this specific topic : baeldung.com/java-string-pool
Awesome! Thanks, I've updated the italicized bit.
No problem. Have a great day !