Why is a method with an int parameter considered for a 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);
  }
}

Conclusion: int. why does jvm consider a method with an int parameter?

+3
source share
2 answers

Because whole literals are of type intin Java. You will need an explicit cast if you want to call others. (Or add a suffix Lif you want to invoke the version long.)

See JLS Lexical Structure §3.10.1 Integer literals for details.

+9
source
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

Therefore, you need to explicitly specify the number as a parameter for the primitive type you need

If you try to give

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

The output will be long

In the case of shortor byte(implicit is int), you need to cast to this type

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

Reference: Primitive Data Types in Java

+4
source

All Articles