What Are Variables In Java?
A variable in Java is a storage location in memory with a name where data values can be kept. Variables allow developers to save, edit and reconstruct the data when they perform a program. Each variable has another data type that determines the type of data that can be stored in it. This can be the entire number, decimal number, a character or a text line.
Types of Variables in Java
There are 3 primary types of variables in Java. Every variable has its own guidelines for how to use it and what its scope is. These types help gather data and manage how variables are accessed within a program.
1. Local Variables
Local variables in Java are defined within blocks, constructors, or methods. Only the method, constructor, or block in which they are defined has access to these variables.
Example Of Local Variable:
public class LocalVariableExample {
public void showNumber() {
int number = 25; // Local variable
System.out.println("The value of the local variable is: " + number);
}
public static void main(String[] args) {
LocalVariableExample example = new LocalVariableExample();
example.showNumber(); // Calling the method to print the value of the local variable
}
}
2. Instance Variables
Although it is declared outside of any method, constructor, or block, an instance variable is part of a class. Since instance variables are exclusive to each object derived from the class, they can be used to hold information that is specific to each object. If an instance variable has not been given an explicit value, it will always get a default (but potentially garbage) value and it is accessible anywhere from the class methods, although to access it, there must be an object to reference it.
Example of an Instance Variable:
public class Car {
// Instance variable
int speed = 60;
// Method to display the value of the instance variable
public void displaySpeed() {
System.out.println("The speed of the car is: " + speed);
}
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car();
// Calling the method to display the speed
myCar.displaySpeed();
}
}
3. Static Variables
Java static variables are declared using the word static chave and belong to the class instead of individual objects. This means that only a copy of the stable variable is shared by all examples of orbit. Static variables receive standard values automatically assigned if they are not explicitly initialized.
Example of Static Variable:
public class Counter {
// Static variable
static int count = 0;
// Method to display the static variable
public static void displayCount() {
System.out.println("Count: " + count);
}
// Method to increment the count
public static void incrementCount() {
count++;
}
public static void main(String[] args) {
// Accessing and modifying static variable using the class name
Counter.incrementCount();
Counter.incrementCount();
Counter.displayCount(); // Outputs: Count: 2
}
}
What Are Local Variables In Java?
Local variables are declared within methods, builders or code blocks. Their scope is limited to the block where they are defined. This means that they cannot be used outside this block. These variables are made when the program enters the block and is destroyed when the block is finished. Local variables are used to temporarily store data when executing the method or loop recurrence.
Characteristics of Local Variables:
There are 5 main characteristics of local variables in Java. These are essential details you should know.
- Limited Scope: The scope of a local variable starts where it is declared and ends when the block finishes.
- Temporary Lifetime: These variables are created when the block of code starts and deleted when it ends.
- No Default Values: Unlike instance or static variables, local variables do not automatically have default values. They must be initialized before use.
- Cannot Use Access Modifiers: Public, private, and protected variables cannot be used with local variables.
- Must Be Initialized: Compilation errors occur when a local variable is used before being assigned a value.
How to Declare Local Variables In Java?
To declare local variables, use this simple format:
// Syntax
dataType variableName;
Local Variables In Java With Example:
public void exampleMethod() {
int number = 10; // Local variable declaration
System.out.println(number);
}
Output:
10
Explanation of Code:
- The method exampleMethod() creates a local variable called number and sets it to 10.
- The statement System.out.println(number); shows value of number variable as 10.
Scope of Local Variables In Java
The area of code where a local variable is accessible is referred to as its scope. A local variable's scope extends from where it is declared to the end of the block where it is declared.
Local Variables In Java Code:
public void scopeExample() {
int a = 5; // Scope of 'a' starts here
if (a > 0) {
int b = 10; // Scope of 'b' is limited to this block
System.out.println(b);
}
// System.out.println(b); // This would cause an error since 'b' is out of scope
}
Output:
10
Explanation Of Code:
- The local variable a is displayed with a value of 5, and its scope starts from the declaration and ends when the method ends.
- Inside the if block, the variable b is declared with a value of 10. Its scope is limited to the if block.
- The System.out.println(b); inside the if block prints the value of b, which is 10.
Initializing Local Variables In Java
Always provide a starting value for your local variables. The compiler enforces this rule, so attempting to read a variable that was declared but left unwritten will result in a compilation error, you won’t get to run the program until you fix the oversight.
Initialization Of Local Variables In Java Code:
public void initExample() {
int value; // Declaration without initialization
// System.out.println(value); // Error: 'value' is not initialized
value = 20; // Initializing the variable
System.out.println(value); // Now it works
}
Output:
10
Explanation Of Code:
- The local variable value is declared but not initialized. Local variables must be explicitly initialized before use, or attempting to use them will result in a compilation error.
- The line System.out.println(value); is commented out in the code because it attempts to access value before initialization, which is not allowed in Java.
- Once a value is initialized with the value 20, the System.out.println(value); statement correctly prints 20.
Types of Local Variables in Java
In Java, local variables are variables displayed inside a method or a block of code. They are important for managing temporary data and controlling memory use. There are three main types of local variables:
1. Method Local Variables
Local variables are declared within methods, builders or code blocks. Their scope is limited to the block where they are defined. This means that they cannot be used outside this block. These variables are made when the program enters the block and is destroyed when the block is finished. Local variables are used to temporarily store data when executing the method or loop recurrence.
Method Local Variable Code:
public class Example {
public void myMethod() {
int a = 10; // Method local variable
System.out.println("Value of a: " + a);
}
public static void main(String[] args) {
Example example = new Example();
example.myMethod();
}
}
Output:
Value of a: 10
Explanation of the Code:
The Example class contains a method called myMethod(). Inside myMethod(), a method local variable a is declared and initialized with the value 10. This value is then printed to the console.
In the main method, an instance of the Example class is created, and myMethod() is called. When the myMethod() is invoked, the value of a is printed, and since a exists only within the scope of myMethod().
Time and Space Complexity:
- Time Complexity: O(1), as there is only one print statement and a simple variable initialization with no iterations or complex operations.
- Space Complexity: O(1), as we only use a constant amount of memory to store the method's local variable a.
2. Block Local Variables
Block local variables in Java are defined within specific code blocks, such as inside conditional statements (if-else) or loops (for, while). They only cover the block in which they are declared.
These variables are generated when the block is recorded and destroyed when it is out of the block, which confirms that they are accessible only during the execution of that particular block. Block local variables cannot be accessed outside the block, which limits their use to specific conditions.
Block Local Variable Code:
public class BlockExample {
public void checkValue(int x) {
if (x > 0) {
int y = 20; // Block local variable
System.out.println("y: " + y);
}
// System.out.println(y); // This would cause a compilation error as y is outside the block
}
public static void main(String[] args) {
BlockExample example = new BlockExample();
example.checkValue(5);
}
}
Output:
y: 20
Explanation of the Code:
In the checkValue() method, an if block checks if the value of x is greater than 0. Inside the block, a variable y is declared and initialized with the value 20, and it is printed to the console. Because y is a block local variable, it is only accessible inside the if block. When trying to access y outside of this block (e.g., in the commented System.out.println(y)), a compilation error occurs. In the main method, the checkValue() method is called with the argument 5, and since 5 > 0, the value of y is printed.
Time and Space Complexity:
- Time Complexity: TO(1), as it contains a simple conditional check and a single print statement with no iterations or complex operations.
- Space Complexity: The space complexity is O(1), as only a constant amount of memory is used to store the block local variable y, which exists only within the if block.
3. Loop Local Variables
Loop local variables in Java are declared within a loop (eg: for or while loop) and can only be used within the loop. They are created at the start of each iteration of the loop and are destroyed once the loop finishes executing. Because of their limited scope, these variables are not accessible outside of the loop.
Loop Local Variable Code:
public class LoopExample {
public void loopMethod() {
for (int i = 0; i < 5; i++) { // i is a loop local variable
System.out.println("Iteration: " + i);
}
// System.out.println(i); // This causes an error as i is outside the loop
}
public static void main(String[] args) {
LoopExample example = new LoopExample();
example.loopMethod();
}
}
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Explanation of the Code:
In the loopMethod(), a for loop runs five times with the loop variable i initialized to 0. The loop runs until i is less than 5, and the value of i is printed to the console during each iteration.
After the loop finishes, the variable i is no longer accessible because it is a loop local variable. If you attempt to access i outside the loop, like in the commented-out System.out.println(i);, you experience a compilation error due to its limited scope within the loop.
Time and Space Complexity:
- Time Complexity is O(n), n is the total no.of iterations the loop. Since the loop iterates five times (from 0 to 4), the time complexity is O(5), which simplifies to O(1). The time complexity depends on the number of iterations.
- Space Complexity: O(1), because the only extra memory used is for the loop local variable i, and its memory requirement does not increase with the input size.
Conclusion
Local variables are a necessary tool for writing clean and efficient Java programs. They help in temporarily storing data, managing calculations, and controlling loop behavior. By understanding their characteristics and best practices, you can improve your programming skills and create code that is easy to understand and maintain.
Frequently Asked Questions
1. What is the difference between local and global variables in Java?
Local variables are declared inside methods or blocks and are only accessible within those methods or blocks. Any method in that class can access global (or instance) variables, which are declared at the class level.
2. What are local variables with an example?
Local variables are those declared inside a method or block. For example, in the method void example() { int x = 5; }, x is a local variable and can only be used inside the example() method.
3. Do local variables have default values in Java?
No, local variables do not have default values. They need to be given a value before they can be used or a compilation error occurs.
4. Can local variables be declared as static?
No, local variables cannot be declared as static because they are specific to the method or block and are created every time that method is called.
5. How is the memory allocated for local variables?
Stack memory is where local variables are kept. They are created when the method is called and removed once the method completes executing.
6. Can we access local variables from inner classes?
Yes, you can access local variables from inner classes, but they must be declared as final or actually final.
7. What happens to local variables after method execution?
Local variables are eliminated after the method completes execution. Their memory is released, and they cannot be accessed again.
8. Are local variables thread-safe?
Yes, local variables are thread-safe because each thread has its stack. Therefore each thread has its instance of a local variable.