Variables that are declared inside a method, constructor, or block are called local variables in Java. They are accessible only within that scope in which they are defined. Therefore, the scope of these variables is limited to the block, method, or constructor where they are declared.
Local variables are not accessible outside their scope due to scoping rules. In other words, local variables are visible within the methods only and, therefore, their scope is local.
Following are the key points of local variables in Java. They are as follows:
- Local variables are limited to the block where they are defined.
- These variables are created when a method is called, and destroyed when the execution of the method or block is complete. In other word, local variables exist only during the execution of the method or block.
- If you try to access local variables outside the method, the compiler will generate an error.
- You can declare the same variable name within several methods without there being a conflict.
- Local variables must be declared and initialized within the method. Before initializing local variables, you cannot access them within the method.
- Local variables are stored in the stack memory, which allows for fast memory allocation and deallocation.
- Formal parameters are local variables in Java. Parameters passed to a method are treated as local variables within that method.
Syntax to Declare Local Variables in Java
The general syntax to declare a local variable in Java is as follows:
data_type variable_name = value;
For example:
int count = 5;
Here, int represents the data type, count is the name of variable and 5 is the value assigned to the variable count.
Rules for Declaring Local Variables in Java
There are the following rules to declare local variables in Java that you should remember. They are:
- You cannot apply access modifiers with local variables.
- Only final is the non-access modifier that you can apply while declaring a local variable. You can use the final modifier with local variables to indicate that their value cannot be reassigned after initialization.
- Unlike instance or static variables, local variables are not assigned a default value. Therefore, they need to be initialized at the time of declaration.
Basic Example of Local Variables
Example 1: Let’s write a Java program in which we will use of local variable inside the method.
package myProgram;
public class Person{
public void displayInfo() {
String name = "John"; // local variable
System.out.println("Name: " + name);
}
public static void main(String[] args) {
// Creating an object of class Person.
Person person = new Person();
// Calling displayInfo() method.
person.displayInfo();
}
}
Output:
Name: John
In this example, we have declared a local variable named name of string type inside an instance method. This variable is created when the method is invoked and destroyed when the method exits.
Local Variable Type Inference (var)
From the Java 10 version onwards, you can also use the var keyword to declare local variables. The compiler infers the type based on the value assigned. However, you cannot use the var keyword for uninitialized local variables.
Example 2:
package myProgram;
public class VarExample {
public void display() {
var message = "Hello Java!"; // Type inferred as String
System.out.println(message);
}
public static void main(String[] args) {
VarExample example = new VarExample();
example.display();
}
}
Output:
Hello Java!
Variable Shadowing in Java
When you declare a local variable in a method that has the same name as a variable declared outside the scope, shadowing takes place. In this case, the inner local variable “shadows” the outer one. Let’s take an example and see how?
Example 3:
package myProgram;
public class Test {
String name = "Bob"; // Instance variable.
public void display() {
// Local variable has the same name as instance variable name.
String name = "John";
System.out.println(name);
}
public static void main(String[] args) {
Test t = new Test();
t.display();
}
}
Output:
John
Final Local Variables in Java
You can declare a local variable with the final keyword in Java. When you declare a local variable with final, it must be initialized at the time of declaration. After initialization, you cannot reassign a final local variable.
Example 4:
package myProgram;
public class FinalVariableExample {
public void display() {
final int number = 10;
// number = 20; // Error: Cannot assign a value to final variable 'number'
System.out.println("Final number: " + number);
}
public static void main(String[] args) {
FinalVariableExample example = new FinalVariableExample();
example.display();
}
}
Output:
Final number: 10
Local Variables in Loops
In Java, we commonly use local variables as loop control variables while using for loop.
Example 5:
public class LoopExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) { // Here, i is a local variable.
System.out.println("Value of i: " + i);
}
}
}
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Common Errors with Local Variables
Example 6: Accessing Uninitialized Variables
package myProgram;
public class UninitializedVarEx {
public static void main(String[] args) {
int number;
System.out.println(number); // Accessing uninitialized local variable.
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable number may not have been initialized
Example 7: Accessing Outside Scope
package myProgram;
public class Test {
void display() {
String name = "Bob"; // local variable.
}
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.name); // Accessing local variable from outside.
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
name cannot be resolved or is not a field
Quizzes
Q1: What will be the output of the following code?
package myProgram;
public class Test {
public static void main(String[] args) {
int x = 5;
{
int x = 10;
System.out.println(x);
}
}
}
Options:
- 5
- 10
- Compilation Error
- Runtime Error
Answer: Compilation Error
This is because variable ‘x’ is already defined in the scope.
Q2: What will happen if you uncomment the line in the following code?
package myProgram;
public class Test {
public static void main(String[] args) {
final int x = 100;
// x = 200;
System.out.println(x);
}
}
Options:
- The program will run successfully.
- Compilation Error.
- Runtime Error.
Answer: Compilation error.