【java】学习路线1-类型转换、隐式转换、强制转换

Posted on 2022-03-10 00:27  罗芭Remoo  阅读(52)  评论(0)    收藏  举报

/**
文档注释,这里是一段文章
一般放在类的外面
*/

public class HelloWorld{
    //这个是注释的文本
    public static void main(String[] args){
        System.out.println("Hello__World!\n太牛逼啦!");
        /*System.out.println("Hello__World!\n太牛逼啦!");
        */
        //类型
        int hp = 100;
        System.out.println("现在的hp(int)是" + hp);
        //byte short int long
        //float double
        //char
        //boolean
        /*
        常量整数默认是int类型
        小数常量默认是double类型
        下面这个例子展示了 隐式转换 强制转换等知识
         */
        byte a = 100;
        System.out.println(a);
        //隐式转换
        //当常量在byte的范围内时,则自动在赋值的时候转换为byte
        long d = 10000000000000L;
        System.out.println(d);
        //强制转换
        //常量大于int的存储范围无法存储,需要强制转换为long再赋值
        //float ee = 2.22;
        //注意!!这样会报错,从double转换到float可能会有损失
        //需要强制转换
        float ee = 2.2f;//这样就没问题
        double ff= 3.3;
        System.out.println(ee + '\n' + ff);
        
        /**类型转换
        小类型赋值给大类型,会自动转换
        */
        byte testCaseByte = 10;
        short testCaseShort=testCaseByte;
        System.out.println(testCaseShort);
        //大类型赋值给小类型,会出现错误。
        
        //int testCaseInt = 100;
        //testCaseByte = testCaseInt;
        //System.out.println(testCaseByte);
        //不兼容的类型:
        //从int转换到byte可能会有损失
        //需要强制转换
        int testCaseInt = 127;
        testCaseByte = (byte)testCaseInt;
        System.out.println(testCaseByte);
        
    }
}