Scope of Variable in Java
The scope of variables in Java refers to the visibility or accessibility of a variable within a program. It determines where a variable can be used and accessed, and it helps ensure proper variable management and prevent conflicts or errors.
In Java variables can be declared and defined within different contexts such as classes, methods or blocks. The scope of a variable depends on where it is declared and defined and it affects where the variable can be accessed within the program.
- Variables declared inside a block or method are only accessible within that specific block or method. Accessing them from outside will result in a compilation error.
- The scope of a variable can be nested, meaning that variables declared within inner blocks or methods are visible only within those specific inner scopes.
- Variables can be declared anywhere in the program but their visibility is limited to the scope in which they are declared.
- Variables can be used as parameters for methods or constructors allowing us to pass values and use them within the corresponding method's scope.
- Within the body of a method or constructor, we can define and declare variables for specific calculations or operations, keeping their scope local to that method.
- We can also define variables inside blocks and loops, providing temporary storage for iterative tasks, with their scope limited to those specific blocks or loops.
Scope of Variable:
1. Local Variables:
- Local variables are declared within a method, constructor or block.
- They have a limited scope and are only accessible within the specific context where they are declared.
- Local variables are created when their declaration statement is executed and are destroyed when the method constructor or block completes execution.
- They must be initialized before they can be used.
- Local variables are not accessible from outside the method and constructor or block in which they are declared.
- Each invocation of the method or block creates a new set of local variables.
- Local variables can shadow variables with the same name declared in outer scopes.
2. Instance Variables (Non-static Variables):
- Instance variables are declared within a class but outside any method or block.
- They have class level scope and are accessible throughout the class.
- Instance variables are created when an object of the class is instantiated and are destroyed when the object is garbage collected.
- Each object of the class has its own set of instance variables.
- Instance variables can be accessed and modified by any method or block within the class.
- They can have default values if not explicitly initialized.
- Instance variables are used to hold data specific to each object of the class.
3. Class Variables (Static Variables):
- Class variables are declared with the static keyword within a class but outside any method or block.
- They have class level scope and are accessible throughout the class.
- Class variables are created when the class is loaded into memory and are destroyed when the class is unloaded.
- Unlike instance variables there is only one copy of a class variable shared among all instances of the class.
- Class variables can be accessed and modified by any method or block within the class regardless of object creation.
- They can have default values if not explicitly initialized.
- Class variables are commonly used to store data that needs to be shared among all objects of the class.
Example:
FileName: VariableExample.java
import java.util.*; public class VariableExample { // Instance variable (non-static) private int instanceVariable; // Class variable (static) private static int classVariable; public void exampleMethod() { // Local variable int localVariable=10; // Accessing and modifying instance variable instanceVariable=20; // Accessing and modifying class variable classVariable=30; // Printing values System.out.println("Local variable: "+localVariable); System.out.println("Instance variable: "+instanceVariable); System.out.println("Class variable: "+classVariable); } public static void main(String[] args) { VariableExample example=new VariableExample(); // Accessing instance method example.exampleMethod(); // Accessing class variable classVariable=40; // Printing class variable System.out.println("Class variable (outside the class): "+classVariable); } }
Output:
Local variable: 10 Instance variable: 20 Class variable: 30 Class variable (outside the class): 40
Types of variables based on Scope:
1. Member Variables (Class Level Scope):
Member variables are also known as instance variables or fields are declared within a class but outside any method or block. They have class level scope It means they are accessible throughout the class and can be used by any method or block within the class.
- Class objects are connected to member variables.The member variables are copies that are contained within each class object.
- They are produced when an object of the class is instantiated and remain in existence for the duration of the object's existence.
- Any method or block in the class has access to and control over member variables.
- They can have default values if not explicitly initialized.
- Data particular to each object in the class is stored in member variables.
- Attributes like name, age, or any other state data pertaining to the objects in the class are examples of member variables.
Syntax:
public class ClassName { // Member variables data_type variable_name1; data_type variable_name2; // ... // Constructor, methods, etc. }
Implementation:
FileName: MemberVariableExample.java
import java.util.*; public class MemberVariableExample { // Member variables (class-level scope) private String name; private int age; // Constructor public MemberVariableExample(String name,int age) { // Assigning values to member variables this.name=name; this.age=age; } // Method to display member variables public void displayInfo() { System.out.println("Name:"+name); System.out.println("Age:"+age); } public static void main(String[] args) { // Creating an instance of MemberVariableExample MemberVariableExample example=new MemberVariableExample("Rahul",20); // Accessing member variables and calling methods example.displayInfo(); } }
Output:
Name:Rahul Age:20
2. Local Variables (Method Level Scope):
Local variables are declared within a method, constructor, or block. They are only usable in the precise context in which they are stated since they have method-level scope.
- Local variables are temporary and exist only within the method, constructor, or block in which they are declared.
- They are created when their declaration statement is executed and destroyed when the method, constructor, or block completes execution.
- Prior to use the local variables must be initialised.
- Outside of the method, constructor or block in which they are declared, local variables cannot be accessed.
- Local variables are created with each call to the function or block.
- Local variables are commonly used for temporary storage or calculations within a method or block.
Syntax:
public class ClassName { public void methodName() { // Local variables data_type variable_name1; data_type variable_name2; // ... // Statements } // Other methods, constructors, etc. }
Implementation:
FileName: LocalVariableExample.java
import java.util.*; public class LocalVariableExample { public void printMessage() { // Local variable declaration and initialization String message="Hello, world!"; // Printing the local variable System.out.println(message); // Modifying the local variable message="Goodbye!"; // Printing the modified local variable System.out.println(message); } public static void main(String[] args) { // Creating an instance of LocalVariableExample LocalVariableExample example=new LocalVariableExample(); // Calling the printMessage method example.printMessage(); } }
Output:
Hello, world! Goodbye!