6、基本数据类型转换

boolean 类型不可转换为其他的数据类型。(其他类型也不能转换为boolean)
整型、字符型、浮点型的数据在混合运算中相互转换,转换时遵循以下原则:
容量小的类型自动转换为容量大的数据类型;数据类型按容量大小排序为:
byte,short,char-》int-》long-》float-》double
byte,short,char之间不会相互转换,他们三者在计算时首先转换为int类型
容量大的数据类型转换为容量小的数据类型时,要加上强制转换符,但可能造成精度降低或溢出;使用时要格外注意
有多种数据类型进行混合运算时,系统首先自动将所有的数据转换为容量最大的那一种数据类型,然后再进行计算。
实数常量(如:1.2)默认为double
整数常量(如:123)默认为int

    TestConvert.java
    public class TestConvert {
      public static void main(String args[]){
        int i = 123;
        int i2 = 456;
        double d1 = (i1+i2)*1.2;//系统将转换为double类型运算
        float f1 = (float)((i1+i2)*1.2);//需要加强制转换符
        byte b1 = 1;
        byte b2 = 2;
        byte b3 = (byte)(b1+b2);//系统将转换为int类型运算,需要加强制转化符

        double d2 = 1e200;
        float f2 = (float)d2;//会产生溢出
        System.out.println(f2);

        float f3 = 1.23f;//必须加f
        long l1 = 123;
        long l2 = 300000000000L;//必须加L
        float f = l1+l2+f3;//系统将转换为float类型运算
        long l = (long)f;//强制转换会舍去小数部分(不是四舍五入)

      }
    }
public class TestConvert2 {
  public static void main (String[] args) {

    int i = 1;
    int j = 2;
    float f1 = (float)0.1;//0.1f
    float f2 = 123;
    long l1 = 12345678;
    long l2 = 888888888888L;
    double d1 = 2e20;
    double d2 = 124;
    byte b1 = 1;
    byte b2 = 127;
    j = j+10;
    i = i/10;
    i = (int)(i*0.1);
    char c1 = 'a';
    char c2 = 125;
    byte b = (byte)(b1-b2);
    char c = (char)(c1+c2-1);
    float f3 = f1+f2;
    float f4 = (float)(f1+f2*0.1);
    double d = d1*i+j;
    float f = (float)(d1*5+d2);

  }
}

  

猜你喜欢

转载自www.cnblogs.com/hlc-123/p/11019409.html