首页 > 其他 > 详细

类型转换

时间:2021-07-17 23:45:40      阅读:30      评论:0      收藏:0      [点我收藏+]

类型转换

 

```java
public class Demo05 {
public static void main(String[] args) {
int i = 128;
byte b = (byte)i; //内存溢出 尽量低转换到高


//强制转换 (类型)变量名 高——>地

System.out.println(i);
System.out.println(b);


//自动转换 低--->高
int i2 = 128;
double b2 = i;

System.out.println(i2);
System.out.println(b2);

/*注意点
1. 不能对布尔值进行转换
2. 不能把对象类型转换到低容量的时候,强制转换
3. 在把高容量转换到低容量的时候,强制转换
4. 转换的时候可能存在内存溢出,或者精度问题!
*/

System.out.println("====================");
System.out.println((int)148.4); //148
System.out.println((int)-148.44f); //-148 精度丢失

System.out.println("====================");
char c = ‘a‘;
int d = c+1;
System.out.println(d); //自动转换
System.out.println((char)d);


}
}
```

```java
public class Demo06 {
public static void main(String[] args) {
//操作比较大的数的时候,注意溢出问题
//JDK7新特性,数字之间可以用下划线分割
int money = 10_0000_0000;

System.out.println(money);
System.out.println("====================================");
int years = 20;
int total = money*years; //-1474836480 溢出
System.out.println(total);

System.out.println("====================================");

long total2 = money*years; //默认是int,之后再转换为long 计算时已经溢出了
System.out.println(total2); // -1474836480

long total3 = money*((long)years); //先把一个数转换为long
System.out.println(total3);

//L l 最好写成大写的L

 


}
}
```

 

类型转换

原文:https://www.cnblogs.com/yizhifei/p/15025266.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!