Variable in Java

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.

How to Create / Declare a variable

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.

Rules of to be followed while declaration of Variable

  • Key words should not be used as variables
  • Ex: int char; char is a key word hence this not a valid variable declaration
    Ex: float void: void is a key word hence this not a valid variable declaration
  • Special characters are not allowed in variable names
  • Ex: int x@3; x@3 is not a valid variable as it contains special character @
    Ex: int r#34; r#34 is not a valid variable as it contains special character #
  • Variable names should not contains spaces
  • Ex: float average of marks; average of marks is not valid variable as it contains spaces.
  • Digit is should not be a starting character of a variable
  • Ex: int 1number; 1number is not a valid variable as it is started with digit 1
  • Variable may contains of combination of characters and digits
  • Ex: int num1; num1 is a valid variable

Types of Variables


There are 4 different types of variables present in java. Those are listed below
1) Local Variables
2) Instance variables or not static variables
3) Class variables or static variables
4) Parameters

Local Variables

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.