Reputation: 1970
I am a bit confused about this topic, reason being in this code:
public class File
{
public static void main(String[] args)
{
numbers();
}
static void numbers(int...x)
{
System.out.println("Integers");
}
static void numbers(byte...x)
{
System.out.println("Byte");
}
static void numbers(short...x)
{
System.out.println("Short");
}
}
The output of this code is "Byte", and the reason is the most specific type is chosen, since among byte
, short
and int
the most specific type is byte
, that's why it is chosen.
But if I modify my code to-
public class File
{
public static void main(String[] args)
{
numbers(1, 4);
}
static void numbers(int...x)
{
System.out.println("Integers");
}
static void numbers(byte...x)
{
System.out.println("Byte");
}
static void numbers(short...x)
{
System.out.println("Short");
}
}
The output is "Integers", and I'm unable to figure out why? I know in case of arithmetic instructions byte
and short
are implicitly promoted to int
, but here we are calling a method with values which is within the range of byte
and short
, then how the method with int
arguments is invoked?
And also, if I comment out the method with int
arguments, then the code shows an error of no suitable method found. Why???
Upvotes: 2
Views: 55
Reputation: 73558
1
and 4
are integer literals. So the int...
version is called.
There are no byte
or short
literals, but if you were to call Numbers((byte)2, (byte)3);
the byte...
version would be called.
Upvotes: 4