java中数字的默认类型 [英] Default type for number in java

查看:84
本文介绍了java中数字的默认类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Java int中的数字的默认类型?如下例所示:



Why is default type for number in Java int? As in this example:

class TestClass {
    public static void main(String args[] ) throws Exception {
        A a = new A();
        a.test(5);
    }
}
class A{
    void test(short a){
        System.out.println("Short");
    }
    void test(int a){
        System.out.println("Integer");
    }
    void test(byte a){
        System.out.println("Byte");
    }
}

它打印整数..我的问题是为什么Java中的数字int的默认类型?



我尝试过:



数值的默认类型

It prints Integer.. My question is "Why is default type for a number int in Java"?

What I have tried:

Default type for numerical value

推荐答案

您正在调用 A.test()传递整数 i 。这不是默认类型,而是由您的代码定义:

You are calling A.test() passing the integer i. That is not a default type but defined by your code:
int i = sc.nextInt();










引用:

先生我修改了代码以传递5而不是int i ..我得到的是Integer

Sir I modified the code to pass 5 instead of int i.. I am getting Integer

5是一个数字整数字面值。

是的,当没有时在文字中键入提示,它是 int

如果它有一个'L'后缀,它是很长

5 is a numerical integer literal.
Yes, when there is no type hint in the literal, it is an int.
If it has an 'L' postfix, it is a long:

a.test(5L);



如果文字包含句号或指数,它是 double

如果它有一个'F'后缀,它是一个浮点数



如果你想把它当作不同的类型,你也可以使用铸造:


If the literal contains a period or an exponent, it is a double.
If it has an 'F' postfix, it is a float.

If you want to treat it as different type you can also use casting:

a.test((short)5);

[/ EDIT]


嗯。

这是一个线索:

Um.
Here is a clue:
int i = sc.nextInt();
...
a.test(i);

你明确地将 i 声明为整数,所以可以理解,它将它视为整数!

You specifically declare i as an integer, so pretty understandably, it treats it as an integer!


您的代码不能证明这一点。

您传递的是 int test 重载。

事实上, Java 是强类型的:变量没有默认类型,它们的已分配类型。
Your code doesn't prove that.
You are passing an int to test overloads.
As matter of fact, Java is strongly typed: variables have not a default type, they do have their assigned type.


这篇关于java中数字的默认类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆