
Variables in Java is the name you give to the memory area that holds the value during the execution of the Java program. You can use both the “field” as well as “Variable” in the in the programming language.
A program generally acts on data, processes it, and provides the results. So data and data types are very important concept of a program.
You must specify the type and need to assign the value to create a variable in Java.
Table of Contents
Types of Variables based on Data Types
There are two type of variables are available based on data types:
- Primitive Variables
- Reference Variables
Types of Variables based on positions
There are three type of variables are available based on positions:
- Instance Variables (Non-Static Fields)
- Class Variables (Static Fields)
- Local Variables
Primitive Variables in Java
Primitive Variable represents the primitive values. For example, You declare a variable with byte, short, int, long etc.
int x = 10;
Reference Variables in Java
Reference Variable refers an object of a class when you need to keep an object to variable.
Employee emp = new Employee();
Instance Variables or Non-Static Fields
The value of the instance or no-static variable varies from object to object that’s the reason the value of such type of variable are unique to each instance of a class.
public class Example { // Class Name
private int instanceVar = 20; // Instance Variable
public static void main(String[] args) {
}
}
Class Variables or Static Fields
The value of the class variable or static field doesn’t vary from object to object. We declare a static variable or class variable with the static modifier. No matter how many times the class has been instantiated there will be exactly one copy of this variable.
public class Example { // Class Name
private static staticVar = 20; // Static Variable
public static void main(String[] args) {
}
}
Local Variables in Java
The local variables are only visible to the methods in which we declare because we declare a variable inside the method only, they are not accessible from the rest of the class.
- Automatic variables or Stack Variables or temporary variables are the terminology you can user other than local variables.
- You must declare before using it because for local variable JVM doesn’t provide any default value.
- Compulsory we should perform initialization explicitly before using local variable.
- You can only use “final” modifier for the local variable otherwise you will get compile timer error.
public class Example { // Class Name
void display() {
int localVar = 20;
}
}