Java基础-类型转换

1、简单数据类型的转换

在Java整型、实型(常量)、字符型数据可以看做简单数据类型。运算中,不同类型的数据先转化为同一类型,然后进行运算,转换从低级到高级。
低 ------------------------------------> 高
byte,short,char—> int —> long—> float —> double
 

自动类型转换

低级变量可以直接转换成高级变量,称为自动类型转换,例如:

public class Test {
    public static void main(String[] args) {
        byte b = 1;
        int i = b;
        long l = b;
        float f = b;
        double d = b;
        System.out.println(i);
        System.out.println(l);
        System.out.println(f);
        System.out.println(d);

        char c ='c';
        int n = c;
        System.out.println("output:"+ n);
    }
}

上述代码可以正常编译通过,运行结果如下:

1
1
1.0
1.0
output:99

 

强制类型转换

对于byte short char 三种类型而言,由于处于平级状态,因此不能自动转换,需要使用强制类型转换
将高级变量转换成低级变量的时候,同样需要使用强制类型转换,但是有丢失精度的风险
public class Test {
    public static void main(String[] args) {
        short i=98;
        char c=(char)i;
        System.out.println("output:"+c);

        i = 99;
        byte b = (byte) i;
        c = (char) i;
        float f = (float) i;
        System.out.println(b);
        System.out.println(c);
        System.out.println(f);
    }
}

结果如下:

output:b
99
c
99.0

 

2、字符串与其他类型间的转换

其他类型向字符串转换

  1. 调用类的串转换方法:X.toString();
  2. 自动转换:X+“”;
  3. 使用String的方法:String.volueOf(X);
public class Test {
    public static void main(String[] args) {
        Integer i = 10;
        String s1 = i.toString();
        String s2 = i+"";
        String s3 = String.valueOf(i);
    }
}

字符串向其他类型转换

  1. 先转换成相应的封装器实例,再调用对应的方法转换成其它类型
  2. 静态parseXXX方法
public class Test {
    public static void main(String[] args) {
        String s = "32";
        //1
        double d1 = Double.valueOf(s).doubleValue();
        double d2 = new Double(s).doubleValue();
        //2
        int i = Integer.parseInt(s);
    }
}

 

3、常用数据类型转换

TODO

 
 
 

4、一些注意

 
数据类型转换必须满足如下规则:
  • 1. 不能对boolean类型进行类型转换。
  • 2. 不能把对象类型转换成不相关类的对象。
  • 3. 在把容量大的类型转换为容量小的类型时必须使用强制类型转换。
  • 4. 转换过程中可能导致溢出或损失精度
public class Test {
    public static void main(String[] args) {
//        boolean f = true;
//        int i = (int)f;   //编译不通过
//
//        Integer integer = 10;
//        Double dd = (Double)integer; //编译不通过
        int i2 = 257;
        byte b = (byte) i2;
        System.out.println(b);  // 1

        double d = 34.22;
        int i3 = (int)d;
        System.out.println(i3);// 34
    }
}

 

posted @ 2021-09-15 20:45  r1-12king  阅读(44)  评论(0编辑  收藏  举报