一、常量
1、概述
常量:是指在Java程序运行期间固定不变的数据
2、分类
| 类型 | 含义 | 数据举例 |
|---|---|---|
| 整数常量 | 所有的整数 | 0, 1, 567, -9 |
| 小数常量 | 所有的小数 | 0.0, -0.1, 2.55 |
| 字符常量 | 单引号引起来,只能写一个字符,必须有内容 | ‘a’, ‘ ‘, ‘好’ |
| 字符串常量 | 双引号引起来,可以些多个字符,也可以不写 | “A”, “Hello”, “你好”, “” |
| 布尔常量 | 只有两个值 | true, false |
| 空常量 | 只有一个值 | null |
3、实例
public class Demo01const{
public static void main(String[] args){
System.out.println("ABC");
System.out.println("");
System.out.println("XYZ");
// 整数常量
System.out.println(30);
System.out.println(-500);
// 小数常量
System.out.println(3.14);
System.out.println(-2.5);
// 字符常量
System.out.println('A');
// System.out.println(''); //两个单引号中间必须有且仅有一个字符,没有不行
System.out.println(' ');
// 布尔常量
System.out.println(true);
System.out.println(false);
// null
// System.out.println(null);//空常量不能直接打印
}
}
二、变量
1、变量的定义
变量定义的格式包括三个要素:数据类型, 变量名, 数据值。
2、格式
数据类型 变量名 = 数据值;
3、实例
public class Demo02Variable{
public static void main(String[] args){
// 创建一个变量
// 格式: 数据类型 变量名
int num1;
num1 = 10;
System.out.println(num1);
// 改变变量当中本来的数字
num1 = 20;
System.out.println(num1);
// 使用一步到位的格式来定义变量
// 格式:数据类型 变量名称 = 数据值
int num2 = 25;
System.out.println(num2);
System.out.println("========");
byte num3 = 30; // 注意:右侧数值的范围不能超过左侧数据类型的范围
System.out.println(num3);
// byte num4 = 400; // 右侧超出了byte的数据范围,错误
long num4 = 3000000000L; //注意整数默认的是int类型,如果需要long类型则需要加上L
System.out.println(num4);
float num5 = 2.5F;
System.out.println(num5);
}
}
4、注意事项
如果创建多个变量,那么变量之间的名称不能重复
对于float和long类型来说,字母后缀F和L不能丢掉
如果使用byte或者short类型的变量,那么右侧的数据值范围不能超过左侧类型的范围
变量要先声明和赋值才能使用
变量的使用不能超过作用域的范围
可以通过一个语句来创建多个变量,但是一般情况不推荐这么写
// 方式一 int a, b, c; a = 10; b = 20; c = 30; // 方式二 int x = 100, y = 200, z = 300;
这种写法也是可以的,一个程序有重复变量名。
public class Demo03VariableNotice{
public static void main(String[] args){
int num1 = 10;
long num2 = 20L;
{
int num3 = 90;
System.out.println(num3);
}
int num3 = 0;
System.out.println(num3);
}
}
三、数据类型
1、数据类型分类:
Java的数据类型分为两大类:
- 基本数据类型:包括
整数(byte, short, int, long),浮点数(float, double),字符(char),布尔(boolean)。 - 引用数据类型:包括
字符串、类、数组、接口、Lambda。
2、基本数据类型
四类八种基本数据类型:
| 数据类型 | 关键字 | 内存占用 | 取值范围 |
|---|---|---|---|
| 字节型 | byte | 1个字节 | -128~127 |
| 短整型 | short | 2个字节 | -32768~32767 |
| 整型 | int(默认) | 4个字节 | -2^31 ~ 2^31 -1 |
| 长整型 | long | 8个字节 | -2^63 ~ 2^63 - 1 |
| 单精度浮点数 | float | 4个字节 | 1.4013E-45 ~ 3.4028E+38 |
| 双精度浮点数 | double(默认) | 8个字节 | 4.9E-324 ~ 1.7977E+308 |
| 字符型 | char | 2个字节 | 0~65535 |
| 布尔类型 | boolean | 1个字节 | true, false |
Java中的默认类型:整数类型是
int, 浮点类型是double.
3、注意事项
字符串不是基本类型,而是引用类型;
浮点型可能只是一个近似值,并非精确的值;
数据范围与字节数不一定相关,例如float数据范围比long更加广泛,但是float是4字节,long是8字节
浮点数当中默认类型是double,如果一定要使用float类型,需要加上一个后缀F;
如果是整数,默认为int类型,如果一定要使用long类型,需要加上一个后缀L。推荐使用大写字母后缀。