Just wondered why is it possible to pass Integer as argument where method parameter is of int type and vice versa?
public class Salmon {
public static Integer foo(Integer a, int b){
return a - b;
}
public static void main(String[] args) {
Integer a = 10;
int b = 1;
foo(b, a);
}
}
Because you can set a double to an integer, then integer as argument is ok to function with double as parameter.
We can convert int to double in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly. It is also known as implicit type casting or type promotion.
This is auto-boxing and auto-unboxing. Basically the compiler puts in calls to Integer.valueOf()
or x.intValue()
appropriately.
The exact mechanism isn't actually specified, but the relevant sections of the spec are 5.1.7 and 5.1.8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With