变量
5.1 变量概述
从本质上讲,变量是内存中的一小块区域,其值可以在一定范围内变化。
1 2 3
| 数据类型 变量名 = 初始化值; int age = 18; System.out.println(age);
|
或者
1 2 3 4 5 6
| 数据类型 变量名; 变量名 = 初始化值; double money; money = 55.5; System.out.println(money);
|
还可以在同一行定义多个同一种数据类型的变量,中间使用逗号隔开。但不建议使用这种方式,降低程序的可读性。
1 2 3 4 5 6 7 8 9
| int a = 10, b = 20; System.out.println(a); System.out.println(b);
int c,d; c = 30; d = 40; System.out.println(c); System.out.println(d);
|
变量的使用:通过变量名访问即可。
5.2 使用变量时的注意事项
- 在同一对花括号中,变量名不能重复。
- 变量在使用之前,必须初始化(赋值)。
- 定义
long
类型的变量时,需要在整数的后面加L
(大小写均可,建议大写)。因为整数默认是int
类型,整数太大可能超出int
范围。
- 定义
float
类型的变量时,需要在小数的后面加F
(大小写均可,建议大写)。因为浮点数的默认类型是double
, double
的取值范围是大于`的,类型不兼容。
5.3代码
案例一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
public class VariableDemo01 { public static void main(String[] args) { int a = 10; System.out.println(a); a = 20; System.out.println(a); } }
|
案例二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
public class VariableDemo02 { public static void main(String[] args) { byte b = 10; System.out.println(b); short s = 100; System.out.println(s); int i = 10000; System.out.println(i); double d = 13.14; System.out.println(d); char c = 'a'; System.out.println(c); boolean bb = true; System.out.println(bb); System.out.println("--------"); long l = 10000000000L; System.out.println(l); System.out.println("--------"); float f = 13.14F; System.out.println(f); } }
|