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

  1. Local Scope – Variables declared inside a method or block.

  2. Instance Scope (Object Scope) – Variables declared inside a class but outside methods (non-static).

  3. Class Scope (Static Scope / Global Scope) – Variables declared as static inside a class.

  4. 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:

Num = 10

Trying to access num outside main will 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:

Total objects created: 3

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 this to refer to the instance variable.

You may also like...