Java Variables and Scope
Java Variables
A variable is a container for storing data values. In Java, each variable has:
- A data type (e.g.,
int
,String
). - A name (identifier).
- An optional initial value.
Types of Variables
-
Local Variables:
- Declared inside a method, constructor, or block.
- Accessible only within that method or block.
- Not initialized by default.
public class LocalExample { public void display() { int localVar = 10; // Local variable System.out.println("Local Variable: " + localVar); } }
-
Instance Variables:
- Declared outside any method but inside a class.
- Belong to an instance of the class.
- Automatically initialized with default values.
public class InstanceExample { int instanceVar; // Instance variable public void display() { System.out.println("Instance Variable: " + instanceVar); } }
-
Static Variables:
- Declared with the
static
keyword. - Shared among all instances of the class.
public class StaticExample { static int staticVar = 50; // Static variable public static void display() { System.out.println("Static Variable: " + staticVar); } }
- Declared with the
Scope of Variables
The scope determines where a variable can be accessed or modified in the program:
-
Local Scope:
- Variables declared inside a method or block.
- Only accessible within that method or block.
public void method() { int x = 10; // Local scope System.out.println(x); }
-
Instance Scope:
- Instance variables are accessible by all methods of the class (if not private).
public class Example { int y = 20; // Instance variable public void method() { System.out.println(y); // Accessible } }
-
Class/Static Scope:
- Static variables are accessible across all methods (if not private).
public class Example { static int z = 30; // Static variable public static void display() { System.out.println(z); // Accessible } }
-
Block Scope:
- Variables declared inside loops or conditional blocks.
- Accessible only within that block.
public void blockScope() { for (int i = 0; i < 5; i++) { System.out.println(i); // Accessible here } // System.out.println(i); // Error: 'i' not accessible }
Example Demonstrating All Scopes:
public class VariableScopeExample {
static int staticVar = 100; // Static scope
int instanceVar = 50; // Instance scope
public void method() {
int localVar = 10; // Local scope
if (localVar > 5) {
int blockVar = 20; // Block scope
System.out.println("Block Variable: " + blockVar);
}
// System.out.println(blockVar); // Error: blockVar is not accessible here
System.out.println("Local Variable: " + localVar);
}
public static void main(String[] args) {
VariableScopeExample example = new VariableScopeExample();
example.method();
System.out.println("Instance Variable: " + example.instanceVar);
System.out.println("Static Variable: " + staticVar);
}
}
Tags:
java