What is the output of the following application?
public class Main { public Main() { super(); } public int m(int v) { return 5; } public int m(short v) { return 2; } public int m(long v) { return 11; } public static void main(String[] path) { System.out.print(new Main().m((byte)2+1)); } }
A.
The code compiles without issue, so Option D is incorrect.
In the main()
method, the value 2 is first cast to a byte.
It is then increased by one using the addition + operator.
The addition + operator automatically promotes all byte and short values to int.
The value passed to the m()
in the main()
method is an int.
The m(int) method is called, returning 5 and making Option A the correct answer.
Note that without the addition operation in the main()
method, byte would have been used as the parameter to the m()
method, causing the m(short) to be selected as the next closest type and outputting 2, making Option B the correct answer.