全局变量
一、什么是全局变量?
直接在类中声明的变量就叫做全局变量(又称成员变量)。
public class Student {
String name;
static int age;
public static void main(String[] args) {
Student student = new Student();
System.out.println(student.name);
System.out.println(age);//静态方法中可以直接调用静态变量;如果变量时非静态的,则静态方法只能通过对象调用
}
}
上面代码片段中,第2、3行即为直接在类中声明的全局变量,可以在这个类中任意地方被调用。
二、全局变量有默认值
如果在定义全局变量时未设置初始值,则系统会根据变量的类型自动分配初始值。
public class Test {
static int a;
static double b;
static char c;
static boolean d;
static String e;//String为引用型数据
public static void main(String[] args) {
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
}
}
运行结果为:
0
0.0
空
false
null
三、全局变量的作用域
全局变量定义后,其作用域是所在的整个类。
public class Test {
static int a;
public static void print(){
System.out.println(a);
}
public static void main(String[] args) {
System.out.println(a);
}
}
由于未赋初始值,故运行结果为:
0
0
局部变量
一、局部变量的定义位置
局部变量一般定义在方法中的参数、方法中定义的变量和代码块中的变量。
例如
public class Test{
{
int a=0;
System.out.println(a);
}
public static void print() {
int b=100;
System.out.println(b);
}
public static void main(String[] args) {
new Test();//用于执行代码块中的代码
print();
}
}
运行结果是:
0
100
二、局部变量的作用域
局部变量的作用域为从定义的位置开始到其所在的语句块结束。
例如,在下面代码片段的方法 Test 中,局部变量a的作用域为从“;”开始到“}”。
public static Test(){
int a=0;
System.out.println(a);
}
三、局部变量没有默认值
局部变量在使用前必须显示初始化或赋值,局部变量没有默认值。
注意下面错误示例
public class Test {
static void Way() {
int y;// 方法中的局部变量
System.out.println("y="+y);//程序在编译时报错
}
public static void main(String[] args) {
Way();
}
}
由于局部变量使用前必须要赋初值,因此代码第5行,在运行时会报错(如下图)。
Tips
①如果局部变量的名字与全局变量的名字相同,则在局部变量的作用范围内全局变量被隐藏,即这个全局变量在同名局部变量所在方法内暂时失效。
public class HT_use_this {
int a=0;
{
System.out.println(a);
int a=100;
System.out.println(a);
}
}
运行结果如下:
0
100
②如果在局部变量的作用域范围内访问该成员变量,则必须使用关键字this来引用成员变量。
例如
public class HT_use_this {
int a=0;
{
System.out.println(a);
int a=100;
System.out.println(this.a);
}
}
运行结果如下:
0
0
③声明局部变量时,数据类型前除final外不允许有其他关键字,其定义格式为:[final]数据类型 变量名 = 初始值。