显式/隐式转换
隐式转换相对安全,会自动将小瓶水装入大瓶
显式的转换是强制转换,可能你会丢失精度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public void testPrimitiveConversion() { System.out.println("=== 1. 基本类型转换 ===");
int smallInt = 100; double bigDouble = smallInt; System.out.println("int -> double (自动): " + bigDouble);
double pi = 3.9999; int piInt = (int) pi; System.out.println("double -> int (强制切掉小数): " + piInt);
int tooBig = 130; byte b = (byte) tooBig; System.out.println("int(130) -> byte (溢出): " + b); }
|
字符与数字
char 底层就是个数字,对应ascii码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @Test public void testCharToNumber() { System.out.println("\n=== 2. 字符与数字转换 ===");
char c = 'A';
int code = c; System.out.println("字符 'A' 对应的数字: " + code);
int code2 = 66; char c2 = (char) code2; System.out.println("数字 66 对应的字符: " + c2);
char lower = 'd'; char upper = (char) (lower - 32); System.out.println("'d' 变大写: " + upper); }
|
字符串与基本类型转换
string to 数字
Integer.parseInt(strPrice);
Double.parseDouble(strRate);
数字 to string
String.valueOf(age);
String s2 = age + “”;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public void testStringConversion() { System.out.println("\n=== 3. String 与基本类型互转 ===");
String strPrice = "128"; String strRate = "3.14";
int price = Integer.parseInt(strPrice); double rate = Double.parseDouble(strRate);
System.out.println("计算结果: " + (price * rate));
int age = 18;
String s1 = String.valueOf(age);
String s2 = age + "";
System.out.println("数字转字符串 s1: " + s1); System.out.println("数字转字符串 s2: " + s2); } }
|