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
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
internyours4should also be interned since it is initialized with a string literal "11". So correct result should betrueas you are seeing in Java 11. Any version giving youfalseis a bug.In Java 11 your code prints
falsetoo and this is the expected behavior.Remember that String is immutable and call
intern()do not change the reference.The operator
==checks the reference ands3is 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
javacommand in source-file mode.And the result was "false".
But when I ran it the second way, compiling with
javacand running withjavain 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".