Java基础教程
作者: 时海
变量与常量

Java是强类型语言,即变量在使用前必须先声明,且该变量在后续的使用中不能改变类型。

1、Java变量命名规范

1)java变量名必须以 字母、下划线、美元符$开头(但不建议使用'$'字符开头),后面可以是字母、数字、下划线。

  •  有效的变量名例

        age1, m_int2, $ok3, _hello4

  • 非法的变量名例

        1invalid : 不能以数字开头

        invalid#a : 含有非法字符‘#’

(2)java变量名不能使用java保留的关键字,java保留的关键字如下:

  • abstract,assert,boolean,break,byte,case,catch,char,class,
    const,continue,default,do,double,else,enum,extends,final,
    finally,float,for,goto,if,implements,import,instanceof,int,
    interface,long,native,new,package,private,protected,public,
    return,strictfp,short,static,super,switch,synchronized,this,
    throw,throws,transient,try,void,volatile,while

2、实例变量和类变量

(1)实例变量是每创建一个实例对象,该实例对象将拷贝一份独立的变量副本,与其它实例互不影响。


public class Student {
    int age;

    double height, weight;  //同一行申明多个变量

    boolean sex = true;  //申明变量的同时给变量赋值

    String name = "Sam";

    public static void main(String[] args) {
        Student student = new Student();
        student.age = 26;
        student.height = 1.7;
        student.weight = 120;

        System.out.println(student.name + "," +
                student.age + "," +
                student.sex + "," +
                student.height + "," +
                student.weight + ",");
    }
}

(2)类变量是该类所有实例共享的变量,不论创建多少个该类的实例对象,类变量只会保存一份。

public class Student {
    static int age;

    static double height, weight;  //同一行申明多个变量

    static boolean sex = true;  //申明变量的同时给变量赋值

    static String name = "Sam";

    public static void main(String[] args) {

        //通过实例对象引用类变量
        Student student = new Student();
        student.age = 26;
        student.height = 1.7;
        student.weight = 120;


        System.out.println(student.name + "," +
                student.age + "," +
                student.sex + "," +
                student.height + "," +
                student.weight );

        //通过类名引用类变量
        System.out.println(Student.name + "," +
                Student.age + "," +
                Student.sex + "," +
                Student.height + "," +
                Student.weight );
    }
}



标签: student、变量、age、sex、申明
一个创业中的苦逼程序员
  • 回复
隐藏