- Local
- Instance
- Static
Let’s discuss these variables in detail.
1. Local Variables
A local variable is specified inside a method however, other methods in the class have no access to this variable.
2. Instance Variables
Instance variables are specified outside a method but within the class and without the using the keyword static. Since these variables have instance-specific values so these are called instance variables.
3. Static Variables
Static variables are specified only once and shared wih other instances of a particular class. Moreover, these are declared at the start of the program execution.
Here is an example.
static int x =10; //This is a static variable
int y = 15; // This is an instance variable
void method ( ) {
int z = 20; // This is a local variable
}
}
Before you begin working with Java variables you need to be aware of two variable relevant concepts and these are:
1. Variable Declaration
Variable declaration is the procedure of specifying the data type and unique name of the variable.
Syntax:
Examples:
2. float pi;
3. double area;
4. char flag;
2. Variable Initialization
Variable initialization is the procedure of giving an authentic value to the variable.
Syntax
Examples
2. pi=3.14;
3. area=32345.65;
4. char= 'a';
Java Variable Types
Java variables can also be categorized by the type of value they store in them. On the basis of the value stored, Java variables can be classified into the following types.
- string
- int
- float
- char
- boolean
These are discussed in detail below.
1. string
String store text and these are always written inside inverted commas. For example,
2. int
Int variables store whole numbers. For example,
3. float
Float is used to store decimal numbers. For example,
4. char
Char variables are used to store single characters and these are always written inside single quotes. For example,
5. boolean
Boolean variable store values that are either true or false.
Conclusion
Variables are entities that store data values while a Java program is being executed. Java variables, in general, are of three types that are local variables, instance variables, and static variables. Java variables can also be classified into categories on the basis of the type of value they store such as string, int, float, char, and boolean. All of these variables along with suitable examples are explained in detail in this write-up.