day9 Java基础——类型转换
不同类型的数据不能运算:
怎么办?转换数据类型:
public class demo05 {
public static void main(String[] args) {
int i = 128;//高
byte b = (byte)i;//低
//输出i,b
System.out.println(i);
System.out.println(b);
}
}
128
-128
进程已结束,退出代码为 0
转换后b竟然变成负数了!why?
原因byte范围是 -128~127,128会内存溢出
而(类型)变量名
这种为强制转换,从高到低要强制转换,反之从低到高则可自动转换,无需强制转换:(就像水桶一样,小水桶的水能自然装入大水桶,而大水桶的水只能强制装入小水桶,而水多了自然就溢出了)
自动转换:
public class demo05 {
public static void main(String[] args) {
int i = 128;//低
double b = i;//高
//输出i,b
System.out.println(i);
System.out.println(b);
}
}
128
128.0
进程已结束,退出代码为 0
注意点:
- 不能对布尔值进行转换
- 不能把对象类型转换为不相干的类型(👨不能转换成🐖,但👨可以转换成👩)
- 在把高容量转换到低容量的时候,必须强制转换,反之不用
- 转换的时候可能存在内存溢出或是精度问题
public class demo05 {
public static void main(String[] args) {
System.out.println((int)23.7);//小数转整数
System.out.println((int)-45.89f);//浮点数转整数
}
}
23
-45
进程已结束,退出代码为 0
public class demo05 {
public static void main(String[] args) {
char c = 'a';
System.out.println(c);
int d = c+1;
System.out.println(d);
System.out.println((char)d);
}
}
a
98
b
进程已结束,退出代码为 0
操作比较大的数时,注意溢出问题
同时数字间可以用下划线分割:
public class demo06 {
public static void main(String[] args) {
int money = 1_000_000_000;
System.out.println(money);
}
}
1000000000
进程已结束,退出代码为 0
public class demo06 {
public static void main(String[] args) {
int money = 10_0000_0000;
System.out.println(money);
}
}
1000000000
进程已结束,退出代码为 0
public class demo06 {
public static void main(String[] args) {
int money = 10_0000_0000;
int years = 20;
int total = money*years;
System.out.println(total);
}
}
-1474836480
进程已结束,退出代码为 0
内存溢出了
那我用long呢?
public class demo06 {
public static void main(String[] args) {
int money = 10_0000_0000;
int years = 20;
long total = money*years;
System.out.println(total);
}
}
-1474836480
进程已结束,退出代码为 0
发现还是这个负数!
原因:先进行money*years这两个int类型相乘,结果默认为int类型,故转换成long类型之前已经出现int内存溢出的问题了。
那要怎么正确地总钱数算出呢?
只转换money或years其中之一就可以将整个表达式用long进行计算(当然两个都改也可以,多此一举罢了)
public class demo06 {
public static void main(String[] args) {
int money = 10_0000_0000;
int years = 20;
long total = money*((long)years);
System.out.println(total);
}
}
20000000000
进程已结束,退出代码为 0
最后再附上数据类型笔记: