0

Explain me please, why, when I write 4 overloaded methods and call it => it chooses method with 'int' as default, but not 'byte', which is closer/better, because it can storage values from -127 to 128?

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

    public static void method(byte b) {
        System.out.println("byte");
    }

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

    public static void method(long l) {
        System.out.println("long");
    }

    public static void main(String[] args) {
        // put your code here
        method(10);
    }
}
  • When you called it, what was the type of variable you passed, or what did you pass? Btw, `byte` is -128 to 127. :) `int` is considered to be the "natural" word size of the system. – lurker Apr 27 '20 at 19:38
  • 1
    Integer literals are interpreted as ints by default because they're more widely used, I guess, since they don't take up too much space and aren't as small as bytes. – user Apr 27 '20 at 19:39
  • Does this answer your question? [overloading method priority in java](https://stackoverflow.com/questions/22590914/overloading-method-priority-in-java) – dawis11 Apr 27 '20 at 19:40
  • thank you all for answers, it was really fast! now i understand, how it works :) – mactepdzen Apr 27 '20 at 19:53

2 Answers2

6

Because the Java Language Specification says so.

Section 3.10.1. Integer Literals says:

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

So your numeric literal 10 is of type int.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

It's because default type of number's literal is integer. To specify long literal you should add L at the end. To specify byte literal - you should cast the value