java中Number Type Casting(数字类型强转)的用法

4.5 Number Type Casting(数字类型强转) 
隐式 casting(from small to big)
byte a = 111;
int b = a;
显式 casting(from big to small)
int a = 1010;
byte b = (byte)a;

注意: 从大到小必须强转!

一道著名的公司面试题如下,以下程序有何问题?

public class Test {
    public static void main(String[] args) {
        short s1 = 1;
        s1 = s1 + 1;
        System.out.println(s1);  
    }
}
 

上面这个程序,因为1是int,s1是short,所以s1+1就往大的隐形转,就自动变成int,所以这个式子s1 = s1 + 1;左边是short,右边是int, 当把大的变成小的时,需要强转。正确的程序见下:

public class Test {
    public static void main(String[] args)  {
        short s1 = 1;
        s1 =(short) (s1 + 1);
        System.out.println(s1);
    }
}

输出结果:

2

版权保护,原文出处:http://www.mark-to-win.com/JavaBeginner/JavaBeginner1_web.html#cast

猜你喜欢

转载自blog.csdn.net/mark_to_win/article/details/89258017