Back to articles
Global Variable VS Local Variable

Global Variable VS Local Variable

via Dev.toDivya Divya

In Java, variables are classified based on where they are declared and how they are accessed. The two main types are global (class-level) variables and local variables. Understanding their scope and behavior is essential for writing efficient programs. What is a Global Variable in Java? Java does not support true global variables like some other languages. Instead, it uses class-level variables, which behave similarly. These variables are declared inside a class but outside any method. Types of Class-Level Variables Static Variable → Shared by all objects Instance Variable → Separate copy for each object Example: class Test { static int x = 10 ; // class-level (global-like) public static void main ( String [] args ) { System . out . println ( x ); } } OutPut What is a Local Variable? A local variable is declared inside a method, constructor, or block and can only be used within that scope. Example: class Test { public static void main ( String [] args ) { int y = 5 ; // local variable

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles