close

資料型態的轉換與提升Conversions and Promotions

是很常用又很重要的觀念

以下介紹簡單常用的幾個

String內碰到+會將其他的運算元也轉成String
ex : int a = 1;
System.out.print("a = " + a); //這邊的a會自動轉成String

數字運算碰到會自動將運算中的數字轉成其中最大的基本資料型態
ex : double x = 1.1 + 2; //2會被轉型成double然後和1.1相加在給x

無特別指定時數字的小數點. 會將數字轉成double型態
ex : float x = 1.1; //會編譯錯誤, 因為1.1是double型態

Promotion晉升 or Implicit Casting 隱含式轉換
小的資料型態轉成大的, 無風險轉換
Casting 強制轉型 or Explicit Casting 強行式轉換
使用括號()手動將型別轉型, 大的資料型態轉成小的,
需強制指定, 原則上多的部分會被捨棄
ex : short a = 258, //00000001 00000010
 (byte) a 會變成 2 //00000010

 

以下介紹官網所提出的所有Conversion

a. Identity Conversion
本身是相同類型的參考資料型態, 不需要特地寫

Interger x;
Interger y = new Integer(1);
x = (Integer)y;

b. Widening Primitive Conversion
小的資料型態轉成大的, 不會有資料遺失的問題

byte to short, int, long, float, or double
short to int, long, float, or double
char to int, long, float, or double
int to long, float, or double
long to float or double
float to double

c. Narrowing Primitive Conversion
char與short或byte, short轉char, 或是大的轉小的
會有資料遺失的問題

short to byte or char
char to byte or short
int to byte, short, or char
long to byte, short, char, or int
float to byte, short, char, int, or long
double to byte, short, char, int, long, or float

d. Widening and Narrowing Primitive Conversion
小轉大再轉成小的

byte to char
byte會先轉成int, int再轉成char

e. Widening Reference Conversion
子class給父class時, 不需特地寫

class A{}
class B extends A{}

A a = new A();
B b = new B();
a = b;

f. Narrowing Reference Conversion
不同class間轉換, 如果有不符合的地方會拋出ClassCastException

g. Boxing Conversion
基本資料型態轉型到對應的class型態
並且編譯器會有auto boxing的功能
ex: Integer a = 10;

boolean to Boolean
byte to Byte
short to Short
char to Character
int to Integer
long to Long
float to Float
double to Double
null to null

h. Unboxing Conversion
基本資料型態對應的class轉型到基本資料型態
並且編譯器會有auto unboxing的功能
ex: int a = new Integer(10);

Boolean to boolean
Byte to byte
Short to short
Character to char
Integer to int
Long to long
Float to float
Double to double

i. Unchecked Conversion
泛型內使用的type可能不完全被compiler掌握

j. Capture Conversion
泛型內使用的type皆是可以被compiler掌握的

k. String Conversion
基本資料型態會被用對應的class轉型成String的型態
其中null會轉成null字串

l. Forbidden Conversions
有些無法互相轉換的就會明確出現被禁止轉換

int i = 1;
String s = (String) i;

m. Value Set Conversion
浮點數轉映射到另一值不需要轉換

 

1. 官網 https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

01.png  

arrow
arrow

    RX1226 發表在 痞客邦 留言(0) 人氣()