DEV Community

KIRUBAGARAN .K
KIRUBAGARAN .K

Posted on

Local Variable and Global variable

Local variables are declared inside a function or block and can be used only within that area, with a limited lifetime. Global variables are declared outside functions and can be accessed anywhere in the program, lasting throughout its execution.

local variable

A local variable is a variable that is declared inside a function, method, or block and can be used only within that specific area.

public class Demo {
    public static void main(String[] args) {
        int number = 10; // local variable
        System.out.println(number);
    }
}

Enter fullscreen mode Exit fullscreen mode

Here, number is a local variable because it is created inside the main method and cannot be used outside it.

global variable

A global variable is a variable that is declared outside of a function or block and can be accessed from different parts of the program.

public class Demo {
    static int number = 10; // global (class-level) variable

    public static void main(String[] args) {
        System.out.println(number);
    }
}

Enter fullscreen mode Exit fullscreen mode

Here, number is accessible anywhere inside the class, so it acts like a global variable.

Top comments (0)