In this article we learn what is variables in java and types of variables in java with examples.
Variables In Java (Java Variables)
Variables in java is a name of memory location that holds the data value of a particular data type.
A variable in Java is a kind of container that contains the value during program execution.
Syntax of variables
datatype variableName=Value ;
Types of Variables In Java
There are two types of variables:
- Local Variables
- Global Variables
1. Local Variables In Java
What Is Local Variable?
- Variable is a container which holds the value
- Variable is name of memory location
- Variable always declare with data type.
- Variable which is present inside the method is called local variable.
Why We Use Local Variable?
- To store the value, we use variable.
- To maintain the scope of value within the method, we use local variable.
- To maintain the heap memory, we use local variable.
When We Use Local Variable?
- When we want to store the value at method level, we use local variable.
- When we don’t want to give scope of value outside the method, we use local variable.
How We Use Local Variable?
- Local variable always declare inside the method
- Syntax of variable: data_type variable_name = value;
Example of Local Variable:
public class Trials {
void method() {
int n = 90; // local variable
System.out.println(n);
}
public static void main(String args[]) {
Trials obj = new Trials();
obj.method();
}
}// end of class”
2. Global Variables In Java
What Is Global Variable?
- Variable is a container which holds the value
- Variable is name of memory location
- Variable always declare with data type.
- Variable which is present outside the method is called global variable.
- Global variable also known as instance variable.
Why We Use Global Variable?
- To store the value, we use variable.
- To maintain the scope of value at class level, we use global variable.
When We Use Global Variable?
- When we want to store the value at class level, we use local variable.
- When we want to give scope of value outside the method, we use global variable.
How We Use Global Variable?
- Global variable always declare outside the method but inside the class.
- Syntax of variable : data_type variable_name = value;
Example of Global Variable:
public class Trials {
int n = 90; // global variable
void method() {
System.out.println(n);
}
public static void main(String args[]) {
Trials obj = new Trials();
obj.method();
}
}// end of class