Java 中的局部变量
原文: https://javabeginnerstutorial.com/core-java-tutorial/local-variable-in-java/
让我们进一步了解 Java 中的局部变量。 在 Java 程序的方法中声明的变量称为局部变量。
局部变量规则
局部变量示例
package com.jbt;
/*
* Here we will discuss about different type of Variables available in Java
*/
public class VariablesInJava {
/*
* Below variable is INSTANCE VARIABLE as it is outside any method and it is
* not using STATIC modifier with it. It is using default access modifier.
* To know more about ACCESS MODIFIER visit appropriate section
*/
int instanceField;
/*
* Below variable is STATIC variable as it is outside any method and it is
* using STATIC modifier with it. It is using default access modifier. To
* know more about ACCESS MODIFIER visit appropriate section
*/
static String staticField;
public void method() {
/*
* Below variable is LOCAL VARIABLE as it is defined inside method in
* class. Only modifier that can be applied on local variable is FINAL.
* To know more about access and non access modifier visit appropriate
* section.
*
* Note* : Local variable needs to initialize before they can be used.
* Which is not true for Static or Instance variable.
*/
final String localVariable = "Initial Value";
System.out.println(localVariable);
}
public static void main(String args[]) {
VariablesInJava obj = new VariablesInJava();
/*
* Instance variable can only be accessed by Object of the class only as below.
*/
System.out.println(obj.instanceField);
/*
* Static field can be accessed in two way.
* 1- Via Object of the class
* 2- Via CLASS name
*/
System.out.println(obj.staticField);
System.out.println(VariablesInJava.staticField);
}
}
public class UserController {
// Instance variable
private String outsideVariable;
public void setLength()
{
//Local variable
String localVariable = "0";
// In order to use below line local variable needs to be initialzed
System.out.println("Value of the localVariable is-"+localVariable);
}
}
命名约定
命名局部变量没有特定的规则。 所有变量规则都适用于局部变量。
下面提到的是命名局部变量的规则。
- 变量名称区分大小写。
- 局部变量的长度没有限制。
- 如果变量名只有一个单词,则所有字符均应小写。
重点
- 局部变量不能使用任何访问级别,因为它们仅存在于方法内部。
Final
是唯一可以应用于局部变量的非访问修饰符。- 局部变量没有默认值,因此必须先启动局部变量,然后才能使用它们。