基本类型转换

转换问题

		int i = 128;
        byte b = (byte) i;
        System.out.println(i);// 128
        System.out.println(b);// -128 byte的范围是127~-128,超出的就-128
        double d = i;
        System.out.println(d);// 128.0

在java中,类型转换分为两种,强制转换自动转换

  • 强制转换:高类型---->低类型 需要在在高类型方写低类型变量名,如上面的:

byte b = (byte) i;

  • 自动类型转换:低类型--->高类型 转换如其名,自动转换,如上面的:

double d = i;

注意点:

  1. 不能对布尔类型进行转换;
  2. 不能把对象类型转换成不相干的类型;
  3. 把高容量转换成低容量时,强制转换;
  4. 转换的时候可能存在内存溢出或者精度问题,需要注意;

		System.out.println((int) 23.7);//23
        System.out.println((int)-45.89F);//-45
        char c = 'a';
        int s = c + 1;
        System.out.println(s);//97
        System.out.println((char) s);//b     
  • 浮点数转换成小数时,取模舍去精度;
  • char类型可以自动转换成int类型,int类型可以强制转换成char类型

		//JDK1.7新特性,数字之间可以用下划线'_'分割
		int money = 10_0000_0000;
        int years = 20;
        int total = money * years;
        System.out.println(total);//-1474836480 
        long total2 = money * years;
        System.out.println(total2);//-1474836480 
        long total3 = money *((long) years);
        System.out.println(total3);////20000000000
  • total为负数,因为当money * years 之后得到值超出int类型的范围,内存溢出,故为负数
  • total2为负数,因为当money * years 之后得到是int类型为负数,再从int类型的负数自动转换成long类型,所以得到的结果还是负数
  • total3正确,在计算money * years之前,将years强制转换成long类型,会使得money * years计算的结果也为long类型,没有超出long类型的范围,所以正确。
刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
原文地址:https://www.cnblogs.com/xd-study/p/12828506.html