java中数字的默认类型 [英] Default type for number in 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 callingA.test()
passing the integeri
. 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 anint
totest
overloads.
As matter of fact,Java
is strongly typed: variables have not a default type, they do have their assigned type.
这篇关于java中数字的默认类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!