Suppose, we want to perform addition of two numbers in our program. We can directly add 5+5. But, in program first we need to store these values somewhere in order to use it throughout our code. We need to store these values in our memory space. Here, variable act as a container which is a reserved area located in memory space to hold values for you during the life of a program. It has a size, and type (size and type – we will learn in Data type tutorial).
Now we know that- Variable is the name of memory allocation for storage of data whose value may vary. It’s a reserved area allocated in memory.
Example; a = 5, b = 5;
There are 3 types of variables in Java:
|Declared in Methods, Constructors or Blocks.||Declared in Class, but outside a Method, Constructor or Block.||Declared with static keyword in a Class, but outside a Method, Constructor or Block.|
|Local variables are created when the method, constructor or block is entered.||Instance variables are created when an object is created with the use of the keyword ‘new’.||Static variables are created when the program starts.|
|variable will be destroyed once it exits the method, constructor, or block.||variable will be destroyed when the object is destroyed.||variable will be destroyed when the program stops.|
|Access modifiers cannot be used for local variables.||Access modifiers can be given for instance variables.||Access modifiers can be given.|
|Local variables are visible only within the declared method, constructor, or block.||The instance variables are visible for all methods, constructors and block in the class.||Visibility is similar to instance variables.|
|There is no default value for local variables.
So, local variables should be declared and an initial value should be assigned before the first use.
|Instance variables have default values.
Ex: For numbers, the default value is 0, for Booleans it is false, and for object references it is null.
|Default values are same as instance variables.|
|Local variables can only be accessed within the method, constructors, blocks only.||Instance variables can be accessed directly by calling the variable name inside the class.||Static variables can be accessed by calling with the class name like