Variable Types in Java

What is a Variable?

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java.

In Java, variables must be declared before they can be used. Java allows variables to be initialized dynamically, using any expression valid at the time, the variable is declared.

Declaration

int x =  15 ;
int y = Math.sqrt(a * a + b * b); // Here variable y will get the value
dynamically      
//depending to the values of a, b.

Scope

The opening and closing of the curly braces describe scope. A scope determines what objects are visible to other parts of our program. It also determines the lifetime of those objects.

Variables are created when their scope is entered and destroyed when their scope is left.

It means variables which are declared within a method will not hold their values outside it. Also, a variable declared within a block will lose its value when the block is left.

Thus, the life-cycle of a variable is within its scope.

Here are the available scopes of variables:

  • Local variables (also known as method-local variables)
  • Method parameters (also known as method arguments)
  • Instance variables (also known as attributes, fields, and non-static variables)
  • Class variables (also known as static variables)

Local variables:- Local variables are defined within a method, constructor or block. We can not apply access modifier to local variables. Local variables are visible only within the scope of declared method, block, or constructor. The local variable should be assigned before there first use. The scope of a local variable depends on the location of its declaration within a method. The scope of local variables defined within a loop, if – else, switch statement or within a code block (marked with {} ) is limited to these curly braces. Local variables defined outside any of these constructs are accessible across the complete method.

Method parameters:- The variables that accept values in a method signature are called method parameters. They’re accessible only in the method that defines them.

Instance variables:- An instance variable is declared within a class, outside all the methods. It’s accessible to all the instance (or non-static) methods defined in a class.

Class variables:- A class variable is defined by using the static keyword. A class variable belongs to a class, not to individual objects of the class. A class variable is shared across all objects. Objects don’t have a separate copy of the class variables. We don’t even need an object to access a class variable. It can be accessed by using the name of the class in which it is defined:

Comparing the use of local variable in different scope.

  • Local variables are defined within a method and are normally used to store the intermediate results of a calculation.
  • Method parameters are used to pass values to a method. These values can be manipulated and may also be assigned to instance variables.
  • Instance variables are used to store the state of an object. These are the values that need to be accessed by multiple methods.
  • Class variables are used to store values that should be shared by all the objects of a class.

Following is an example demonstrating the scope and behavior of variable types with the help of classes: VariableTypesExample.java and Car.java

Car.java
package com.shishirkant.java;
/**
* @author shishirkant.com
*/
class Car{
    final static int noOfWheels = 4; // static variable with modifier final
    static String ownerName = "ShishirKant"; // static variable
    String carName; // non-static variable
    int topSpeed; // non-static variable
    // carName and topSpeed together define the state of an instance of this Car class
    public Car(int speed, String name){ // speed and name are parameters
        topSpeed = speed;
        carName = name;
    }
    public void horn(){
        int frontCarDistance=5; // scope of frontCarDistance varible is horn() method
        { // scope of noOfHorns is this first block
            int noOfHorns = 2; 
            System.out.println(carName + " horns "+noOfHorns+" times.");
        }
        { // scope of noOfHorns is this second block
            int noOfHorns = 3; 
            System.out.println(carName + " horns "+noOfHorns+" times.");
        }
        System.out.println("For "+carName+", frontCarDistance value is :"+frontCarDistance);
    }
}
VariableTypesExample.java
package com.shishirkant.java;
/**
* @author shishirkant.com
*/
public class VariableTypesExample {
    static int var = 10; 
    public static void main(String[] args) {
        Car carOne = new Car(120, "carOne");
        Car carTwo = new Car(185, "carTwo");
        
        System.out.println("--------------carOne's details--------");
        System.out.println(carOne.carName + "'s top speed : "+carOne.topSpeed);
        carOne.horn();
        System.out.println(carOne.carName +" has "+carOne.noOfWheels+" wheels.");
        System.out.println(carOne.carName +"'s owner is "+carOne.ownerName);
        carOne.ownerName = "ShishirKant Modified";
        System.out.println("------------------------------------\n");
        
        System.out.println("--------------carTwo's details--------");
        System.out.println(carTwo.carName + "'s top speed : "+carTwo.topSpeed);
        carTwo.horn();
        System.out.println(carTwo.carName +" has "+carTwo.noOfWheels+" wheels.");
        // ownerName is changed in the instance of carOne, the change reflects in all the instances of Car class
        System.out.println(carTwo.carName +"'s owner is "+carTwo.ownerName);
        System.out.println("------------------------------------");
    }
}
Output
 
--------------carOne's details--------
carOne's top speed : 120
carOne horns 2 times.
carOne horns 3 times.
For carOne, frontCarDistance value is :5
carOne has 4 wheels.
carOne's owner is ShishirKant
------------------------------------
 
--------------carTwo's details--------
carTwo's top speed : 185
carTwo horns 2 times.
carTwo horns 3 times.
For carTwo, frontCarDistance value is :5
carTwo has 4 wheels.
carTwo's owner is ShishirKant Modified
------------------------------------
Follow Us On