long data type java_java Long data type comparison

Long is an object, not a primitive. By using == you compare the reference value.

You need to do:

if(str.equals(str2))

As you compare in the second time.

EDIT: I get it...you think other objects behave like string literals. they do not*. Even then, you don't want to use == with String literals.

(* The Autobox type implements the flyweight pattern, but only with values ​​-128 -> 127. If you make your Long equal to 50, you will have two references to the same flyweight object, again, don't use == to compare them.)

Edited to add: This is in the Java Language Specification, Section 5.1.7:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Note, long is not specifically mentioned, but current Oracle and OpenJDK implementations do (1.6 and 1.7), which is another reason not to be used anymore ==

Long l = 5L;

Long l2 = 5L;

System.out.println(l == l2);

l = 5000L;

l2 = 5000L;

System.out.println(l == l2);

output:

true false

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324218629&siteId=291194637