JavaChallenge47
#MethodOverloading #varargs #int #long #short #Integer #autoboxing
1. challenge(Integer)
2. challenge(short)
3. challenge(long)
4. challenge(int ...)
5. Compliation will fail.
Please try to solve the challenge by yourself first.
The challenge is about overloading and autoboxing. You have already solved similar problems of overloading. Here we need to find out whether the compiler has clarity about which method it has to call. So the clarity will come if the compiler can figure out the autoboxing logic here otherwise compilation will fail.
Simply, challenge(short i)
is out of the scope because the passed value which is 10 is an int value and can not be cast to short.
So the question arises as —
Why compiler considered 10 as int not short?
(Almost) All operations on byte
, short
will promote them to int
, for example, you cannot write: —
short x = 1;
short y = 2;
short z = x + y; //error
But why???
So to go one level deeper: The answer may simply be related to the Java Virtual Machine Instruction Set. As summarized in the Table in the Java Virtual Machine Specification, all integral arithmetic operations, like adding, dividing, and others, are only available for the type int
and the type long
, and not for the smaller types so we end up converting byte/short to int.
Similarly, challenge(int...)
method is out of confusion because challenge(10)
call has only one value so more likely it will go to other methods unless an explicit cast is required.
Now, there is a competition between challenge(Integer i) and challenge(long i).
There is a very good article on Baeldung which explains why Java needs to prefer primitive over reference type. Because of multiple reasons such as —
- Memory efficient.
- Faster operations
https://www.baeldung.com/wp-content/uploads/2018/08/plot-benchmark-primitive-wrapper-3.gif
In our case primitive long takes 64 bits while reference Integer takes 128bits so because of memory optimization, challenge(long i)
method will be called and it will print out challenge(long)
.
Thanks
Do subscribe the publication for more such java challenges.