开发者

why the method with int parameter is considered for numerical value?

class Test {
  void m1(byte b) {
    System.out.print("byte");
  }

  void m1(short s) {
     System.out.print("short");
  }

  void m1(int i) {
     System.out.print("int");
  }

  void m1(long l) {
     System.out.print("long");
  }

  public static void main(String [] args) {
    Test test = new Test();
    test.m1(2);
  }
}
开发者_StackOverflow社区

The output is : int. why does jvm consider the method with int parameter?


Because integer literals are of type int in Java. You'll need an explicit cast if you want to call the other ones. (Or add a L suffix if you want to call the long version.)

See the JLS Lexical Structure §3.10.1 Integer Literals for the details.


Data       Type          Default Value (for fields)
byte        0
short       0
int         0
long        0L
float       0.0f
double      0.0d
char       '\u0000'
String (or any object)      null
boolean false

So you need to explicitly to give the number as parameter to the appropriate primitive type you want

If you try giving

 public static void main(String [] args) {
    Test test = new Test();
    test.m1(2L);
  }

The output will be long

In case of short or byte (implicit is int), you will need a cast to that type

public static void main(String [] args) {
        Test test = new Test();
        test.m1((short)2);
      }

Reference: Primitive Data Types in Java

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜