I've been using JShell a bit just to test it out, and today I came across quite the interesting bit of behavior.
jshell> String a = "A"
a ==> "A"
jshell> String b = "A"
b ==> "A"
jshell> a == b
$4 ==> true
jshell> "A" == "A"
$5 ==> true
I was first wondering if this was a feature of Java 9, and I checked it out by compiling and running this program with Java 9
public class Equus {
public static void main(String... args) {
String a = "A";
String b = "A";
System.out.println("a == b");
System.out.println(a == b);
System.out.println("\"A\" == \"A\"");
System.out.println("A" == "A");
}
}
And interestingly enough I got
a == b true "A" == "A" true
As my output as well. What's going on here? Why are a
and b
equal to each other and why is "A" == "A"
true?