低 ------------------------------------> 高 byte,short,char—> int —> long—> float —> double
低级变量可以直接转换成高级变量,称为自动类型转换,例如:
public class Test { public static void main(String[] args) { byte b = 1; int i = b; long l = b; float f = b; double d = b; System.out.println(i); System.out.println(l); System.out.println(f); System.out.println(d); char c ='c'; int n = c; System.out.println("output:"+ n); } }
上述代码可以正常编译通过,运行结果如下:
1 1 1.0 1.0 output:99
public class Test { public static void main(String[] args) { short i=98; char c=(char)i; System.out.println("output:"+c); i = 99; byte b = (byte) i; c = (char) i; float f = (float) i; System.out.println(b); System.out.println(c); System.out.println(f); } }
结果如下:
output:b 99 c 99.0
public class Test { public static void main(String[] args) { Integer i = 10; String s1 = i.toString(); String s2 = i+""; String s3 = String.valueOf(i); } }
public class Test { public static void main(String[] args) { String s = "32"; //1 double d1 = Double.valueOf(s).doubleValue(); double d2 = new Double(s).doubleValue(); //2 int i = Integer.parseInt(s); } }
TODO
public class Test { public static void main(String[] args) { // boolean f = true; // int i = (int)f; //编译不通过 // // Integer integer = 10; // Double dd = (Double)integer; //编译不通过 int i2 = 257; byte b = (byte) i2; System.out.println(b); // 1 double d = 34.22; int i3 = (int)d; System.out.println(i3);// 34 } }