基本數據類型
數據類型在程序語言中佔有舉足輕重的地位,java的數據類型可分爲基本數據類型與引用數據類型
如下圖
在java中想要使用一個變量,就必須先申明,此時編譯程序會在未使用的內存空間中尋找一塊足夠能保存這個變量的空間以供這個變量使用。下圖爲基本數據類型的基本信息:
1.整數類型
整數類型佔32位,即4字節,範圍在-2147483648~2147483647,在編譯器中int類型的變量賦予超出範圍的數字大小就會報錯。
public class TestString {
public static void main(String[] args) {
int a=99999999999999999999999;
System.out.println(a);
}
}
運行結果:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The literal 99999999999999999999999 of type int is out of range
at TestStringChangToInt.TestString.main(TestString.java:6)
結果中的“type int is out of range” 即是超出表示範圍的意思。
整型數據的short類型以及long類型同理。
public class TestString {
public static void main(String[] args) {
int a=Integer.MAX_VALUE; //Integer爲包裝類
System.out.println("a的最大值:"+a);
a=a+1;
System.out.println("a的最大值加1,造成的結果:"+a);
}
}
/*
運行結果
a的最大值:2147483647
a的最大值加1,造成的結果:-2147483648
*/
數據溢出:
如上的代碼所示,當int類型的變量最大值加1就會變成int類型的最小值,加2時就會變成次小值,即-2147483647。這就是數據的溢出。
強制類型轉換:
假如int數據類型溢出,我們可以強制轉換類型,避免數據的出錯。
public class TestString {
public static void main(String[] args) {
int a=Integer.MAX_VALUE;
System.out.println("a的最大值:"+a);
int e=a+1;
System.out.println("a的最大值加1,造成的結果:"+e);
long d=a+1L;
System.out.println("a爲整型,1加上了L爲long型:"+d);//倆者相加被強制轉換成long型
long c=(long)a+1;
System.out.println("強制轉換a然後加1:"+c);
}
}
/*
a的最大值:2147483647
a的最大值加1,造成的結果:-2147483648
a爲整型,1加上了L爲long型:2147483648
強制轉換a然後加1:2147483648
*/