全局变量:
定义在类中,方法外的变量叫做全局变量,全局变量所有方法均能够访问
局部变量
作用域从定义位置开始,到代码块结束。
public class Demo{
//全局变量
int b = 10;
public void test(){
//局部变量
int a = 10;
if(a>=10){
//局部变量
int b = a+1;
int c = b+1;
System.out.println(“小b的值是:”+b); =11
}
//局部变量,定义在方法中 在方法中有效
System.out.println(a); =10
//引用的是全局变量
System.out.println(b); =10
//错误的,超出了作用域的范围
System.out.println(c); (错误的)
}
public void test1(){
System.out.println(a); //错误
}
public void test2(){
System.out.println(b);
}
public static void main(String[] args){
Demo demo = new Demo();
demo.test();
}
}