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);
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);
For further actions, you may consider blocking this person and/or reporting abuse
Nikhil Soman Sahu -
Rohit -
Pizofreude -
Salad Lam -
Top comments (4)
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:
So even without a call to
intern
yours4
should also be interned since it is initialized with a string literal "11". So correct result should betrue
as you are seeing in Java 11. Any version giving youfalse
is a bug.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 ands3
is differente froms4
.The code below prints
true
.i have tried,In Java 11 his code really prints true
You is right! Sorry.
I ran your code in 2 ways:
First using the
java
command in source-file mode.And the result was "false".
But when I ran it the second way, compiling with
javac
and running withjava
in normal mode, the result was "true". Look:Now I was confused too. I believe it's just a bug. I also tested with Java 17 and 20 and both print "false".