Java Scope
🔹 Java Scope
Scope in Java defines where a variable or method is accessible within a program. Understanding scope is crucial to avoid errors and write clean code.
✅ 1. Types of Scope in Java
-
Local Scope – Variables declared inside a method or block.
-
Instance Scope (Object Scope) – Variables declared inside a class but outside methods (non-static).
-
Class Scope (Static Scope / Global Scope) – Variables declared as static inside a class.
-
Block Scope – Variables declared inside loops, if statements, or other blocks.
✅ 2. Local Scope Example
Variables declared inside a method are accessible only within that method.
📌 Output:
Trying to access
numoutsidemainwill cause an error.
✅ 3. Instance (Object) Scope Example
Instance variables belong to an object of a class. Accessible in all non-static methods of the class.
✅ 4. Class (Static / Global) Scope Example
Static variables belong to the class, shared by all objects.
📌 Output:
✅ 5. Block Scope Example
Variables declared inside {} are accessible only within that block.
✅ 6. Key Points About Scope
| Scope Type | Declared Where | Accessible Where |
|---|---|---|
| Local | Inside a method | Only inside that method |
| Instance | Inside class, outside methods | All non-static methods of object |
| Class/Static | Inside class, static keyword | Anywhere via class reference |
| Block | Inside {} |
Only inside that block |
-
Variables should have the minimum required scope for better readability and safety.
-
Shadowing occurs when a local variable has the same name as an instance variable. Use
thisto refer to the instance variable.
