資料型別轉換

2021-08-27 14:51:32 字數 1777 閱讀 4314

資料型別的轉換方式主要可以分為3種:自動型別轉換、強制型別轉換、包裝類過渡型別轉換。其中強制型別轉換在實際開發中運用的比較多。

1.自動型別轉換

**示例:

public class conversion_1

}

執行結果:

short -> int 4

byte -> int 30

char -> int 71

2.強制型別轉換

**示例:

public class conversion_2

}

執行結果:

int -> byte 56

float -> int 2

double -> int 123.45678901234568

int -> char 8

3.包裝類過渡型別轉換

在進行簡單資料型別之間的強制轉換時,也可以利用包裝類進行中間過渡。

在一般情況下,首先宣告乙個變數,再將其轉換成與其相對應的包裝類的乙個例項化物件,然後用這個物件呼叫包裝類中的xxvalue()方法進行型別轉換。

例如,當把int型轉換為short型時,**如下:

int i = 67;

integer it = new integer(i);

short s = it.shortvalue(); // it.shortvalue()以short型別返回該integer的值

當希望把double型轉換為int型時,**如下所示:

double d1 = 100.00;

double d2 = new double(d1);

int i1 = d2.intvalue();

string型別轉換成資料型別

**示例1:

public class stringtype_1

}

執行結果:

the stringtype of int is 12

the stringtype of float is 12.3

the stringtype of double is 12.6

the stringtype of long is 123

the stringtype of short is 12

**示例2:

public class stringtype_2

}

執行結果:

the inttype of string is 123

the floattype of string is 45.6

the doubletype of string is 12.3456789

the longtype of string is 15555555666

the bytetype of string is 12

資料型別 型別轉換

這樣的語句將報錯,因為char型別精度低於int型別,編譯器無法將其自動轉換,只能進行強制轉換 int x 65 char ch char x 舉例1 int age 19 char 女 char result age int 不可以自動轉換成char 精度損失 舉例2 int a 10 int b...

Objective C資料型別 資料型別轉換

資料型別 1.objective c資料型別可以分為 基本資料型別 物件資料型別和id型別。2.基本資料型別有 int float double和char型別。3.物件型別就是類或協議所宣告的指標型別,例如 nsautoreleasepool pool 其中,nsautoreleasepool是乙個...

資料型別轉換

資料型別轉換 public class typeconvert 一 容量小的資料型別自動轉換為容量大的資料型別 資料型別按容量大小排序為 byte,short,char int long float double byte,short,char之間不會互相轉換,他們三者在計算時首先回轉換為int型別...