Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of short and int in java

Tags:

java

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.

like image 790
Shades88 Avatar asked Aug 26 '12 13:08

Shades88


1 Answers

Since there is no method go(short s) to choose, Java has to choose another one. This can be done in two ways:

  1. Widening, widening the short to an int
  2. Autoboxing, surrounding the 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.

like image 156
Keppil Avatar answered Oct 23 '22 09:10

Keppil