DEV Community

Discussion on: Primitive Types and Variables in Java

Collapse
 
ivenk profile image
iven_k

Hi Jeremy,
first let me say : great article !

However I was wondering about your addition to the text (italic). You say that the first string example evaluates to true when using an online compiler or an IDE. I tried that and as far as i can tell it always evaluates to true as string pooling is a default optimization of the jvm and it performs a lot of pooling for different data types in order to optimize performance. I don't really understand how the IDE would come into effect here.

Collapse
 
renegadecoder94 profile image
Jeremy Grifski • Edited

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:

DrJava Interactions Pane String Equality

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:

String s1 = "Test";
String s2 = new String("Test");
System.out.println(s1 == s2); // Prints false
Collapse
 
ivenk profile image
iven_k • Edited

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

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

Awesome! Thanks, I've updated the italicized bit.

Thread Thread
 
ivenk profile image
iven_k

No problem. Have a great day !