类型转换

类型转换

1.代码块

 

package myaction;

public class Demo2 {
public static void main(String[] args) {
int i = 128;
byte b = (byte)i;  //内存溢出

/*强制转换            
* 格式:数据类型   变量 = (数据类型)变量、数据;
* 高--->低
*/

System.out.println(i); //128
System.out.println(b);  //-128
System.out.println("==========================");
//==================================================

//自动转换         低-->高
int a = 12;
double c = 13.5;
System.out.println(a);//12
System.out.println(c);//13.5

System.out.println("==========================");
//====================================================
/*注意点
* 1.不能对布尔值进行转换
* 2.不能把对象类型转换为不相干的类型
* 3.再把高容量转化为低容时,强制转化
* 4.转化的时候可能存在内容溢出,或精度问题*/
System.out.println((int)45.5);//45
System.out.println((int)78.4F);//78

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

char m = 'a';
int n = m + 1;
System.out.println(n);//98
System.out.println((char)n);//b

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

//操作比较大的数的时候,注意溢出问题
//JDK7新特性,数字之间可以使用下划线,用于方便观看,下划线不会被输出
int money = 1000000000;
int years = 20;
int total = money*years;
System.out.println(total);//-1474836480   计算溢出

long total1 = money*years;//默认是int ,转换之前已经存在问题了?
System.out.println(total1);

long total2 = money*((long)years);//最高类型有表达式中最高类型决定
System.out.println(total2);//20000000000

}

}

2.自动转换

  1. byte-->short-->int-->long-->float-->double

  2. char-->int

posted @ 2022-09-21 14:56  瞎皮  阅读(108)  评论(0)    收藏  举报