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

Thursday, 20 May 2021

Java Inheritance for Beginners

Just a little exercise, to get things in perspective.

Besides, I thought I was being clever, but made a rookie mistake and it just didn't work1.

Something similar can be found in Java Puzzlers2.

During compile time a decision is made which method is to be called (§15.12)3. During compile time it is as yet unknown which type/subtype it will be. The compiler tries to be as specific as possible, but in this case, it will just be Animal in the second testcase.

References

[1] Stackoverflow - Overloaded method selection based on the parameter's real type
https://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type
[2] Java Puzzlers - Traps, Pitfalls, and Corner Cases - By Joshua Bloch and Neal Gafter
http://www.javapuzzlers.com/
[3] JLS 16 - 15.12. Method Invocation Expressions
https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.12