Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Except the scope and the storage differences, are there any other major difference between instance and local variables in Java?

like image 915
GuruKulki Avatar asked Jan 18 '10 18:01

GuruKulki


1 Answers

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.

like image 146
Alex Ntousias Avatar answered Oct 13 '22 17:10

Alex Ntousias