Java中类型转换易错题

来源:互联网 发布:日在校园 知乎 编辑:程序博客网 时间:2024/06/05 17:33

JAVA中八种基本类型:byte、short、int、long、float、double、char、boolean。

基本类型 默认值 所占字节数 byte 0 1 short 0 2 int 0 4 long 0L 8 float 0.0f 4 double 0.0d 8 char ‘\u0000’ 2 boolean false 视环境而定

系统为了数据存储能对齐,boolean在字符中,存储的长度是2,当是数字的时候,存储的长度是1。
练习题:

1、byte、short、char和int

public void fun() {    byte b = 1;    byte a = 2;//  byte c = a + b;//报错    byte c = (byte) (a + b);    System.out.println(c);}

解释:类型为byte,short,char类型的变量在运算的时候会自动转为int类型,在式byte c = a + b;中变量c为byte类型,而a + b为整形。

2、int和double

int a = Math.pow(-1>>1, 4);System.out.println(a);

解释:程序不能运行,Math.pow返回的是double类型 不可以用int接收

3、short和int

short s1 = 1;//s1 = s1 + 1;//报错,需要强转s1 = (short) (s1 + 1);s1  += 1;

解释:short+1是int型,需要强转
4、char和int

int a = 4;char b = '4';char c = (char)(a+b);//c的值为‘8’

解释:c的值是’8’,System.out.print打印是8,但是他是char型。int精度比char高,加之后等于8,强转为char变成‘8’

5、char和int

char chr = 'a'+18;char chr2 = 'a';char chr3 = chr2 + 18;System.out.println(chr);System.out.println(chr3);

解释:不能运行的,char chr3 = chr2 + 18;这一句会报错,要强制转换成char

6、

int i = (boolean)8.9//是错的,boolean不能和其他类型转换//这三个就不会错int i2 = (int) 8.3;long L = (long) 8.4f;int i3 = 'A';

7、

    public static void main(String[] args) {        test(null);    }    public static void test(){        System.out.println("null");    }    public static void test(Object obj) {        System.out.println("Object");    }       public static void test(int i){        System.out.println("int");    }    public static void test(double[] array) {        System.out.println("double array");    }}

解释:输出double array,null不能确定其类型,两个函数都能满足条件,数组也是继承Object,所以double[]比Object具有跟高的精确度,于是输出结果是double array

8、

public class Test01 {    public static void main(String[] args) {        f1((byte)1);    }    static void f1(char x){        System.out.println("char");    }    static void f1(short x){        System.out.println("short");    }    static void f1(int x){        System.out.println("int");    }    static void f1(long x){        System.out.println("long");    }}

解释:输出short,因为变成short失去的精度比较少

1 0
原创粉丝点击