一、命名规则
int a= 5; int a_12= 5; int $a43= 5; int a434= 5; ? ? //第一个字符是数字,是不符合规则的 int 34a= 5; |
? ?
二、使用完整的单词命名,而非使用缩写
在命名的时候,尽量使用完整的单词进行命名,比如name,moveSpeed,而不是使用缩写 n,m。
? ?
对比:
完整单词命名 √ | 缩写 × |
public?class?Hero { ?????//使用完整单词命名,易于理解 ????String name; ????float?hp; ????float?armor; ????int?moveSpeed; } | public?class?Hero { ????//使用缩写,不易理解 ????String n; ????float?h; ????float?a; ????int?m; } |
? ?
三、不能只使用关键字,但是可以包含关键字。
? ?
public class HelloWorld {? ????public static void main(String[] args) { ????????int class5 = 5;??????? ????} } |
? ?
四、关键字列表1
? ?
五、关键字列表2
? ?
六、变量可以用中文来命名
中文也是可以用来命名变量的?
但是在实际的开发工作中:别这么干
public class 余秋雨{ ????public void 耍流氓(){ ????????System.out.println("最怕流氓有权有文化"); ????} ???? ? ????public static void main(String[] args) { ??????? ?余秋雨 新雨对象 = new 余秋雨(); ??新雨对象.耍流氓(); ????} } |
? ?
七、练习与答案
题目:
思考如下变量命名是否合法,如果不合法,为什么??
1. int a_;
2. int a@;
3. int a3;
4. int 8@;
5. int 9_;
6. int X$_;
7. int y;
8. int _$_;
9. int $_$;
10. int $*$;
11. int $1$;
12. int _1_;
13. int _@_;
14. int a#;
15. int a";
16. int 123a";
17. int 123a_;
18. int $123b_;
? ?
官方答案:
public class HelloWorld { ????1. int a_; ????2. int a@; //@不能使用 3. int a3; ????4. int 8@; //@不能使用,数字不能是第一个字符 ????5. int 9_; //数字不能使是第一个字符 ????6. int X$_; ????7. int y; ????8. int _$_; ????9. int $_$; ????10. int $*$; //*不能使用 ????11. int $1$; ????12. int _1_; ????13. int _@_; //@不能使用 ????14. int a#; //#不能使用 ????15. int a"; //"不能使用 ????16. int 123a"; //数字不能是第一个字符,"不能使用 ????17. int 123a_; //数字不能是第一个字符 ????18. int $123b_; } |
? ?
? ?
? ?
? ?
原文:https://www.cnblogs.com/xlfcjx/p/10767618.html