Java编译器为什么将长数据类型默认为Double而不是Integer?

问题描述 投票:0回答:1

我是Java新手,在测试一些代码时偶然发现了这一点。 Java为什么将x(数据类型为long)传递给采用双参数而不是带整数参数的函数。如果有人可以向我解释原因(即使对大多数人来说这是一个简单的问题!),我将不胜感激。

public class Hello {
public static void main (String [] args) {
    long x=1;
    System.out.println("Before calling the method, x is "+x);
    increase(x);
    System.out.println("After calling the method, x is "+x);
    System.out.println();

    double y=1;
    System.out.println("Before calling the method, y is "+y);
    increase(y);
    System.out.println("After calling the method, y is "+y);


}

public static void increase(int p) {
    p+=1;
    System.out.println(" Inside the method is "+p);

}

public static void increase(double p) {
    p+=2;
    System.out.println(" Inside the method is "+p);

}   }
java long-integer
1个回答
1
投票

您有2个int和double作为输入参数的gain()重载方法。另外,您正在将输入参数传递为长类型。

在Java中,UpCasting以以下格式发生。

byte -> short -> int -> long -> float -> double

因此,当您将long类型值作为输入参数传递时,编译器首先会在输入参数中查找完全匹配。如果找不到,它将转换为下一个值。

因此,具有双值输入参数的方法可以接受长值

© www.soinside.com 2019 - 2024. All rights reserved.