Relatively long and floating

i developed the code below

static String m(float i) {
    return "float";
}

static String m(double i) {
    return "double";
}

public static void main(String[] args) {
    int a1 = 1;
    long b1 = 2;
    System.out.print(m(a1) + "," + m(b1));
}

Both results print float, float, what is the reason for this, please report and how can I call twice, please report thanks.

+3
source share
4 answers

Try

    System.out.print(m(1f)+","+ m(2d));

why do you create an int and test it for a long time? Well, what actually happens is that both parameters are converted to float by default.

+3
source

The short answer: Java can automatically expand intand longup float, and doubles, but Java will choose an extension floatbecause it is smaller (in terms of memory) than double. You can invoke the method version of a doublemethod by explicitly passing an argument:

System.out.print(m((double)a1) + "," + m((double)b1));

:. Java ( ), , (, , ) . Java:

byte     1 byte
short    2 bytes
char     2 bytes
int      4 bytes
float    4 bytes
long     8 bytes
double   8 bytes

Java "" , Java . Java :

  • byte short, int, long, float double
  • short int, long, float double
  • char int, long, float double
  • int long, float double
  • long float double
  • float to double

, :

  • .
  • ; .
  • int long float long double .

, Java int long , , long , int (. 2). Java int float, . .

public static void foo(float f) {
    System.out.println(f);
}

public static void main(String[] args) {
    int a = 123;
    int b = 1234567890;
    foo(a);
    foo(b);
}

foo(float) "123.0", . int "123" float "123.0". "1.23456794E9", , 3. "1234567940" , , "1234567890".

, : , Java , , ( ), . , , , , , Java , .

int a long . Java m(float) m(double), , . int float double, float (4 ) , double (8 ), Java m(float). , long: float , , a long .

+7

If you want to invoke the version double, make it explicitly double:m((double)a1)

Take a look at JLS ยง8.4.9 - Method Overloading

+4
source

how can i call double?

Use variable double

double d = 3.3;
m(d);
+1
source

All Articles