基本数据类型
Java中有8种基本数据类型来存储数值、字符和布尔值。
整数类型
整数类型简称整型,用来存储整数值(没小数部分的值)。可以是正数也可以是负数。整型数据根据它所占内存大小的不同,可分为byte、short、int和long4种类型。
| 数据类型 | 内存空间 | 取值范围 |
|---|---|---|
| byte | 8位 | -128~127 |
| short | 16位 | -32768~32767 |
| int | 32位 | -2147483648~2147483647 |
| long | 64位 | -9223372036854775808~9223372036854775807 |
8位等于1字节
int型
int型是Java整型值的默认数据类型。当对多个尚未定义数据类型的整数做运算时,运算结果默认int类型。
public class Demo {
public static void main(String[] args) {
System.out.println(15+20);
}
}
运行结果
35
定义int型变量有4种语法
// 定义int型变量x
public class Demo {
public static void main(String[] args) {
int x;
x = 9;
System.out.println(x);
}
}
// 同时定义int型变量x,y
public class Demo {
public static void main(String[] args) {
int x,y;
x = 9;
y = 11;
System.out.println(x+y);
}
}
// 同时定义int型变量x,y并赋予初值
public class Demo {
public static void main(String[] args) {
int x = 9,y = 11;
System.out.println(x+y);
}
}
// 定义int型变量,并赋予公式9+11计算结果的初值
public class Demo {
public static void main(String[] args) {
int x = 9+11;
System.out.println(x);
}
}
byte型
byte型的定义方式与int相同
public class Demo {
public static void main(String[] args) {
byte x = 9;
byte b = -11;
System.out.println(x + b);
}
}
public class Demo {
public static void main(String[] args) {
byte x = 9,b = -11;
System.out.println(x+b);
}
}
上述两段代码的运行结果
-2
short型
short型的定义方式与int相同。
long型
由于long型的取值范围比int型大,且属于高精度数据类型。所以在赋值时要与int型做区分。
在整数后加L或者l(小写的L)。
public class Demo {
public static void main(String[] args) {
long a = 123456789 * 987654321;
long x = 123456789L;
long y = 987654321L;
System.out.println(a);
System.out.println(x*y);
}
}
运行结果
-67153019
121932631112635269
从两种结果上看,long型加L与不加L的区别。