Difference between a local, instance and static variable in Java

Java supports three types of variables, local, instance and static. This post explains the difference between a local, instance and static variable in Java

Local VariableInstance VariableStatic Variable
Defined within a method or a code blockDefined outside a method at the class levelDefined outside a method at the class level
Is only accessible in the method/code block where it is declaredIs accessible throughout the classIs accessible throughout the class
Remains in memory as long as the method executesRemains in memory as long as the object is in memoryRemains in memory as long as program executes
Does not require any special keywordDoes not require any special keyword but any access specifier (private, protected or public) can be specified. Typically, private or protected is usedRequires the static keyword to be specified. In addition, any access specifier (private, protected or public) can be specified. Typically, public is used
Requires to be initialized before it is usedIs given default value based on its data type, so does not require to be initialized before it is usedIs given default value based on its data type, so does not require to be initialized before it is used.

 

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set