DEV Community

Cover image for string implementation in different jdk version
dongfangYH
dongfangYH

Posted on

string implementation in different jdk version

Why the output of this code in jdk11 is true but in jdk19 is false?

String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
cicirello profile image
Vincent A. Cicirello

I didn't try your code to confirm behavior you are seeing. However, the intern() method is documented the same in both Java 11 and Java 19 so your code should behave the same in both.

I believe what you indicate you see in Java 11 is the correct behavior. The javadocs indicate:

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java Language Specification.

So even without a call to intern your s4 should also be interned since it is initialized with a string literal "11". So correct result should be true as you are seeing in Java 11. Any version giving you false is a bug.

Collapse
 
wldomiciano profile image
Wellington Domiciano

In Java 11 your code prints false too and this is the expected behavior.

Remember that String is immutable and call intern() do not change the reference.

The operator == checks the reference and s3 is differente from s4.

The code below prints true.

System.out.println(s3.intern() == s4);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
linmingxing profile image
Star

i have tried,In Java 11 his code really prints true

Collapse
 
wldomiciano profile image
Wellington Domiciano • Edited

You is right! Sorry.

I ran your code in 2 ways:

First using the java command in source-file mode.

$ java -version
openjdk version "11.0.20" 2023-07-18
OpenJDK Runtime Environment Temurin-11.0.20+8 (build 11.0.20+8)
OpenJDK 64-Bit Server VM Temurin-11.0.20+8 (build 11.0.20+8, mixed mode)
$ java Test.java
false
Enter fullscreen mode Exit fullscreen mode

And the result was "false".

But when I ran it the second way, compiling with javac and running with java in normal mode, the result was "true". Look:

$ javac -version
javac 11.0.20
$ java -version
openjdk version "11.0.20" 2023-07-18
OpenJDK Runtime Environment Temurin-11.0.20+8 (build 11.0.20+8)
OpenJDK 64-Bit Server VM Temurin-11.0.20+8 (build 11.0.20+8, mixed mode)
$ javac Test.java && java Test
true
Enter fullscreen mode Exit fullscreen mode

Now I was confused too. I believe it's just a bug. I also tested with Java 17 and 20 and both print "false".