Variable Types in Java With Samples

In the previous lecture, we discussed various data types and the declaration format of variables. In this lecture, we are going to see the types of variables on the basis of its availability and effectiveness.

There are three types of variable:

  • Class/Static Variable
  • Instance Variable
  • Local Variable

Let us take a real-life scenario to relate to each of them:

You visited an Amusement Park with your family with a bottle of water for refreshment. There is an Entry ticket. You purchased the ticket and entered. Inside the park, there are some exclusives rides, which have their specific ticket.

Time to dig deep into the given scenario.

The bottle of water in your hand is a single entity. Every member of your family is going to use the same bottle. That bottle is a static variable.

The entry ticket is to be purchased for every single member of your family. Every member of the family will have a different ticket( ticket number will be distinct). This entry ticket is an instance variable.

There are some exclusive rides that have their own tickets. The ticket for the Giant wheel will not be applicable to the Roller coaster and vice versa. This specific ride ticket is a local variable.

Class/Static Variable

A variable when declared inside the class with the keyword static, it is a static variable. The keyword indicates this specific variable will have one, and only one memory allocation whenever the class is loaded in memory and is destroyed when the program stops/terminate. The format of the declaration of a static variable is as follows:

static <dataType> <meaningfulVariableName>

Every instance of the class i.e object is going to share and refer to the same copy of the variable. These variables can be accessed by the instance as its own variable. They can be declared anywhere inside the class and are generally used for constants that never change from its initial value. Since they are a member of the class and not objects, we refer to the static variable using the following format:                                                                                 

ClassName.staticVariableName

The default value of these variables is the same as given in the previous lecture. For integral data it is 0, for decimal data, it is 0.0f/0.0d, and for boolean it is false, and for reference variables it is null.  

Example:

public class StaticTest
{
   static int sharedVariable=7; //This variable is static and holds the value 7

   public static void main(String args[])
   {
     /*
     We will see that every instance will refer to the same variable
     */
     StaticTest object1 = new StaticTest(); //We created an object of name object1
     StaticTest object2 = new StaticTest(); //We created another object of name object1
     System.out.println("Static Variable accessed by class Name:"+StaticTest.sharedVariable);  // This will print 7 
     System.out.println("Static Variable accessed by object Object1:"+object1.sharedVariable); // This will also print 7
     System.out.println("Static Variable accessed by object Object2:"+object2.sharedVariable);  // This will also print 7

     StaticTest.sharedVariable = StaticTest.sharedVariable + 1; // This will increment the value of static variable by 1. This will impact the results
    
     System.out.println("\n\nThe sharedVariable has been incremented by 1\n\n");
    
     System.out.println("Static Variable accessed by class Name:"+StaticTest.sharedVariable);  // This will print 8 
     System.out.println("Static Variable accessed by object Object1:"+object1.sharedVariable); // This will also print 8
     System.out.println("Static Variable accessed by object Object2:"+object2.sharedVariable);    // This will also print 8
   }
}

Output:

Static Variable accessed by class Name:7
Static Variable accessed by object Object1:7
Static Variable accessed by object Object2:7


The sharedVariable has been incremented by 1


Static Variable accessed by class Name:8
Static Variable accessed by object Object1:8
Static Variable accessed by object Object2:8

Instance Variable

A variable that is defined inside the class, without the static keyword. It is to be ensured that the variable is declared directly inside the class, and not inside any member i.e method/constructor of the class.

The variables of these types indicate that every instance i.e object of the class will have its individual memory space of that variable, unlike sharing as it was in the case of the class variable. The memory for these is allocated upon instance creation and is available until the instance is not destroyed.

Since they are a member of objects and not class, we refer to the instance variable using the following format:

objectReferenceName.variableName

The default value of these variables is the same as given in the previous lecture. For integral values it is 0, for decimal values, it is 0.0f/0.0d, for boolean it is false, and for reference variables it is null.  

Example:

public class InstanceTest
{
   int instanceVariable; //This variable is not static and each instance will have a separate memory allocation for it.

   public static void main(String args[])
   {
     /*
     We will see that every instance will refer to its own variable
     */
     InstanceTest object1 = new InstanceTest(); //We created an object of name object1
     InstanceTest object2 = new InstanceTest(); //We created another object of name object1

     object1.instanceVariable = 91;  // This sets value 91 to instanceVariable of object1
     
      object2.instanceVariable = 97;  // This sets value 91 to instanceVariable of object1
     System.out.println("Instance Variable accessed by object Object1:"+object1.instanceVariable); // This will also print 91
     System.out.println("Instance Variable accessed by object Object2:"+object2.instanceVariable);  // This will also print 97

     object1.instanceVariable = 95; // This updates the value of instanceVariable of object1 to 95
    
    System.out.println("\n\nThe change of variable value in object1 won't affect object2 \n\n");
    

     System.out.println("Instance Variable accessed by object Object1:"+object1.instanceVariable); // This will also print 95
     System.out.println("Instance Variable accessed by object Object2:"+object2.instanceVariable);    // This will also print 97
   }
}

Output:

Instance Variable accessed by object Object1:91
Instance Variable accessed by object Object2:97


The change of variable value in object1 won't affect object2 


Instance Variable accessed by object Object1:95
Instance Variable accessed by object Object2:97

Local Variable

 The variables which are declared inside a block like methods and constructors are known as Local Variable. These variables are also declared without the static keyword. The variables are visible and applicable only inside the block in which it is declared. It is unknown to the rest of the program.

These variables are implemented at stack level and the memory is allocated when that very block is in execution and gets destroyed once it exits the block.

Unlike instance and class variables, local variables do not have any default value. So it will result in an error if the local variable is used before any value is assigned to it.

Example 1:

public class InstanceTest
{
   public static void main(String args[])
   {
     int localVariable=15; // This is a local variable and is found only inside the main method
     System.out.println("The value of localVariable inside main method is "+localVariable);
   }
}

Output:

The value of localVariable inside main method is 15

Example 2:

The local variable has no existence outside the method in which it is declared

public class LocalTest
{
   public static void main(String args[])
   {
     int localVariable=15; // This is a local variable and is found only inside the main method
     System.out.println("The value of localVariable inside main method is "+localVariable);
   }
    System.out.println("The value of localVariable outside main method is "+localVariable); // This line will give error as localVariable has no existence outside the main
}

Output:

LocalTest.java:8: error: <identifier> expected
    System.out.println("The value of localVariable outside main method is "+localVariable); // This line will give error as localVariable has no existence outside the main
                      ^
LocalTest.java:8: error: illegal start of type
    System.out.println("The value of localVariable outside main method is "+localVariable); // This line will give error as localVariable has no existence outside the main
                       ^
LocalTest.java:8: error: ')' expected
    System.out.println("The value of localVariable outside main method is "+localVariable); // This line will give error as localVariable has no existence outside the main
                                                                           ^
LocalTest.java:8: error: ';' expected
    System.out.println("The value of localVariable outside main method is "+localVariable); // This line will give error as localVariable has no existence outside the main
                                                                            ^
LocalTest.java:8: error: illegal start of type
    System.out.println("The value of localVariable outside main method is "+localVariable); // This line will give error as localVariable has no existence outside the main
                                                                                         ^
LocalTest.java:8: error: <identifier> expected
    System.out.println("The value of localVariable outside main method is "+localVariable); // This line will give error as localVariable has no existence outside the main
                                                                                          ^
LocalTest.java:8: error: ';' expected
    System.out.println("The value of localVariable outside main method is "+localVariable); // This line will give error as localVariable has no existence outside the main
                                                                                           ^
LocalTest.java:9: error: reached end of file while parsing
}
 ^
8 errors

Example 3:

The local variable does not have a default value and expects value assignment prior to using it.

public class LocalTest
{
   public static void main(String args[])
   {
     int localVariable; // This is a local variable and is found only inside the main method
     System.out.println("The value of localVariable inside main method is "+localVariable);
   }
}

Output:

LocalTest.java:6: error: variable localVariable might not have been initialized
     System.out.println("The value of localVariable inside main method is "+localVariable);
                                                                            ^
1 error

This was a brief illustration of variable types, we will look into each data type in detail in our upcoming lectures.