I saw this one question in scjp preparation book.
public class Yikes {
public static void go(Long n) {
System.out.println("Long ");
}
public static void go(Short n) {
System.out.println("Short ");
}
public static void go(int n) {
System.out.println("int ");
}
public static void main(String [] args) {
short y = 6;
long z = 7;
go(y);
go(z);
}
}
The output is int Long.
I am passing short datatype variable to overloaded method go. Now go has a short datatype version also. Then how come the one with int is getting invoked? What is the reason for this behaviour?
I am quite new in java. So please help me here.
Since there is no method go(short s) to choose, Java has to choose another one. This can be done in two ways:
short to an int
short with a Short, the corresponding wrapper class.Since widening has been around longer than autoboxing (introduced in Java 5), the JVM chooses this alternative first if available.
Therefore, the go(int n) method is invoked.
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