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.

public class Main {
public static void main(String[] args) {
int num = 10; // local variable
System.out.println("Num = " + num);
}

// num is NOT accessible here
}

📌 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.

public class Person {
String name; // instance variable

void setName(String name) {
this.name = name; // refers to instance variable
}

void display() {
System.out.println("Name: " + name);
}

public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
p.display(); // Name: Alice
}
}


✅ 4. Class (Static / Global) Scope Example

Static variables belong to the class, shared by all objects.

public class Counter {
static int count = 0; // class variable

Counter() {
count++; // incremented for each object
}

public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

System.out.println("Total objects created: " + Counter.count);
}
}

📌 Output:

Total objects created: 3

✅ 5. Block Scope Example

Variables declared inside {} are accessible only within that block.

public class Main {
public static void main(String[] args) {
if (true) {
int x = 100; // block scope
System.out.println(x);
}
// System.out.println(x); // Error: x cannot be resolved
}
}

✅ 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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *