- /*
- 基础类型的隐式转换:
- byte,short,char --> int --> long --> float --> double
- byte可隐转short
- 除了boolean,基础类型之间都可进行强制转换
- */
- public class TypeDemo {
-
- public static void isType(byte b) {System.out.println("it is a byte");} //注释该行,isType(b)输出short
- public static void isType(short s) {System.out.println("it is a short");} //注释该行,isType(s)输出int
- public static void isType(char c) {System.out.println("it is a char");} //注释该行,isType(c)输出int
- public static void isType(int i) {System.out.println("it is a int");} //注释该行,上四个输出long
- public static void isType(long l) {System.out.println("it is a long");} //注释该行,上五输出float
- public static void isType(float f) {System.out.println("it is a float");} //注释该行,全输出double
- public static void isType(double d) {System.out.println("it is a double");}
- public static void main(String[] args) {
- byte b = 1;
-
- short s = 1;
- short s2 = b; //byte可隐转为short
- char c = 'c';
- //char c2 = b; //报错,byte无法隐转char
- int i = 1;
- long l = 1;
- /*
- 整数型和char总结
- byte,short,char 中,只有byte可隐转为short
- byte,short,char 都可隐转int、float,运算时都隐转为int,'整数常量'默认类型为int
- 赋值优化机制,'整数常量'可强转为 short,byte,char 赋值给基础数据类型
-
- */
-
- //float f = 1.1; 可用float f = 1; 1隐转float,但是不能赋值默认double型小数给float
- float f = 1.0F;
- float f2 = 1L; //可把long类型隐式转换为float
- double d = 1.0D;
- /*
- isType(c+b); //it is a int
- isType(s+b); //it is a int ,char,short,byte 整数型和char型运算时会隐转为int
- isType(f+l); //it is a double, 浮点数运算会隐转为double
- */
-
- isType(b);
- isType(s);
- isType(c);
- isType(i);
- isType(l);
- isType(f);
- isType(d);
- }
- }
复制代码 今天总结的时候写得测试小程序,基本上通过注释和反复运行,可以了解不同类型之间相互转换的情况。 有兴趣的同学可以copy下来,自己试试。明天我会发我写的关于JAVA各部分初始化顺序的小程序。看过的朋友帮忙顶顶~~ 谢谢~ 一起加油
|
|