DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

Global vs local variables in Java

When you write Java code, every variable has a home — a place where it lives and can be used. That home is called its scope. Today we'll learn about two kinds of variable homes: global and local.

Local variable — lives inside a method

A local variable is created inside a method. It only exists while that method is running. Once the method finishes, the variable disappears.

Think of it like this: A local variable is like a sticky note you write during a meeting. Once the meeting ends, you throw it away.

public class MyClass {

    public void sayHello() {

        String name = "Ravi";  // local variable

        System.out.println("Hello " + name);
    }
    // name is gone here — outside the method
}
Enter fullscreen mode Exit fullscreen mode

The variable name is only usable inside sayHello(). Try to use it anywhere else and Java will give you an error.

Local variable

  • Written inside a method
  • Only that method can use it
  • Dies when method ends
  • Must be given a value first
  • No default value

Global variable — lives inside the class

A global variable (also called an instance variable) is created inside the class but outside any method. All methods in that class can see and use it.

Think of it like this: A global variable is like a whiteboard in the office. Everyone in the room can read it and write on it at any time.

public class MyClass {

    String name = "Ravi";  // global (instance) variable

    public void sayHello() {
        System.out.println("Hello " + name);  // ✓ works
    }

    public void sayBye() {
        System.out.println("Bye " + name);    // ✓ also works
    }
}
Enter fullscreen mode Exit fullscreen mode

Global variable

  • Written inside the class
  • Outside any method
  • All methods can use it
  • Lives as long as the object
  • Gets a default value (0, null)

Both methods can use name because it's declared at the class level.

See both together

Here's a simple example that shows both in one class:

public class Student {

    String studentName = "Priya";  // global — all methods can use this

    public void showMarks() {
        int marks = 95;               // local — only lives inside showMarks()
        System.out.println(studentName + " scored " + marks);
    }

    public void showName() {
        System.out.println(studentName); // ✓ global, works fine
        // System.out.println(marks);   ✗ ERROR — marks is not here!
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)