java語言中的型別轉換

2020-08-11 20:23:34

java語言中的型別轉換

1、自動型別轉換

要注意的點:

(1)兩種型別要相互相容

(2)高型別不能轉成低型別,低型別可以轉成高型別

(3)如果非要高型別轉低型別,就必須要用到下面 下麪的強制型別轉換

public class text{
	public static void main(String[] args){
		//短整型轉爲整型
		short s = 123;
		int i = s;//將源型別值存入到目標型別變數中(自動型別轉換)
		System.out.println(i);
		
		//單精度轉爲雙精度
		float f = 100.0F;
		double d = f;//自動型別轉換
		System.out.println(d);
		
		//整型轉爲浮點型
		int i2 = 100;
		double d2 = i2;//自動型別轉換
		System.out.println(d2);
		
		//字元型轉爲整型
		char c = 'A';
		int i3 = c;//自動型別轉換
		System.out.println(i3);
		
		//字元轉爲浮點型
		char c2 = 'a';
		double d3 = c2;
		System.out.println(d3);
		
		//boolean無法與其他型別進行轉換
		boolean bool = true;//只能爲true或者flase
		int i4 = bool;//不相容的型別
	}
}

2、強制型別轉換

public class text{
	public static void main(String[] args){
		//short型轉爲byte型
		short s = 123;
		//自動型別轉換失敗,編譯錯誤
		byte b = s;
		System.out.println(b);
	}
}

強制型別轉換:(目標型別)值

public class text{
	public static void main(String[] args){
		//short型轉爲byte型
		short s = 123;
		//強制型別轉換成功
		byte b = (byte)s;
		System.out.println(b);
	}
}

如果被轉換的值在要轉換的值的範圍內,數據是會完整儲存的;

如果被轉換的值不在要轉換的值的範圍內,數據是會被截斷的。

public class text{
	public static void main(String[] args){
		//長度足夠,數據完整
		short s = 123;
		byte b = (byte)s;//強制型別轉換(數據完整)
		System.out.println(b);

		//長度不夠,數據截斷
		short s2 = 257;
		byte b2 = (byte)s2;//強制型別轉換(數據截斷)
		System.out.println(b2);
	}
}