在类型转换的时候要非常小心,有些是编译时错误,简单些,有些是运行时错误,要特别注意。
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public class ConvTest {
public static void main(String[] args) {
Integer i1 = 1; String s1 = String.valueOf(i1); System.out.println(s1);
String s2 = "1"; Integer i2 = Integer.valueOf(s2); System.out.println(i2);
int i22 = Integer.parseInt(s2); System.out.println(i22);
Object o3 = 1; Integer i3 = (Integer) o3; System.out.println(i3);
Object o6 = "1"; String s6 = (String) o6; System.out.println(s6);
Object o4 = "1"; if (o4 instanceof Integer) { System.out.println("Integer"); } else if (o4 instanceof String) { System.out.println("String"); }
Object o7 = 1; String s7 = String.valueOf(o7); System.out.println(s7); } }
|