Java基础教程
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
(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 ); } }