What is the difference between local and instance variables in Java?

The main differences that I see are in their:

Scope: Local variables are visible only in the method or block they are declared whereas instance variables can been seen by all methods in the class.

Place where they are declared: Local variables are declared inside a method or a block whereas instance variables inside a class, but outside a method.

Existence time: Local variables are created when a method is called and destroyed when the method exits whereas instance variables are created using new and destroyed by the garbage collector when there aren't any reference to them.

Access: You can't access local variables, whereas instance variables can be accessed if they are declared as public.

Where they are declared: Local variables are declared in a method or a block before they are called, whereas instance variables can be declared anywhere in the class level (even after their use).

Instance variables always have value, even if they are not assigned by the code (then they will have for example null, 0, 0.0, and false). For local variables, there must be an assigned value by the code. Otherwise the compiler generates an error.


One extra thing I can think of:

Instance variables are given default values, i.e., null if it's an object reference, and 0 if it's an int.

Local variables don't get default values, and therefore need to be explicitly initialized (and the compiler usually complains if you fail to do this).

Tags:

Java