1. 程式人生 > 實用技巧 >#Java Day04 型別轉換

#Java Day04 型別轉換

型別轉換

-------------------------------------------------------------------------------------------------------------------------------------------> 高

byte, short, char -> int -> long -> float -> double

public class Demo05 {
public static void main(String[] args) {
int i =128;
double b = i;//記憶體溢位

//強制轉換 (型別)變數名 高--低
//自動轉換 低--高

System.out.println(i);
System.out.println(b);

/*
注意點:
1.不能對布林值進行轉換
2.不能把物件型別轉轉為不相干的型別
3.在把高容量轉換到低容量的時候,強制轉換
4.轉換的時候可能存在記憶體溢位,或者精度問題!
*/

System.out.println("========================================================");
System.out.println((int)23.7); //23
System.out.println((int)-45.89f); //-45


System.out.println("========================================================");
char c ='a';
int d =c+1;
System.out.println(d);
System.out.println((char)d);

}
}

public class Demo06 {
public static void main(String[] args) {
//操作比較大的數的時候,注意溢位問題
//JDK7 新特性 , 數字之間可以用下劃線分割
int money = 10_0000_0000;
System.out.println(money);

int years = 20;
int total = money * years; //-1474836480 ,計算的時候溢位了
long total2 = money * years;//預設是int,轉換之前已經存在問題了?

long total3 = money*((long)years);//先把一個數轉換為long
System.out.println(total3);

// L l

}
}