Java Variables

Variable:

The variable is the name of a reserved memory location. It means some part of memory is reserved when we declare a variable.

e.g. int num1 = 15;

num1 is a variable here.

Types of Variable:

Local variable

A variable that is declared within the method, constructor, or block is known as a local variable.

No Access modifier is used for local variables. The scope of the local variable is limited to that method, constructor, or block only in which it is declared.

Instance variable

A variable that is declared within the class but outside of the method, constructor, or block is known as an instance variable (Non-static). They are associated with objects. Access modifiers can be used with instance variables. Inside the class, you can access instance variables directly by variable name without any object reference.

Static variable

A variable that is declared within the class with a static keyword but outside of the method, constructor, or block is known as a Static/class variable. They are associated with class. Static variables are accessed by ClassName.VariableName.

Java Variables Examples

package com.w3schools;

public class VariableTest {
    //Static variable
    static int num1=100;
    
    //Instance Variable
    int num2 = 200;
    
    void displayLocal()  
    {   
    	//Local variable
        int num3=300; 
        System.out.println("Local Variable: " + num3);
    }  
    
    public static void main(String[] args) {
        VariableTest variableTest = new VariableTest();
        
        //Local Variable will be printed from displayLocal() Method
        variableTest.displayLocal();
        
        //Access and Print Instance Variable by Object.VariableName
        System.out.println("Instance Variable: " + variableTest.num2);
        
        //Access and Print Static Variable by ClassName.VariableName
        System.out.println("Static Variable: " + VariableTest.num1);		

    }

}

Output

Local Variable: 300
Instance Variable: 200
Static Variable: 100