2016-07-21 59 views
1

a)如果我用Java编写铸造或数据类型转换

short a = 15 
short b = 3; 
short c = a * b;//will not compile 

I know it will not compile because short values are automatically 
promoted to int with the resulting value of type int so this will compile: 

int d=a*b ; //compile 

乙像这样)如果我做长的数字,如一个乘法:

long a=15; 
long b=3; 
long c=a*b;//will compile 
int d=a*b;//will not compile 

我假定那长的值不会被提升为int,因为 int更小,而且当我写时

long a = 15;

的Java会解释文字为int,因为没有“L”与15的分配,要是Java的解读是,INT为什么不能乘其解释为整型数据类型

int d=a*b; 

为什么要给出错误?

在长变量的任何算术运算的情况下,java是否没有考虑int值?

为什么java允许long a = 15;当我不能对int做任何操作时将它解释为int。

回答

2

这是由于java向上转换而不向下转换的事实。它会通过增加空间转换为更大的东西,但通过减少空间可能会丢失数据,因此java不会这样做。它会让你的小数字变成15,但如果你永远不会填满长期使用的空间,这样做会浪费内存。

+0

感谢您的答复。只需添加到上面我假定以下不应该工作:float num1 = 4,num2 = 5; float result = num1 + num2;但它并不像在上述问题 –

+0

中添加两个短数字那样,所以在这里将会丢失数据。 –