Java variables and data types


A variable provides us with named storage that our programs can manipulate. You must declare all variables before they can be used. Following is the basic form of a variable declaration -

data type variable [ = value][, variable [ = value] ...] ;

data type is one of Java's data types and the variable is the name of the variable. To declare more than the 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 - Local variables are declared in methods, constructors, or blocks.

Instance variables - Instance variables are declared in a class, but outside a method, constructor or any block.

Class/Static variables - Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.

Data Type

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.

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.

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.