1. 程式人生 > 其它 >Java基礎-型別轉換

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
    }
}