变量、常量

变量

变量的作用域

变量作用域分为:类变量、实例变量、局部变量

类变量

从属于类,会随着类一起出来,一起消失。

public class Demo2 {
    //类变量 static
    static double salary = 2500;
    public static void main(String[] args) {
        System.out.println(salary);
    }
}

实例变量

写了就可以用,从属于对象,如果不初始值,则为这个类型的默认值。

public class Demo01 {
    //实例变量
    String name;
    public static void main(String[] args) {
    Demo01 demo01 = new Demo01();
        System.out.println(demo01.name);
    }
}

局部变量

public class Demo01 {
    public static void main(String[] args) {
        double salary = 2500;
        System.out.println(salary);
    }
}

 

常量

常量初始化后就不能改变,常量名一般是使用大写字符。

初始化:final 常量名 = 值;

public class Demo02 {
    static final double PI = 3.14;
    public static void main(String[] args) {
        final int AGE = 20;
        System.out.println(PI);
        System.out.println(AGE);
    }
}
posted @ 2022-09-19 16:41  十六夜。  阅读(25)  评论(0)    收藏  举报