Java基礎複習——數據類型、變量和數組
“學而時習之,不亦說乎!”
Java基礎類型
不應將一箇中型類型的寬度(width)看成是他所小韓的存儲位置的數量,而應當其理解成定義這種類
型的變量和表達式的行爲。只要類型符合聲明他的時候的規定,Java運行時環境就可隨意使用任意大
小(的空間)。
整形
名稱 寬度 範圍
long 64 -9 223 372 036 854 775 808 ~ 9 223 372 036 854 775 807
int 32 -2 147 483 648 ~ 2 147 483 647
short 16 -32 768 ~ 32 767
byte 8 -128 ~ 127
浮點型
名稱 寬度 大致範圍
double 64 4.9e-324 ~ 1.8e+308
float 32 1.4e-045 ~ 3.4e+038
字符型
名稱 寬度
char 16
Java使用Unicode表示字符,Unicode是許多字符集的統一體,需要16位的寬度。
住:有關Unicode的更多信息,可在http://www.unicode.org找到。
程序:
//char variables behave like integers.
class CharDemo2 {
public static void mian(String[] args) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++;
System.out.println("ch1 is now " + ch1);
}
}
輸出:
ch1 contians X
ch1 is now Y
儘管ch1是字符型,但在執行算數操作時,也可將它看成整形類型。
變量的作用域
在嵌套定義變量的時候,注意不能江邊兩證名稱和外部作用域中的變量相同的名稱。
程序:
//This program will not compile
class ScopeErr {
public static void main(String[] args) {
int bar = 1;
{
int bar = 2; //Compile-time error - bar already defined!
}
Java類型轉換
強制轉換不兼容的類型
由小變大時,可自動進行轉換;但有大變小時,需要強制轉換。
如將int強制轉換成一個byte時,如果整數值超出了byte的範圍,則將以byte的範圍爲模(即,用整數
值除以byte範圍所得的餘數)減少。
程序:
//Demonstrate casts.
class Conbersion {
public static void main(String[] args) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("/nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " "+ b);
System.out.println("/nConversion of double to int.");
d = (int) i;
System.out.println("d and i " + d + " "+ i);
System.out.println("/nConversion of double to byte.");
d = (byte) b;
System.out.println("d and b " + d + " "+ b);
}
}
輸出:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
當值257被強制轉換成一個byte變量時,結果是257除以256(byte 的範圍)的餘數,也就是1。.....
自動類型提升
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
a * b的結果很容易超出byte操作數的範圍。爲解決這類問題,當求值一個表達式時,Java自動將byte
,short或char操作數提升爲int。所以在執行表達式a * b是,使用的是整形,而不是byte型。
雖然自動提升有用,但也會引起編譯錯誤。
例如:
byte b = 50;
b = b * 2; //Error!Cannot assign an int to byte!
在這個 b * 2 表達式中 b 已被提升爲 int 型,結果當然是 int 型,付給byte型變量當然會出錯。
如果能理解溢出的後果,則應當使用如下的強制轉換:
byte b = 50;
b = (byte)b * 2;
數組
有new分配的數組中的元素會被自動初始化成0。