[Java Basic] 02 变量
变量的定义
在数学中变量是指没有固定的值、可以改变的数.在计算机中也是大同小异,数学意义上的变量只可以是数字.但是计算机意义上的变量可以存储很多类型的数据,如数字、字符串等.在软件系统中,是将数据存储在内存之中的,而对内存中的数据的引用就是变量,可以理解为变量就是内存中数据的代词.变量就是指代在内存中开辟的存储空间,用于存放运算过程中需要用到的数据.
内存中的变量
系统内存可大致分为3个区域,系统区(OS)、程序区(Program)和数据区(Data).当程序执行时,程序代码会加载到内存中的程序区,数据暂时会存储在数据区中.从内存的角度来讲可以理解为变量存储的内容是数据在数据区中的"门牌号".系统调用变量时通过这个"门牌号"找到对应数据.

注意
- 变量的声明: 用特定语法声明一个变量,让运行环境为其分配空间.
Java语言语法规定,变量使用之前必须声明,否则会有编译错误.
-
public static void main(String[] args) { a = 1; // 编译错误,变量没有声明 int score = 0; scord = 100; // 编译错误,拼写错误 System.out.println(score); }
-
- 变量的命名
1.变量名必须是一个有效的标示符
标示符可以简单地理解为是一个名字,用来标示类名、变量名、方法名、数组名、文件名的有效字符序列.
Java语言规定标示符由任意顺序的字母、下划线(_)、美元符号($)和数字组成,但是第一个字符不能是数字.
2.变量名不可以使用Java中关键字
| int | public | this | finally | boolean | abstract |
| continue | float | long | short | throw | throws |
| return | break | for | static | new | interface |
| if | goto | default | byte | do | case |
| strictfp | package | super | void | try | switch |
| else | catch | implements | private | final | class |
| extends | volatile | while | synchronized | instanceof | char |
| double | import | transient | implements |
3.变量名不能重复
4.应选择有意义的单词作为变量名
- 变量的初始化:变量声明后,要为其赋一个确定的初值后再使用.
1.未经初始化的变量不能使用
-
public static void main(String[] args) { int a; int b = 10; int c = a + b; // 编译错误 System.out.prinltn(c); }
-
2.在声明变量时初始化
-
public static void main(String[] args) { int sum = 0; //声明同时初始化 int a = 5; int b = 6; sum = a + b; System.out.println(sum); }
-
3.在第一次使用变量前初始化
-
public static void main(String[] args) { int sum; sum = 0; // 在使用sum变量之前对其进行初始化. sum = sum + 100; System.out.println(sum);
-
- 变量的访问:可以对变量中的数据进行存取、操作,但必须和其类型匹配.
-
public static void main(String[] args) { int salary; salary = 15000.50; // 编译错误,整型变量不可以赋予浮点值(小数). double d = 123.456; int n = d%2; // 编译错误,浮点型变量不可以进行取余计算. }
作者: cnCoder 出处: http://www.cnblogs.com/cnCoder 转载请注明出处!


浙公网安备 33010602011771号