1
public static void main(String[] args) {
    methodA(5);
}

public static void methodA(int i) {
    System.out.println("int method " + i);
}

public static void methodA(short s) {
    System.out.println("short method " + s);
}

The output of the above java program is

int method 5

So, when passing 5 as an argument, why method with int argument is called instead of short.

After casting the argument to short, the method with a short argument will be called.

methodA((short)5);

When I pass 5, why java considers it as int, whereas, for short I have to cast it? Considering, for short datatype, number range is -32,768 to 32767.

lovul
  • 11
  • 1
ChandraBhan Singh
  • 2,841
  • 1
  • 22
  • 27

3 Answers3

3

5 is an int literal, and therefore it's an int, not a short.

k_ssb
  • 6,024
  • 23
  • 47
Ahorn
  • 649
  • 4
  • 19
  • Also worth reading this https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html to know actually why and what it means. – miiiii Oct 05 '18 at 08:31
0

Because by default this is how Java works when you pass raw data like that it always sees it as an int, or String if it's ("" e.g). And so by default, it calls the method with the int value as input.

That's why you should always assign the raw data to values before passing them, so confusions like that won't occur.

Sumesh TG
  • 2,557
  • 2
  • 15
  • 29
Sir. Hedgehog
  • 1,260
  • 3
  • 17
  • 40
0

The default size of an Integer or Integer constant is 4 byte whereas short is 2 byte. You can do the following.

      long t = 5;

because widening primitive conversion does not loos information.

for the following, you need to cast because narrowing primitive conversion loos information and magnitude. compiler make sure that you are doing it purposely.

     short t = (short)5;
Pandey Amit
  • 657
  • 6
  • 19