Thursday 27 May 2021

Java Comparison for Beginners

So, we all know about boxing and unboxing in Java, and the fact that we have "int" which is a primitive, and we have "Integer" which is an Object.

So, when comparing "int", we can use ==. When comparing "Integer" it's better to use .equals().

It may seem like it works, but this is only for small values that are cached in the JVM. Do not rely on that!

See the following example:

So, what happens when using different comparisons? let's explain the test below:

It works fine! Exactly as we would expect.

In short, according to the JLS1, first unboxing takes place, in order to be able to compare two primitives.

Then a widening primitive conversion2 takes place, in this case the int will be converted up to type long.

Now the comparison can take place.

References

[1] JLS Java 16 - 15.20. Relational Operators
https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.20
[2] JLS Java 16 - 5.6. Numeric Contexts
https://docs.oracle.com/javase/specs/jls/se16/html/jls-5.html#jls-5.6

No comments:

Post a Comment