示例程序1:
public class StudentDetails { public void StudentAge() { //local variable age int age = 0; age = age + 5; System.out.println("Student age is : " + age); } public static void main(String args[]) { StudentDetails obj = new StudentDetails(); obj.StudentAge(); } }
输出:
Student age is : 5
在上面的程序中,变量年龄是函数StudentAge()的局部变量。如果我们在StudentAge()函数外使用变量年龄,编译器将产生一个错误,如下面的程序所示。
示例程序2:
public class StudentDetails { public void StudentAge() { //local variable age int age = 0; age = age + 5; } public static void main(String args[]) { //using local variable age outside it's scope System.out.println("Student age is : " + age); } }
输出:
error: cannot find symbol " + age);