JAVA5

类型转换

  • 由于java是强类型语言,所以要进行有些运算的时候需要用到类型转换。
    低------------------------------------------->高 (容量)
    byte、short、char-->int-->long-->float-->double(小数的优先级大于整数)

  • 运算中,不同类型的数据先转化为同一类型,然后进行运算。

    int i=128;
    byte b=(byte)i;
    //内存溢出 byte是-128至127,所以它会随便给一个值
    //强制转换:(类型)变量名 高--低
    //在转换的时候我们要避免内存溢出的情况
    System.out.println(i);
    System.out.println(b);

    //自动转换:低--高
    int a=256;
    double c=a;
    System.out.println(a);
    System.out.println(c);

    //浮点转换的精度问题
    System.out.println((int)23.7); //变成23,小数位没了
    System.out.println((int)-45.89f); //变成-45,小数位没了

    char d='o';
    int e=d+1;
    System.out.println(e);
    System.out.println((char)e);

    /*
    注意点:
    1.不能对布尔值进行转换
    2.不能把对象类型转换为不相干的类型
    3.在把大容量转换为低容量的时候,要强制转换,即()
    4.转换的时候可能存在内存溢出,或者精度问题
    */

    //操作比较大的时候注意溢出问题
    //JDK7的新特性,数字之间可以用下划线分割,并且运行的时候不会出现(小技巧)
    int money=10_0000_0000;
    System.out.println(money);
    int years=20;

    //错误示范
    int total=money*years; //-1474836480,计算的时候溢出了,它会默认为int类型
    System.out.println(total);

    long total2=money*years; //它会默认为int类型,转换之前已经存在问题了
    System.out.println(total2);

    //正确示范
    long total3=money*((long)years); //要先把其中一个数转化为long类型
    System.out.println(total3);

    long total4=((long)money)*years;
    System.out.println(total4);

    //long类型后面的数字加上大写的L,float类型同,不要用小写的。

    }

posted @ 2022-07-30 13:57  三毛捡菜  阅读(103)  评论(0)    收藏  举报