Java 基本值的强制转换或数据类型转换
a) 如果我用java写这样的东西Java 基本值的强制转换或数据类型转换,java,types,type-conversion,Java,Types,Type Conversion,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 B) 如果
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
B) 如果我对长数进行乘法,例如:
long a=15;
long b=3;
long c=a*b;//will compile
int d=a*b;//will not compile
我假设长值不会提升为int,因为
int更小,但当我写的时候
长a=15
Java会将文本解释为int,因为赋值中没有带15的“l”,如果Java将其解释为int,为什么不能将其解释为int数据类型
int d=a*b;
为什么会出现错误
在长变量的算术运算中,java不考虑int值吗
为什么java允许长a=15;当我不能对它进行任何操作时,将它解释为int。这是因为java向上转换,而不是向下转换。通过增加空间,它将转换成更大的东西,但通过减少空间,您可能会丢失数据,因此java不会这样做。它会把你的小数字比如15变成一个长的数字,但是如果你永远都不去填补长时间使用的空间,那么这样做是浪费内存 感谢您的回复。为了补充以上内容,我假设以下内容不应该起作用:float num1=4,num2=5;浮动结果=num1+num2;但是,它不像上面问题中那样添加两个短数字,所以这里会丢失数据。