DEV Community

S Sarumathi
S Sarumathi

Posted on

Global Vs Local Variable In Java

1. Global Variable:
Java technically does not have "global variables" like C or Python.
But in Java, variables declared inside a class but outside methods are treated like global variables.

These are also called:

  • Instance variables

  • Class variables (if static)

Example:

class Student {

    int age = 20;   // Global Variable
    void display() {
        System.out.println(age);
    }

    public static void main(String[] args) {
        Student obj = new Student();
        obj.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

  20
Enter fullscreen mode Exit fullscreen mode

Why This is Global Variable:

Because:

  • It is declared inside class

  • Outside method

  • Can be used in multiple methods

2.Local Variable:
A Local Variable is declared inside a method, constructor, or block.

It can only be used inside that method.

Example:

class Test {

    void display() {
        int num = 10;  // Local Variable
               System.out.println(num);
    }

    public static void main(String args[]) {
        Test obj = new Test();
        obj.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

10
Enter fullscreen mode Exit fullscreen mode

Top comments (0)