Loading

What is a variable in Java?

It is defined as a container that can hold any type of data. As the name implies, we can alter the value stored in the variable.


Key Points:- 

  •  It is a name given to the location in the memory in which we store data.

Declaration of Variable:- To declare a variable first write datatype ( type of data i.e. int,
float, char, etc.) then space (“ ”), and then write the name of the variable (Identifier).
Syntax: 

 datatype variable_name;

Example:

 int a;

Initialization of Variable: - To initialize a variable we have to assign a value to the variable.
Syntax: 

variable_name = value;

Example:

var = 12;

Example of Declaration and Initialization of the variable at once:

int a=20;
String s="Hello";

Types of Variables

Variables are of three types: Instance, Local, Static
1. Instance Variable: - Variable declared within a class but outside of any methods.

Example:

package quipohouse;
public class InstanceVariable {
	int var = 10;    // Declaration and initialization of instance variable

	public static void main(String[] args) {
		InstanceVariable c = new InstanceVariable();
		System.out.println(c.var);
	}
}

Output:

10

2. Local Variable: -Variable declared inside any method or block. The scope of the local variable is inside that method or block.
Example:

package quipohouse;
public class LocalVariable {

	public static void main(String[] args) {
		int var2 = 12; // Declaration and initialization of Local Variable
		System.out.println(var2);
	}
}

Output:

12

3. Static Variable:

  • A variable marked with a static keyword is known as a static variable. e.g. - static int var;
  • The static variable is declared inside a class but outside any method. 
  •  The scope of the static variable is inside the class.
  • We can have only one copy of the static variable of any class, independent of the number of objects we create.
  • As a result, if we make any changes to a static variable in one object then it
    will reflect back on another variable.
  • We can directly access static variables by using the class name.
  • We can also access static variables without using the class name within a class inside the static block. In this scenario compiler automatically append the class name before it.

Example:

package quipohouse;
public class StaticVariable {
	static int var; // Declaration of static variable

	public static void main(String[] args) {
		System.out.println(StaticVariable.var); // 20
		System.out.println(var); // 20
	}
}

Output:

0
0