What is the difference between static and non-static variables in Java

In Java, variables are used to store data or values that can be manipulated or accessed by a program. Java variables can be classified into two main categories: static and non-static. The main difference between static and non-static variables is their scope and the way they are initialized and accessed.

Static variables, also known as class variables, are declared using the static keyword and are shared by all instances of a class. They are initialized only once, at the start of the program, and remain in memory until the program terminates. Static variables are accessed using the class name, rather than an instance of the class, and can be modified by any instance of the class or by the class itself. Static variables are useful for values that are shared across all instances of a class, such as constants or global counters.

Non-static variables, also known as instance variables, are declared without the static keyword and are unique to each instance of a class. They are initialized when an object of the class is created and remain in memory until the object is destroyed. Non-static variables are accessed using an instance of the class and can only be modified by that instance or by methods within the class. Non-static variables are useful for values that are specific to each instance of a class, such as object state or object-specific counters.

In summary, static variables are shared by all instances of a class and can be modified by any instance or the class itself, while non-static variables are unique to each instance of a class and can only be modified by that instance or methods within the class.

 

The main differences between static and non static variables are:

 

Static variable Non static variable
Static variables can be accessed using class name Non static variables can be accessed using instance of a class
Static variables can be accessed by static and non static methods Non static variables cannot be accessed inside a static method.
Static variables reduce the amount of memory used by a program. Non static variables do not reduce the amount of memory used by a program
Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class.
Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.

Submit Your Programming Assignment Details