Short and int behavior in java

I saw this one question in the scjp tutorial.

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 pass the short datatype variable to the overloaded go method. You now have a short version. Then, how is the call with int called? What is the reason for this behavior?

I am new to java. So please help me here.

+6
source share
1 answer

Since go(short s) does not exist to select a method, Java must choose another. There are two ways to do this:

  • Extension, extension short to int
  • Autoboxing surrounding short with short matching wrapper class.

Since the extension was longer than autoboxing (introduced in Java 5), ​​the JVM first chooses this alternative, if available.

Therefore, the go(int n) method is called.

+9
source

Source: https://habr.com/ru/post/923786/


All Articles