Data Types:
There are two data types available in Java:
- Primitive Data Types
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a keyword.
byte,short,int,long,char,double,float,boolean
- Reference/Object Data Types
- Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy etc.
- Class objects, and various type of array variables come under reference data type.
- Default value of any reference variable is null.
- A reference variable can be used to refer to any object of the declared type or any compatible type.
You must declare all variables before they can be used.
The basic form of a variable declaration is shown here:
data type variable [ = value][, variable [= value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
There are three kinds of variables in Java:
- Local variables
- Instance variables
- Class/static variables
Local Variable
A variable that is declared inside the method is called local variable. |
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not declared as static. |
Static variable
A variable that is declared as static is called static variable. It cannot be local. |