简体   繁体   English

基本值的转换或数据类型转换

[英]casting or data type conversion of primitive values

a) If I write something like this in java 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)If I do a multiplication of long numbers such as: B)如果我做长数的乘法,例如:

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

I assume that long values do not get promoted to int because int is smaller,but also when I write 我假设长整数值不会因为int较小而被提升为int,而且在我编写时

long a=15; 长a = 15;

Java would have interpreted the literal as an int because there is no 'l' with 15 in assignment,if java had interpreted it as int why can't it multiply interpreting it as of int data types Java会将字面量解释为int,因为赋值中不存在带15的“ l”,如果Java将其解释为int,为什么它不能将解释为int数据类型的值相乘

int d=a*b; 

Why should this give an error? 为什么要给出错误?

Does java not take into consideration the int value in case of any arithmetic operation of long variables ? 在对长变量进行任何算术运算的情况下,java是否不考虑int值?

Why java allows long a=15; 为什么Java允许long a = 15; interpreting it as int when I can't do any operation on it as int . 当我无法对它进行任何操作时,将其解释为int。

This is due to the fact that java converts upwards but not downward. 这是由于java向上转换而不向下转换的事实。 It will convert to something bigger by adding space but by reducing space you might have loss of data therefore java will not do it. 通过增加空间,它将转换成更大的东西,但是通过减少空间,您可能会丢失数据,因此java不会这样做。 It will take your small number like 15 into a long but this is a waste of memory to do so if your never going to fill in the space a long uses. 这样会使您的小数(例如15)变成一个长整数,但是如果您从不填充长时间使用的空间,这样做会浪费内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM