How many types of variables are there in Java?

A variables can be defined as to reserve memory space to store the values. These can be initialized at the time of declaration or later on depending on the type of variable. There are basically three type of variable available in java: local variables, instance variables and static variables.


Table of Contents

Types Of Variables in JAVA:

There are 3 types of variables in JAVA:

1. Local Variable
2. Instance variable
3. Class Variable/Static variable

Local variable:

  • These are also called as stack variable. Because they exist in stack memory
  • It is mandatory to initialize the local variable. Otherwise you will get run time error from compiler
  • These can be defined inside method, constructor or also inside block. The scope or life time of local variable destroyed with end of method completion.

Instance variable:

  • Instance variable are also known as member variable or field
  • These are associated with the object creation. As the object get created instance variable also get created
  • These live on heap memory. In case, if you don’t initialize instance variable with initial value these get default value at run time implicitly.

Class Variable/Static Variable:

  • These are loaded and initialized when class is loaded in JVM
  • There exists only one copy of class variable
  • They live on heap memory. If these variables are not initialized to some default value is assigned to them implicitly.

Examples Of Variables In JAVA:

Given three type of variable are explained in the program written here. Simply to check the output from a java program you need JDK (java development kit) and editor to write the program (e.g. notepad, eclipse, netbeans etc).

Here, in this concept the Eclipse editor is used to check the output for different type of variables.

Open Eclipse editor, create new project and create class name TypeOfVariable and program file will be automatically save in TypeOfVariable.java. This is because when you write code in java. It is mandatory to save file name as name of class having main function defined with .java extension.

public class TypeOfVariable{
	public static int staticvariable;
	int instancevariable;
	public void printValue(){
		int localvariable;
		System.out.println("the value of staticvariable \t"+staticvariable);
		System.out.println("the value of instancevariable\t"+instancevariable);
		System.out.println("the value of localvariable \t"+localvariable);
	}
	public static void main(String args[]){
		TypeOfVariable object=new TypeOfVariable();
		object.printValue();
	}
}

Here, in this program three variables named as staticvariable, instancevariable and localvariable are declared as respective for static variable, instance variable and local variable.

Important Note: If you run this program without initializing localvariable you will get an compile time error. This is simple because local variable must be initialized otherwise it will show an error like “The local variable localvariable may not have been initialized”.

Correct Program Code With Initialization of Local Variable:

Simply just assign the initial value to localvariable in the same program. The change in output will reflect automatically the importance of this change. Because only local variable required to initialize with some value.

Class/Static and instance variable implicitly assign the null /0/ false value to these particular variable.

In this Tutorial, we will Explore Java Variables, Types of Variables, Java Instanceof,  Scope & Lifetime of a Variable with the help of Examples:

We will also see a few frequently asked questions that would help you in understanding the topic better.

After going through this tutorial, you will be gaining insights into the Java variables, local and global variables, the instance variable, and other sub-topics related to Java variables.

=> Check ALL Java Tutorials Here.

How many types of variables are there in Java?

What You Will Learn:

Java Variables

As we know a Java variable is a storage unit in a Java program. A Java variable is a combination of ‘type’, ‘identifier’, ‘identifier value’. Declaring a variable requires ‘type’ and ‘identifier’.

However, when you specify the value of a variable after declaring the variable, this process is called the initialization of a variable.

Syntax:

type identifier [ = value][, identifier [= value] ...]

Examples

// declaring three variables a, b and c.
int a, b, c;
// initializing variables a and c.
int a = 10, b, c = 5;

Dynamic Initialization

Here, we will see the dynamic initialization of a variable. We will be calculating the discriminant of the quadratic equation of mathematics.

The mathematical formula for calculating discriminant is b²-4ac for the equation ax² +bx +c

All we have to do is to calculate the discriminant using dynamic initialization.

public class DynamicInitialization {

	public static void main(String[] args) {
		int a = 1, b = 2, c = 3;
		
		/*
		 * d is dynamically initialized which will be the
		 * discriminant of the quadratic equation
		 */
		
		double d = b*b -4*a*c;
		
		System.out.println("Discriminant is: " + d);

	}
}

Output

How many types of variables are there in Java?

Scope And Lifetime Of Variables

In this section, we will discuss the scope and lifetime of a Java variable. Here, we will take a variable ‘a’ that will be known to the entire program and then demonstrate the value of that variable which will be specific to a block inside the program.

Again we will create another variable ‘b’ inside a block that depends on the value of ‘a’. As soon as the scope ends, the scope of variable ‘b’ also ends whereas ‘a’ is still known to the program.

class VariableScope {
	
	public static void main(String args[]) {
	
		// a is known to entire program
		int a; 
		a = 15;
		
		// starting new scope known only to this block
		if (a == 15) {
			int b = 20;
			
			// a and b both known here.
			System.out.println("a and b: " + a + " " + b);
			a = b / 2;
		}
		
		/* b is unknown here which means
		 * if we print b, it will throw an error
		 * whereas a is still known
		 */
		
		System.out.println("a is " + a);
	
	}
}

Output

How many types of variables are there in Java?

Java Variable Types

In this section, we will learn about the various types of Java variables mentioned below.

  • Local variable
  • Instance variable
  • Static or Class variable

Local Variables

These variables are declared inside the body of a method. These can be used within the same method where it is being initialized.

Some of the properties of a Local Variable include:

  1. Local variables are declared inside a method, constructor, or block.
  2. No access modifiers for local variables.
  3. These can be used only within the same block, method, or constructor where it is initialized.
  4. No default value after you have declared your local variable. You need to initialize your declared local variable.
  5. It can’t be defined by a static keyword.

Given below is the program in which we have used local variables initialized within a method of a class. As “height” is a local variable initialized with the calculate() method, the scope of this variable will be confined within the method.

public class local {
	
	public void calculate() {
		
		// initialized a local variable "height"
		int height = 0;
		
		// incrementing the value of height
		height = height + 170;
		System.out.println("height is: " + height + " cm");
	}

	public static void main(String args[]) {
		
		// a is a reference used to call calculate() method
		local a = new local();
		a.calculate();
	}
}

Output

How many types of variables are there in Java?

Instance Variables

Instance variables are those variables that are declared inside a class. Unlike Local variables, these variables cannot be declared within a block, method, or constructor.

Enlisted below are the properties of the Instance variable:

  1. They are declared within a class but outside a block, method or constructor.
  2. It cannot be defined by a static keyword.
  3. Unlike Local variables, these variables have a default value.
  4. The integer type has a default value ‘0’ and the boolean type has the default value ‘false’.
  5. Unlike Local variables, we have access modifiers for Instance variables.

Given below is the program where we have demonstrated the instance variable. We have declared variables outside the main method and then assigned the values to them by using objects keeping one variable the “number” unassigned.

Finally, we have printed the values of these Instance variables and the unassigned variable “number” has printed ‘0’ by default.

public class instance {
	
	// Declaring instance variables
		public int rollNum; 
		public String name; 
		public int totalMarks;
		public int number;
    
	public static void main(String[] args) {
		
		// created object
		instance in = new instance();
		in.rollNum = 95;
		in.name = "Saket";
		in.totalMarks = 480;
		
		// printing the created objects
		System.out.println(in.rollNum);
		System.out.println(in.name);
		System.out.println(in.totalMarks);
		
		/*
		 * we did not assign the value to number so it 
		 * will print '0' by default
		 */
		System.out.println(in.number);

	}

}

Output

How many types of variables are there in Java?

Static Or Class Variable

Unlike the Local and Instance variable (where we can not use static), we have another variable type which is declared as static and is known as “Static or Class variable”.

Given below are some of the properties of the Static or Class variable:

  1. These variables cannot be local.
  2. Static variables are shared among all the instances of a class.
  3. The default values of Static/Class variables are the same as the Instance variables.
  4. Static variables can be used within a program by calling the className.variableName
  5. The memory allocated to store Static variables is Static memory.

In the below program, we are calculating the circumference of a circle by using a private variable radius and a constant pi. Both these variables are declared as static.

public class StaticVariable {
	
	// radius is declared as private static
	private static int radius;
	
	// pi is a constant of type double declared as static
	private static final double pi = 3.14;

	public static void main(String[] args) {
		
		// assigning value of radius
		radius = 3;
		
		// calculating and printing circumference
		System.out.println("Circumference of a circle is: " + 2*pi*radius);

	}

}

Output

How many types of variables are there in Java?

Java instanceof

The Java instanceof is an operator that is used to tell whether the created object is an instance of the type or not. Type can be a Class or an interface.

The return type is Boolean i.e. either “true” or “false”.

For Example, In the below program, we have created a reference variable a1 of type A and tried to find whether a1 is an instance of A or not. As a1 is an instance of A, it returned “true”.

class A {
	
	public static void main(String args[]) {
		
		A a1 = new A();
		System.out.println(a1 instanceof A);
		
	}
}

Output

How many types of variables are there in Java?

Frequently Asked Questions

Q #1) What are Java Global Variables?

Answer: Global variables are those variables that are accessed by the entire program and it is declared at the beginning of the program.

Global variables do not belong to Java as Java is a pure Object Oriented programming language and everything belongs to the Java Class. Just to protect data and members (variables) of the Class, Java does not support Global variables.

However, we have Static variables that are globally declared and is accessible by all method, subclass of a program.

Q #2) How to clear the value of a variable in Java?

Answer: It can be done using an inbuilt method of Java that is java.DoubleAdder.reset().

The syntax of this method is

Public void reset();

This method belongs to the package “java.util.concurrent.atomic.DoubleAdder” so you need to import this package before you proceed.

In the below program, we have added a few elements into DoubleAdder and then tried resetting it and finally printed the value after the reset operation.

import java.util.concurrent.atomic.DoubleAdder;

public class clearValue {

	public static void main(String[] args) {
		DoubleAdder a = new DoubleAdder(); 
		  
        // adding elements into DoubleAdder 
        a.add(99); 
        a.add(83); 
        a.add(75);
        a.add(105);
        
        //Printing the value of 'a' 
        System.out.println("Value after adding elements: " +a);
        
        // resetting the value of a 
        a.reset(); 
  
        // Printing the value of 'a' after reset 
        System.out.println("Value after resetting: " + a); 
    } 

}

Output

How many types of variables are there in Java?

#3) How to check the following Variable Type in Java?

String a = “test”;

Answer: If the variable is of type String then you can use referenceVariable.getClass().getName().

// declaring three variables a, b and c.
int a, b, c;
// initializing variables a and c.
int a = 10, b, c = 5;
0

Output

How many types of variables are there in Java?

#4) How to update a variable in Java?

Answer: Given below is a simple program where we have updated a variable in Java.

// declaring three variables a, b and c.
int a, b, c;
// initializing variables a and c.
int a = 10, b, c = 5;
1

Output

How many types of variables are there in Java?

Conclusion

In this tutorial, we have discussed Java Variables and provided an insight into the Dynamic Initialization, scope, and lifetime of a variable along with explaining the different Java variable types and Java instanceof operator.

Each major concept was explained with proper programming examples to help you understand the topic better.

Suggested reading =>> VBA Variables and Option Explicit

Towards the end, we also saw a couple of frequently asked questions that will let you know about the different questions which could be asked during Java interviews.

What are the 4 types of variables in Java?

In Java, there are different types of variables, for example:.
String - stores text, such as "Hello". ... .
int - stores integers (whole numbers), without decimals, such as 123 or -123..
float - stores floating point numbers, with decimals, such as 19.99 or -19.99..
char - stores single characters, such as 'a' or 'B'..

What are the 3 variable of class of Java?

There are three different types of variables a class can have in Java are local variables, instance variables, and class/static variables.

How many types of variables are there in class?

Variables may be classified into two main categories: categorical and numeric. Each category is then classified in two subcategories: nominal or ordinal for categorical variables, discrete or continuous for numeric variables.