Java 变量、常量、作用域

209 阅读1分钟

go

public class Day03 {
    //实列变量,属于对象;
    String name;
    double d;
    boolean e;
    char f;
    //类变量 static。跟随其所在类走;
    static final float STABLE_VALUE = 8798794.2f;//修饰符不讲究顺序;

    public static void main(String[] args) {
        //为了规范不要int a=0,b=0,c=0;
        int a = 0;
        int b = 0;
        int c = 0;//规范定义变量;
        System.out.println("============================");
        //局部变量,必须申明和初始化;只在其所在的大括号内使用;
        int a1 = 1;
        System.out.println(a1);
        Day03 day03 = new Day03();//对象实列化
        System.out.println(day03.name);
        System.out.println(day03.d);
        System.out.println(day03.e);
        System.out.println(day03.f);//char类型的默认值是\u0000 即空值
        System.out.println("实列变量不需要要初始化,会有默认值");//基本数字类型默认值都是0。布尔是false。char是\u0000,即空。其它都是null
        System.out.println("===================================");
        System.out.println(STABLE_VALUE);



    }
}

定义变量总结

  1. 为了规范不要一行定义多个变量
  2. 局部变量,必须申明和初始化;只在其所在的大括号内使用
  3. 实列变量不需要初始化,会有默认值。基本数字类型默认值都是0。布尔是false。char是\u0000,即空。其它都是null
  4. 实列变量,属于对象。
  5. 类变量即static修饰。跟随其所在类走。

变量的命名规范

  1. 所有变量、方法、类名:要见名知意。
  2. 类成员变量和局部变量:首字母小写和驼峰原则,如lastName
  3. 常量大写字母和下划线,如MAX_VALUE
  4. 类名:首字母大写和驼峰原则Man、SuperGirl
  5. 方法名:首字母小写和驼峰原则add()、addAll()