📚 类型转换概述
1. Java数据类型层次
数值类型
|
---------------------------------
| |
整型类型 浮点类型
| |
----------- -----------
| | | |
byte short float double
| |
char int
|
long
2. 两种类型转换
🔄 自动类型转换(隐式转换)
1. 转换规则(从小到大)
byte → short → int → long → float → double
↑
char
2. 自动转换示例
public class AutoConversion {
public static void main(String[] args) {
byte b = 10;
short s = b;
int i = s;
long l = i;
System.out.println("b=" + b + ", s=" + s + ", i=" + i + ", l=" + l);
int intValue = 100;
float f = intValue;
double d = f;
System.out.println("intValue=" + intValue + ", f=" + f + ", d=" + d);
char c = 'A';
int charToInt = c;
System.out.println("c=" + c + ", charToInt=" + charToInt);
byte b1 = 10;
byte b2 = 20;
int result = b1 + b2;
System.out.println("result=" + result);
int x = 10;
long y = 20L;
float z = 30.5f;
double w = 40.5;
double total = x + y + z + w;
System.out.println("total=" + total);
}
}
🚨 强制类型转换(显式转换)
1. 基本语法
目标类型 变量名 = (目标类型) 源变量或表达式
2. 整型之间的强制转换
public class IntegerCast {
public static void main(String[] args) {
int intValue = 300;
byte byteValue = (byte) intValue;
System.out.println("intValue=" + intValue + ", byteValue=" + byteValue);
long longValue = 1234567890123L;
int intFromLong = (int) longValue;
System.out.println("longValue=" + longValue + ", intFromLong=" + intFromLong);
int negativeInt = -100;
byte negativeByte = (byte) negativeInt;
System.out.println("negativeInt=" + negativeInt +
", negativeByte=" + negativeByte);
int safeInt = 100;
byte safeByte = (byte) safeInt;
System.out.println("safeByte=" + safeByte);
}
}
3. 浮点型与整型的强制转换
public class FloatIntegerCast {
public static void main(String[] args) {
double d = 123.456;
int i = (int) d;
System.out.println("d=" + d + ", i=" + i);
float f = 78.9f;
int i2 = (int) f;
System.out.println("f=" + f + ", i2=" + i2);
double price = 99.99;
int rounded = (int) Math.round(price);
System.out.println("price=" + price + ", rounded=" + rounded);
double value = 56.78;
int rounded2 = (int) (value + 0.5);
System.out.println("value=" + value + ", rounded2=" + rounded2);
int bigInt = 123456789;
float floatFromInt = (float) bigInt;
System.out.println("bigInt=" + bigInt +
", floatFromInt=" + floatFromInt);
}
}
4. 精度丢失问题
public class PrecisionLoss {
public static void main(String[] args) {
double precise = 3.1415926535;
float lessPrecise = (float) precise;
System.out.println("double: " + precise);
System.out.println("float: " + lessPrecise);
int largeNumber = 123456789;
float floatNumber = largeNumber;
System.out.println("int: " + largeNumber);
System.out.println("float: " + floatNumber);
double d1 = 0.1;
double d2 = 0.2;
System.out.println("0.1 + 0.2 = " + (d1 + d2));
}
}