在块、方法或构造函数中定义的变量称为局部变量。
- 这些变量在进入块时创建,或者函数在退出块后被调用和销毁,或者调用从函数返回时被创建。
- 这些变量的作用域只存在于声明变量的块内,即我们只能在该块内访问这些变量。
- 在定义的范围内使用局部变量之前,必须对其进行初始化。
代码示例:
/*package whatever //do not write package name here */
// Contributed by Shubham Jain
importjava.io.*;
classGFG {
publicstaticvoidmain(String[] args)
{
intvar =10;// Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: "+ var);
}
}
|
输出结果:
局部变量:10