标识符
什么是标识符?
凡是程序员有权利命名的单词都是标识符,如:类名、方法名、变量名、接口名、常量名
标识符命名规则:
- 只能由数字、字母(包括中文)、下划线、美元符号$(人民币符号¥也可以)组成
- 不能以数字开头
- 关键字不能作为标识符
- 严格区分大小写
- 没有长度限制
在windows操作系统中文件名叫:123.java没毛病,但文件中定义不了public class
上面这个命名规则是很多教材翻译官方的,实际描述如下:
An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.
“Java letter” is a character for which the method Character.isJavaIdentifierStart(int) returns true.“Java letter-or-digit” is a character for which the method Character.isJavaIdentifierPart(int) returns true.
The “Java letters” include uppercase and lowercase ASCII Latin letters A-Z(\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign (,or\u0024).The,or\u0024).The sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.The “Java digits” include the ASCII digits 0-9 (\u0030-\u0039).
Letters and digits may be drawn from the entire Unicode character set, which supports most writing scripts in use in the world today, including the large sets for Chinese(//中文), Japanese, and Korean. This allows programmers to use identifiers in their programs that are written in their native languages.(从这个角度看出,标识符也能够是文字,即字母实际上应归结为Java 字母更为准确)
An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.
标识符命名规范:
- 见名知意
- 遵循驼峰命名方式
- 类名和接口名首字母大写,后面每个单词首字母大写
- 变量名和方法名首字母小写,后面每个单词首字母大写
- 常量名所有字母大写,并且单词与单词之间采用下划线衔接
关键字
什么是关键字?
SUN公司开发Java语言时,提前定义好了一些具有特殊含义的单词,这些单词全都小写,具有特殊含义,不能作为标识符(为蓝色字体)(Public和public是不一样的)
变量
变量的分类和作用域
- 局部变量:在方法体中声明的变量(只在方法体中有效,执行结束该变量的内存就释放,存放在栈内存当中)
- 成员变量:在方法体之外,类体内声明的变量,分为以下两类:
- 静态变量(类变量,存放在方法区中)
- 实例变量(存放在堆内存当中))
作用域:变量出了大括号就不认识了(变量的有效范围 ) 在java语言中,平常不允许声明两个一样的变量,因为如果定义两个变量名一样的变量,系统识别调用时就会产生疑惑,不知道该调用哪个变量。而在if,for,while等结构体中声明的变量是局部变量,出了本身所在的{}就会被销毁,所以不用担心每次循环变量名冲突。比如下面例子:
问题:for语句中的变量存放在哪个区?
for(int i=0;i<10;i++){
Student s = new Student();
}
声明变量
语法:数据类型 变量名
变量赋值
初始化变量有两种方式:
- 声明时直接赋值
- 先声明,后赋值
char usersex='女';
或者
String username;
username="喵可三三";
另外,多个同类型的变量可以同时定义或者初始化,但是多个变量中间要使用逗号分隔,声明结束时用分号分隔。
String username,address,phone,tel; // 声明多个变量
int num1=12,num2=23,result=35; // 声明并初始化多个变量
注意!Java 中初始化变量时需要注意以下事项:
- 变量是成员变量时,如果没有显式地初始化,默认状态下创建变量并默认初始值为 0。
- 变量是局部变量时,必须显式地初始化,否则在使用该变量时就会出错。
- 访问变量时采用就近原则
public class VariableTest01 {
public static void main(String[] args) {
//测试成员变量
Test01 test01=new Test01();
System.out.println(test01.a); //结果:0
//测试局部变量
int i;
System.out.println(i); //报错:java: 可能尚未初始化变量i
}
}
class Test01{
public int a;
public Test01(){
}
//变量就近原则,this.a区分于形参的a
public Test01(int a){
this.a=a;
}
}