请教大家一个问题,,,
public class IntegerTest { public static void main(String[] args) {
short short_test;
int int_test;
float float_test;
short_test=100;//为什么这个可以编译通过? 100默认不是int 类型的吗?
//float_test=1.2;
int_test=50;
short_test=int_test;//为什么这个就会报非运行时异常.
System.out.println(short_test);
}
百度上我也搜了 ,都没有从问题的本质出发,我想知道他们底层是怎么实现的. 顺便也分析下byte 谢谢.
public class IntegerTest { public static void main(String[] args) {
short short_test;
int int_test;
float float_test;
short_test=100;//为什么这个可以编译通过? 100默认不是int 类型的吗?
//float_test=1.2;
int_test=50;
short_test=int_test;//为什么这个就会报非运行时异常.
System.out.println(short_test);
}
百度上我也搜了 ,都没有从问题的本质出发,我想知道他们底层是怎么实现的. 顺便也分析下byte 谢谢.
照你这么说,short类型就没法赋值了?
short s = 1;不是一样的道理?
只要在short的范围以内,就可以直接赋值。short_test=int_test;//为什么这个就会报非运行时异常.
int_test是一个变量,编译期只知道这是一个int,又不知道这个int到底是多大,那么,到底short到底能不能容下这个int呢?编译器崩溃了!编译期不是神啊!
照你这么说,short类型就没法赋值了?
short s = 1;不是一样的道理?
只要在short的范围以内,就可以直接赋值。short_test=int_test;//为什么这个就会报非运行时异常.
int_test是一个变量,编译期只知道这是一个int,又不知道这个int到底是……
++++
你这就是抬杠了,java语法就规定了,float必须带上f,short可没有这么规定。
eg:
byte b =127; //ok
byte b = 128;//error code
byte b =(byte)128//ok,结果是-128,因为强制转换丢失了精度
float float_test=1.2
这样子赋值是不可以的,尽管1.2在float所能表示的取值范围内,因为整数和小数的二进制表示不一样
eg:
byte b1=1;
把一赋值给byte型变量,用32位表示的int 1是前面31个0,最后一个为1
用byte来存储的时候,取32位的低8位,即 0000 0001,大小没有改变为什么小数不行,建议你自己去看看小数的二进制表示咯 有些东西可以当作规律或者语法记下来,没必要追根究底,因为有些东西挖的太深,对我们初学者来说会很吃力呵呵
short 2个字节,16个bit
float int 4个字节,32个bit。所以应该是位数少的可以赋值给位数多的,多的不能赋值给位数少的,我是这样理解的,不知道对不对