In any language variables are used to store values.
We have to understand what is variable?
Why we use variables?
How to create variable or how to define variables?
Generally every program deals with the manipulation of data. Then there must be a question where data is stored? The data is stored in memory. To read or modify data we have to access the memory location then we have to modify. It is tedious job to get the memory location always when we refer the memory. It is better to give a name to the memory location to remember it easily. It is same like every student can be identified with roll no and name. But calling the student with his name is easy then with roll no. So the named memory location is called variable. It means if we want to access the values or modify the value in a memory location we use variable instead of memory address.
We have to crate variable by specifying the data type before the name of the variable. The syntax is as follows
Datatype variablename;
Here we have to specify the valid data types of java which is int, float, double, char, byte, short, long, boolean
Variable name is name or identifier which contains combination of characters and digits.
Local variables are the variables which are declared in functions or methods or block. Local variables are accessed within the function or method or block. Their life is within the block only hence those are called as local variables. Local variables are illustrated in the following snippet.
void add(){
int a=20;
int b=30;
int c = a + b;
}
In this snippet variables a,b,c are treated as local variables.