Java是一門強類型語言,每個變數都必須先聲明其類型,再賦予具體的值。Java的基本類型包括整型、浮點型、字元型、布爾型以及一些特殊類型,如void和null。
一、整型
整型表示整數,Java提供了4種整型:byte、short、int和long,這些類型的大小和取值範圍不同。
public class IntegerTypeDemo {
public static void main(String[] args) {
byte b = 1;
short s = 100;
int i = 1234567890;
long l = 1234567890123456789L;
System.out.println("byte b = " + b);
System.out.println("short s = " + s);
System.out.println("int i = " + i);
System.out.println("long l = " + l);
}
}
運行上述代碼,輸出結果為:
byte b = 1 short s = 100 int i = 1234567890 long l = 1234567890123456789
可以看出,byte類型變數的範圍為-128~127,short類型變數的範圍為-32768~32767,int類型變數的範圍為-2147483648~2147483647,long類型變數的範圍為-9223372036854775808~9223372036854775807。
二、浮點型
浮點型表示實數,Java提供了兩種浮點型:float和double,float類型比double類型小。
public class FloatTypeDemo {
public static void main(String[] args) {
float f = 12345.6789f;
double d = 12345.6789;
System.out.println("float f = " + f);
System.out.println("double d = " + d);
}
}
運行上述代碼,輸出結果為:
float f = 12345.679 double d = 12345.6789
可以看出,float類型變數的範圍為3.40282347 x 1038 ~ 1.40239846 x 10-45,精度為7位有效數字;double類型變數的範圍為1.79769313486231570 x 10308 ~ 4.9406564584124654 x 10-324,精度為15位有效數字。
三、字元型
字元型表示單個字元,Java使用Unicode編碼,可以用單引號括起來表示。
public class CharTypeDemo {
public static void main(String[] args) {
char c1 = 'A';
char c2 = '中';
char c3 = '\u0041';
char c4 = '\u4e2d';
System.out.println("c1 = " + c1);
System.out.println("c2 = " + c2);
System.out.println("c3 = " + c3);
System.out.println("c4 = " + c4);
}
}
運行上述代碼,輸出結果為:
c1 = A c2 = 中 c3 = A c4 = 中
可以看出,字元型變數可以用一個字元或者Unicode編碼表示。
四、布爾型
布爾型表示真或假,Java提供了boolean類型,只有兩個取值:true和false。
public class BooleanTypeDemo {
public static void main(String[] args) {
boolean b1 = true;
boolean b2 = false;
System.out.println("b1 = " + b1);
System.out.println("b2 = " + b2);
}
}
運行上述代碼,輸出結果為:
b1 = true b2 = false
五、特殊類型
Java還提供了一些特殊類型,比如void和null。void表示沒有返回值的方法,null表示一個空引用。
public class SpecialTypeDemo {
public static void test() {
System.out.println("test method");
}
public static void main(String[] args) {
test();
String s = null;
System.out.println("s = " + s);
}
}
運行上述代碼,輸出結果為:
test method s = null
注意,在使用空引用時要避免空指針異常。
結論
Java的基本類型包括整型、浮點型、字元型和布爾型,以及一些特殊類型。在使用時需要根據具體情況選擇合適的類型,並注意取值範圍和精度問題。
原創文章,作者:BLMS,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/134988.html
微信掃一掃
支付寶掃一掃