数据类型
Java的数据类型可以分为两种:基本数据类型以及引用数据类型。
基本数据类型
Java的基本数据类型有8种:byte、short、int、long、float、double、char、boolean。byte、short、int、long是整数类型;float、double是浮点数类型;char是字符型;boolean是布尔型。
它们的取值范围如下表所示:
类型 | 描述 | 位数 | 字节 | 取值范围 | 默认值 | 包装类 |
byte | 字节型 | 8 | 1 | -128~127 | 0 | Byte |
short | 短整型 | 16 | 2 | -2^15~2^15-1 | 0 | Short |
int | 整型 | 32 | 4 | -2^31~2^31-1 | 0 | Integer |
long | 长整型 | 64 | 8 | -2^63~2^63-1 | 0 | Long |
float | 单精度浮点型 | 32 | 4 | 1.4e-45f~3.4e+38f | 0.0 | Float |
double | 双精度浮点型 | 64 | 8 | 4.9e-324~1.8e+308 | 0.0 | Double |
char | 字符型 | 16 | 2 | \u0000~\uffff或0~65535 | \u0000或0 | Character |
boolean | 布尔型 | 只有true和false | false | Boolean |
浮点数类型采用的是IEEE754标准。
public class Demo {
public static void main(String[] args) {
byte a = 10;
short b = 15;
int c = 20;
long d = 25;
long i = 1000000000000l;//当long初始化的值比int大的时候需要加上l或L
float e = 0.7f;//float初始化需要在后面加上f或F
double f = 0.8;
char g = 'a';
boolean h = false;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("d = " + d);
System.out.println("e = " + e);
System.out.println("g = " + g);
System.out.println("f = " + f);
System.out.println("h = " + h);
System.out.println("i = " + i);
}
}
引用数据类型
引用类型是指向一个对象,不是一个原始值,在Java中除了基本数据类型之外其他的数据类型都是引用类型。用的比较多的引用类型是String,StringBuffer,数组等。
public class Demo {
public static void main(String[] args) {
String str = "Hello World";
int [] array = new int[]{1,2,3,4,5};
System.out.println("str = " + str);//String重写了toString方法,所以输出的是Hello World
System.out.println("array = " + array);//输出地址,而不是值
}
}