Variables in Java

Variables are basically the containers that store the value inside them. Every time we declare a variable, we need to specify the type that will define the kind of value which will be stored in the variable.

in short Variables are used to store values in computer’s memory.

Declaring Variables in Java

To declare a variable, you will need to specify its type, then type name for the variable and end the line with a semicolon (;). the type of the variable should be compatible with the data inside it.

Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).

how to declare a variable:

int x;

How to Initialize Variables in Java

Java allows you to declare and initialize a variable in a single statment. as shown below.

type name = expression;

datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

In effect, the initializer lets you combine a declaration and an assignment statement into one concise statement. Here are some examples:

int x = 0;

String firstName = "Mohammed";

double score = 15.4;

In each case, the variable is both declared and initialized in a single statement.

When you declare more than one variable in a single statement, each variable can have its own initializer. The following code declares variables named x and y, and initializes x to 5 and y to 10:

int x = 5, y = 10;

Types of variables

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren’t even aware that the variable exists.

A local variable cannot be defined with “static” keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared asĀ static.

It is called instance variable because its value is instance specific and is not shared among instances.

3) Static variable

A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.

class studentProgress{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}//end of method()
}//end of class