A variable is a basic unit of storage in a Java Program. Variables represent memory location in which value can be stored. Before using any variable, you have to declare it. After it is declared, you can then assign values to it.
int a;
byte b;
boolean male;
short age;
You can also declare and assign a value to a variable at the same time.
int a = 3;
byte b = 23;
short age = 20;
In this we declare and assign a value to a variable at the same time.
We can also declare multiple variables of one type in one expression such as in the following example:
int age, enrollnum, name, numChildren;
In java variables are define into three ways:
Instance variables are used to define the attributes of a particular object.
It is not possible to declared instance variable as static.
Class Variables are similar to instance variables, except their values apply to all the instances of a class (and to the class itself) rather than having different values for each object.
Local variables are declared and used inside methods, for example, for index counters in loops, temporary variables or to hold values that you need only inside the method definition itself.
A local variable cannot be defined as "static"
class Simple{
public static void main(String args[]){
int x = 22;
int y = 62;
int z = x+y;
System.out.println(z);
}
}
Output:
84
class Simple{
public static void main(String args[]){
int x = 2;
int y = 6;
int z = x*y;
System.out.println(z);
}
}
Output:
12