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

Solution 1:

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.

Solution 2:

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).

Solution 3:

One other difference is you don't have to worry about concurrent access to local variables; whereas you do with instance variables in a multi-threaded environment.

Solution 4:

No, you pretty much covered it. An instance variable belongs to an instance of a class, and a local variable belongs to a stack frame.

Instance variables are initialized to default values, but it's generally good practice to use explicit initializations anyway.