Thursday, 2 July 2015

VARIABLES IN JAVA

VARIABLES IN JAVA

JAVA supports 6 types of variables
1. Local variable
2. Static variable
3. Instance variable
4. Final variable
5. Transient variable
6. Volatile variable

LOCAL VARIABLE:
If the variable is declared within a block (block of method, block of constructor, Block of loop, block of if or else, block of switch or case, or any general block)   it is known as local variable.

class Test{
-------block-------
}

We cannot make the local variable as public
We cannot make the local variable as public , private or protected because the local variable can only be accessed within the same block , but the public access specifier makes the variable global. Thus it is not possible.
In short, no access specifier is used for a local variable.
Private makes it accessible within the same class.
Local variable is only able to access within the same block in which it is declared.

Local variable is not a member of the class or object, so it can't be called by class name or object name. It only accesses directly within the same block. Before using the local variable, that variable should be initialised.

Static variable
If the variable is declared within the class and not within the block, with a static keyword, then it is known as static variable. Static variable is known as class level variable. This type of variable can be called by class_name or object_name, within the same class as well as outside , it's possible to call a static variable within the same class directly.
Static variable creates a single copy for the whole program.

Instance variable.
This is known as object level variable, because Instance Variable only allocates memory at the time of the object creation.
If the variable is within the class and not within the block without any static keyword, it is known as non static or instance variable. Instance variable only can be called by the object name.

Final variable.
If the variable is declared with a "final" keyword, then it is known as final variable.
JAVA never supports any "const" keyword to declare a constant. If the variable is declared with a "final" keyword, then it is constant in JAVA.
Final variable may or may not be static in JAVA, by its better for programmer to declare the Final variable as Static.