To explain why the code prints such output, we might need to look into lower level:
I decompiled your code to bytecode level.
For the 1st line:
System.out.println((Integer.valueOf("5000") <= Integer.valueOf("5000")));
The bytecode is(useless information is removed):
LDC "5000"
INVOKESTATIC java/lang/Integer.valueOf (Ljava/lang/String;)Ljava/lang/Integer;
INVOKEVIRTUAL java/lang/Integer.intValue ()I
LDC "5000"
INVOKESTATIC java/lang/Integer.valueOf (Ljava/lang/String;)Ljava/lang/Integer;
INVOKEVIRTUAL java/lang/Integer.intValue ()I
IF_ICMPGT L1
You can see for the left part of <=
, JVM use Integer.valueOf function to convert the string to a Integer object. Then use Integer.intValue function to extract the inner value of this object(also called auto-unboxing). So, for the left part, we get an int
value.
The right part of <=
is the same as left part.
The last line IF_ICMPGT
, is to compare these two int values. So, the conclusion is if you are using <=
, Java compiler will do auto-unboxing for you and compare the inner int values.
For the 2nd line:
System.out.println((Integer.valueOf("5000") == Integer.valueOf("5000")));
The bytecode is(useless information is removed):
LDC "5000"
INVOKESTATIC java/lang/Integer.valueOf (Ljava/lang/String;)Ljava/lang/Integer;
LDC "5000"
INVOKESTATIC java/lang/Integer.valueOf (Ljava/lang/String;)Ljava/lang/Integer;
IF_ACMPNE L4
You can see the bytecode is different from the 1st line. It just convert string to Integer objects, but NOT auto-unboxing them. And because they are two individual objects, they must have different addresses(In the memory).
The last line IF_ACMPNE
is going to compare the addresses of these two Integer objects. So, the conclusion is if you are using ==
, Java compiler will do NOTauto-unboxing for you and compare the object addresses.
What's more
The Integer
class caches the Integer objects for range -128~127. It means if you pass a string with in this range, you will get the exactly same Integer object. Below code will print true:
System.out.println((Integer.valueOf("127") == Integer.valueOf("127"))); // true