案例1:
请问以下的代码有没有问题
double d = 12.34;
float f = d;
public class DataTypeDemo1 {
public static void main(String[] args) {
double d = 12.34;
float f = d;
}
}
运行结果:
案例2:
看程序说明有没有问题,这两个有什么区别呢?
float f1 = (float)12.34;
float f2 = 12.34F;
public class DataTypeDemo1 {
public static void main(String[] args) {
double d = 12.34;
System.out.println(d);
float f1 = (float)12.34;
float f2 = 12.34F;
System.out.println(f1);
System.out.println(f2);
}
}
运行结果:
12.34
12.34
12.34Process finished with exit code 0
f1其实是通过double类型进行强制类型转换过来的
f2本身就是一个float类型
案例3:
byte b1=3,b2=4,b;
b=b1+b2;
b=3+4;
哪句是编译失败的呢?为什么呢?
public class DataTypeDemo2 {
public static void main(String[] args) {
byte b1=3,b2=4,b;
// b=b1+b2;
b=3+4;
}
}
第二句语句会出现问题,b=b1+b2是有问题的。
1、变量相加,首先会看类型问题,最终把结果的赋值也会去考虑类型问题,因为byte,short,char他们参与运算首先转换为int类型。
2、常量之间相加,首先会做加法运算,然后看这个结果是不是在接收数据类型的范围内,如果在,就直接赋值,不会报错。
案例4:
byte b = 130;有没有问题?如果我想让赋值正确,可以怎么做?
结果是多少呢?
练习:byte b = 300;
public class DataTypeDemo3 {
public static void main(String[] args) {
byte b = (byte)132;
System.out.println(b);
}
运行结果: -124 Process finished with exit code 0
分析过程: 首先,我们要想知道结果是什么,就得明白计算机内部是 如何计算的。 我们知道计算机中的数据运算都是通过补码进行的。 想要得到补码,就必须知道反码,原码。 而要想知道原码,就必须知道对应的二进制。 1、计算出130这个数据的二进制 整数默认是int类型,占4个字节 00000000 00000000 00000000 10000010 这就是130的原码,也是反码,和补码 2、强制类型转换(做了截取操作) 10000010 这个结果是补码 3、已知补码求原码 符号位 数值位 补码: 1 0000010 反码: 1 0000001 原码: 1 1111110 把原码1111110换算成十进制 64 + 32 + 16 + 8 + 4 + 2 = 126 由于符号位是1,所以结果是-126
案例5
看程序写结果:
System.out.println(‘a’);
System.out.println(‘a’+1);
System.out.println(“hello”+’a’+1);
System.out.println(‘a’+1+”hello”);
System.out.println(“5+5=”+5+5);
System.out.println(5+5+”=5+5”);
public class DataTypeDemo4 {
public static void main(String[] args) {
System.out.println('a'); //a
System.out.println('a'+1); //98
System.out.println("hello"+'a'+1); //helloa1
System.out.println('a'+1+"hello"); // 98hello
System.out.println("5+5="+5+5); //5+5=55
System.out.println(5+5+"=5+5"); //10=5+5
System.out.println(1+1);//2
System.out.println('a'+1);//98
System.out.println("你好"+3);//你好3
}
}
运行结果:
a
98
helloa1
98hello
5+5=55
10=5+5
2
98
你好3Process finished with exit code 0
字符串数据和其他数据做+,此时这里的+不是做加法运算,而是
字符串连接符,结果依旧是字符串。
当+两边是数字或者一边是数字,一边是字符,此时的+是做加法运算的。
案例6:
面试题
short s=1, s = s+1;
short s=1, s+=1;
上面两个代码有没有问题,如果有,那里有问题
public class OptFuZhiDemo2 {
public static void main(String[] args) {
short s=1;
// s = s+1;
short s1=1;
s1+=1;
}
}
s+=1,底层进行了转换,但是不是我们想当然的转化为s = s+1 而是转化成了 s = (s的数据类型)(s+1) 默认包含了强制类型转换。 float f = (float)12.34
到底啦!再看看博主别的文章吧!感谢大家的支持!欢迎大家在下方评论。