数据类型转换(重要!!!)
类型一:自动类型转换
-
定义:精度小的类型自动转换成精度大的数据类型
-
-
byte --> short --> int --> long --> float --> double
-
-
具体规则介绍(非常重要!!!)
-
(1)多种数据类型混合运算时,系统首先自动将所有数据转成容量最大的那种数据类型,然后进行计算
-
-
(3)(byte short)和 char 之间不会相互自动转换
-
-
>>>解释:只要是混合运算,无论出现了相同类型还是不同类型,只要出现了三个类型,计算的结果就是int 类型
-
-
(5)boolean 不参与转换
-
具体代码示例解释
public class AutoConvertDetail {public static void main(String[] args) {int n1 = 10; float d1 = n1 + 1.1F;byte b1 = 10; byte b2 = 1;byte b3 = 2;short s1 = 1;int s2 = b2 + s1;boolean pass = true;byte b4 = 1;short s3 = 100;int num200 = 1;float num300 = 1.1F;double num500 = b4 + s3 + num200 + num300; }
}
类型二:强制类型转换
-
1. 定义:精度大的数据类型转换成精度小的数据类型
-
-
3. 使用方法
-
(1)在变量值前面用小括号加数据类型
,例如:float a = (float)1.1
,注意在 Java 中小数默认是double类型,把一下精度大的赋值给精度小的必然报错
-
-
(3)可用括号改变优先级,例如对表达式的结果进行强制类型转换,double a = (float)(2.5*3+9)
,float
赋值给 duuble
属于是低精度赋值给高精度—>合法
-
-
1.char
类型可以保存int
的常量值,但布恩那个保存int
的变量值,需要强转(错误案例:int m = 100 , char c = m
,因为 int
赋值给 char
属于是高精度赋值给低精度,必然报错)
-
类型三:字符串类型转换
一、所有数据类型转字符串
System.out.println((数据)+ "")
如何理解?其实就是和空字符进行了拼接,而+
本身就表示字符串的拼接,结果必然是字符串
二、字符串转不同类型数据
注意:用到了类和方法,不好理解,直接上代码理解+记忆
public class StringToBasic {public static void main(String[] args) {int n1 = 100;float f1 = 1.1F;double d1 = 4.5;boolean b1 = true;String s1 = n1 + "";String s2 = f1 + "";String s3 = d1 + "";String s4 = b1 + "";System.out.println(s1 + " " + s2 + " " + s3 + " " + s4);String s5 = "123";int num1 = Integer.parseInt(s5);double num2 = Double.parseDouble(s5);float num3 = Float.parseFloat(s5);long num4 = Long.parseLong(s5);byte num5 = Byte.parseByte(s5);boolean b = Boolean.parseBoolean("true");short num6 = Short.parseShort(s5);System.out.println(num1);System.out.println(num2);System.out.println(num3);System.out.println(num4);System.out.println(num5);System.out.println(num6);System.out.println(b);System.out.println(s5.charAt(0));}
}
运行结果
100 1.1 4.5 true
123
123.0
123.0
123
123
123
true
1
注意点
-
1. 在char
转int
类型的时候
-
2. 字符 转 字符串:取第一个字符进行转换
小练习巩固
判断是否能够通过编译
-
第一组
-
short s = 12;
//ok
-
-
byte b = 10;
// ok
-
-
b = (byte)(b + 11);
// 正确,使用强转
-
-
char c = 'a';
//ok
-
-
float d = .314F;
//ok
-
-
第三组
-
byte b = 16;
//ok
-
-
short t = s + b;
// 错误 int -> short