Variables in Java are named storage locations in a computer’s memory that can hold a value. They are a way to store information on our computer. Variables that we define in a Java program are accessed by a name that we give. Computer/JVM does the hard work to figure out where are they stored in the RAM.
All variables must be declared before the use. The form of variable declaration is
*type identifier* [ = *value* ][, *identifier* [= *value* ] …];
type: primitive data types or name of class or interface. identifier: name of variable. = value
: (optional) variable can be initialized by specifying equal sign and value. Here value
should be of same/compatible type as specified. To declara more than one variable of specified type, use comma-separated list.
eg int i, j, k;
int i = 1, j, k = 2;
Variables store:
- Primitives: fundamental values
- References: address of object.
Types of Variables
- Local Variables
- Instance Variables
- Static Variables
Local Variables
These variables are defined within a block, method or constructor. These variables are created when the block is entered, or the function/nethod is called and destroyed after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variables are declared, i.e., we can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined scope.
Instance Variables
These are non-static variables and are declared in a class outside of any method, constructor, or block.
As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
Initialization of an instance variable is not mandatory. Its default value is dependent on the data type of variable.
Instance variables can be accessed only by creating objects.
Static Variables
They are also called class variables.
Static variables are declared using the static
keyword within a class outside of any method, constructor, or block. They cannot be declared locally inside an instance method. Static block can be used be used to initialize static variables. static{}
There is only one copy of a static variable per class. Static variables are created at the start of program execution and destroyed automatically when execution ends.
Initialization of a static variable is not mandatory. Its default value is dependent on the data type of variable.
Block
Block is a group of zero or more statements enclosed within curly braces {}
.