变量的作用域表示变量的范围。局部变量的作用域在方法内,即当在方法中创建变量时,无法在方法之外访问它。如果在此处观察以下示例,在 main 方法中创建一个名为 num 的变量,并尝试在另一个方法 (demo) 中访问它。
public class SampleTest {
String str = "Yiibai.com";
public static void main(String args[]){
int num = 999;
}
public void demo(){
System.out.println(num);
}
}
由于不能访问它之外的局部变量(方法的变量),编译器会产生一个错误,即 -
C:\Sample>javac SampleTest.java
SampleTest.java:7: error: cannot find symbol
System.out.println(num);
^
symbol: variable num
location: class SampleTest
1 error