Java之八大基本数据类型
在Java语言中有八大基本数据类型,按类型来分,整型有四种:byte,short,int,long;浮点型有两种:float,double;字符型有一种:char;布尔型有一种:boolean。每种数据类型的范围以及具体的占内存量如下各表所示。
1.1整型
| 基本数据类型 | 范围 | 占内存量 |
|---|
| byte | -128~127 | 1字节 |
| short | -32768~32767 | 2字节 |
| int(默认) | -2^31~ 2^31-1 | 4字节 |
| long | -2^63~ 2^63-1 | 8字节 |
1.2浮点型
| 基本数据类型 | 范围 | 占内存量 | 有效位数 |
|---|
| float | -3.4* 10^38~3.4* 10^38 | 4字节 | 6~7位 |
| double(默认) | -1.79* 10^308~1.79* 10^308 | 8字节 | 15~16位 |
1.3字符型
| 基本数据类型 | 范围 | 占内存量 |
|---|
| char | 除转义字符外的其他所有字符 | 不定 |
1.4布尔类型
| 基本数据类型 | 范围 | 占内存量 |
|---|
| boolean | true ,false | 1字节 |
在一般定义变量的方式基础上,需要注意的是:
1.声明long类型数据需要在后面添加L或l。
2.声明float类型数据需要在后面添加F或f。
3.声明char类型数据需要使用单引号,且单引号中只能放一个元素。
代码示例:
public class Demo3 {
public static void main(String[] args) {
//声明一个byte类型变量
byte b = 125;
System.out.println(b);
//声明一个short类型变量
short s = 32000;
System.out.println(s);
//声明一个int类型变量
int i = 12345;
System.out.println(i);
//声明一个long类型变量
long l = 123456789L;
System.out.println(l);
//声明一个float类型变量
float f1 = 89.9f;
System.out.println(f1);
//有效位数6~7位
float f2 = 12.345612789f;//12.345613
System.out.println(f2);
//声明一个double类型变量
double d1 = 89.9;
System.out.println(d1);
//有效位数15~16位
double d2 = 12.123456789012345123444445;//12.123456789012344
System.out.println(d2);
//声明一个字符类型的数据
char c = '狗';
System.out.println(c);//狗
//声明一个布尔类型的数据
boolean b1 = true;
System.out.println(b1);//true
}
}