Why does the code below return false for long3 == long2 comparison even though it’s literal.
public class Strings {
public static void main(String[] args) {
Long long1 = 256L + 256L;
Long long2 = 512L;
Long long3 = 512L;
System.out.println(long3 == long2);
System.out.println(long1.equals(long2));
}
}
Longis an object, not a primitive. By using==you’re comparing the reference values.You need to do:
As you do in your second comparison.
Edit: I get it … you are thinking that other objects act like
Stringliterals. They don’t*. And even then, you never want to use==withStringliterals either.(*Autobox types do implement the flyweight pattern, but only for values -128 -> 127. If you made your
Longequal to50you would indeed have two references to the same flyweight object. And again, never use == to compare them. )Edit to add: This is specifically stated in the Java Language Specification, Section 5.1.7:
Note that
longis not specifically mentioned but the current Oracle and OpenJDK implementations do so (1.6 and 1.7), which is yet another reason to never use==Outputs: