Understand and use local and global variables

Local and Global Variables in Java

🧩 Variables are like storage boxes that hold data. Think of them as labelled jars where you can put a number, a word, or a whole list of items.

In Java, the scope of a variable determines where you can see and use that jar. Two main scopes:

  • Local variables – only inside the block (method, loop, or conditional) where they’re declared.
  • Global variables (class fields) – accessible to all methods in the same class.

Local Variables: The Secret Locker

📦 Local variables live inside a method. They’re created when the method starts and disappear when it ends.

Analogy: Imagine a secret locker in a classroom. Only the teacher who opens that locker can see the notes inside. Once the class ends, the locker is locked again.

Key points:

  • Must be initialised before use.
  • Cannot be accessed from outside the method.
  • Memory is reclaimed automatically when the method finishes.

Global Variables: The Shared Whiteboard

🖊️ Global variables (also called class fields) are declared outside any method but inside the class. They’re visible to all methods in that class.

Analogy: Think of a shared whiteboard in the classroom. Anyone can write on it and read what’s written, as long as they’re in the same room.

Key points:

  • Can be declared static to belong to the class itself, not to any particular instance.
  • Can be accessed from any method using the class name (if static) or an object reference.
  • Memory persists for the lifetime of the program (or until the object is garbage‑collected).

Example Code

public class ScopeDemo {
    // Global variable (class field)
    private int counter = 0;

    public void increment() {
        // Local variable
        int temp = counter + 1;
        counter = temp;
    }

    public void display() {
        System.out.println("Counter: " + counter);
    }

    public static void main(String[] args) {
        ScopeDemo demo = new ScopeDemo();
        demo.increment();  // counter becomes 1
        demo.display();    // prints 1
    }
}
  

Notice how temp is only known inside increment(), while counter is shared across all methods.

Comparison Table

Scope Visibility Lifetime Typical Use
Local Only inside the method/block From method start to end Temporary calculations, loop counters
Global (class field) All methods in the class (or via class name if static) Program runs (or until object is destroyed) Shared data, configuration settings

Exam Tips

?? Remember the rule: A variable can only be used after it has been declared and initialised.

?? Scope matters: If you try to access a local variable from another method, the compiler will flag an error.

?? Static vs instance: Static fields belong to the class; instance fields belong to objects. Use static only when the data truly belongs to the class.

?? Naming conventions: Use camelCase for variables (e.g., studentScore) and start with a lowercase letter.

?? Practice: Write a small program that counts how many times a button is pressed. Use a global counter and a local variable for temporary calculations.

Quick Practice Question

Write a Java method calculateSum that takes two integers, adds them together, and returns the result. The method should use a local variable to store the sum. Then, in the main method, call calculateSum twice with different arguments and print the results.

Hint: The local variable will only exist inside calculateSum.

Key Takeaways

  • Local variables are private to their method and help keep code tidy.
  • Global variables (class fields) allow data to be shared across methods.
  • Always initialise variables before use.
  • Use clear, descriptive names and follow Java naming conventions.
  • Understanding scope is essential for debugging and for writing correct, maintainable code.

Revision

Log in to practice.

1 views 0 suggestions