Variables in Java

Code Computer Skills Java

Overview

In this article, I will discuss in details how to declare variables in Java and use them. This article will cover

  1. Types of variables in Java
  2. The scope of visibility of the variables

Before jumping off to types of variables, first, let us see how a variable works.

Variables:

During execution, programs perform various operations on data values. These data values are stored in memory locations.

  • We can call variables as names given to the memory locations which contain the data value.
  • Variables are containers that hold the data value.
  • These containers (variables) can hold different values at different times.
  • The memory location always remains the same under that variable.

Variables in Java

Declaring Variables in Java

In Java, we declare variables as Datatype VariableName;

For example:

int number;

char letter;

String name;

Initializing Variables in Java

Now, these statements will only give names to specific locations in the memory. The memory locations now do not contain any values.

  • In order to assign values to the variables, we use the assignment operator “=”.
  • We can assign values to the above variables as VariableName = value;

For example:

number = 3;

letter = 'a';

name = "JavaProgram";

We can also assign values to the variables at the time of declaration as follows.

int number = 3;

char letter = 'a';

String name = "JavaProgram";

Given below is a program that explains different instances of variable declaration, variable definition and displaying variables.

package test;

public class JavaVariables {
  
  public static void main(String[] args) {
    
    // declaring variables 
    int result;
    int number1;
    String name;
    
    // assigning a value to the variable  
    number1 = 9;
    name = "JavaProgram";
    
    // defining variables
    int number2 = 3;
    char letter = 'a';		
    String sentence = "This program will teach you about Java variables";
    Boolean flag = true;
        
    // small operations using Java variables
    result = number1 + number2; //assigns the sum of number1 and number2 to result
    System.out.println("The result of the addition = " + result);
    
    System.out.println("The character is " + letter);
    System.out.println("The name is " + name);
    System.out.println("The sentence is " + sentence);
    System.out.println("The boolean value is " +  flag);		
  }
}

The output of this program :

Java Variables Result

Types of Variables in Java:

Based on the scope of variables, there are 3 types of variables in Java. They are :

Local Variable:

  • We declare a local variable within a block of the method, a block of the loop, a block of the constructor, block of if-else or any general block.
  • It can only be used inside the same method in which it is declared.
  • It is not a member of Class or object, so we cannot call it by class name or object name.
  • Other methods or variables present outside of that block of a variable cannot use it.
  • The local variables are created when that particular method is entered or called by any other method.
  • When control exits from that method or block, the local variables are also destroyed and are of no use.
  • We cannot specify any access specifier for a local variable.

Refer to the below program for a clear understanding of local variables.

package test;

public class Shape {

  int area() {
    
    // local variables inside area() method
    int length = 10; 
    int breadth = 20;
    int area = length*breadth;
    
    System.out.println("length is "+ length);
    System.out.println("breadth is "+ breadth);
    
    return area;		
  }

  public static void main(String[] args) {
    
    Shape obj=new Shape();
    int result=obj.area();  // the method area() is called to display the result.
    System.out.println( "the result of area " + result);
  }
}

The output of the above program:

Local variable Output

But if you try to call a local variable directly outside that method as below, it would give an error.

package test;

public class Shape {

  int area() {
    
    // local variables inside area() method
    int length = 10; 
    int breadth = 20;
    int area = length*breadth;	
    return area;		
  }
  
  public static void main(String[] args) {
    
    System.out.println( "the result of area " + result);
  }
}

The error message :


Instance Variables (Non-Static):

  • We declare the instance variables inside a class but outside of any method/block.
  • They have a broader scope of accessibility within the program.
  • These variables should have some access specifier which decides its scope.
  • This is known as object level variable. The memory allocation for this variable only happens at the time of object creation.
  • We can access instance variables only by calling with the help of objects of a class like this: ObjectName.variableName;
  • Each object of the class makes its own copy of the instance variable. This means, there are multiple copies of the same instance variable.
  • An instance variable can hold different values for different objects.

Let us look at an example:

package test;

public class ShapeParameters{
  
  // instance variables of class ShapeParameters
  // These will be used inside another class for computing area of different shapes.
  public int length; 
  public int breadth;
}
public class Area {
  
  public int area; // instance variable of class Area
  
  public static void main(String[] args) {
    
    Area obj_sq = new Area(); // object of class Area, it will be used to call the instance variable area
    
    // For shape 1 : sqaure
    ShapeParameters square = new ShapeParameters(); // object of class ShapeParameters
    square.length = 10; // Calling the instance variable length, using object
    
    obj_sq.area = square.length * square.length; // operation on instance variables of different classes
    System.out.println("The area of square is " + obj_sq.area);
    
    // For shape 2 : rectangle
    Area obj_rect = new Area();
    
    ShapeParameters rect = new ShapeParameters(); // object of class ShapeParameters
    rect.length = 10; // Calling the instance variable length
    rect.breadth = 20; // Calling the instance variable breadth
    
    obj_rect.area = rect.length * rect.breadth; // operation on instance variables of different classes
    System.out.println("The area of rectangle is " + obj_rect.area);
  }
}

You can see the output of this program as follows:

Here you can see that it has created 2 different copies of length and breadth for the 2 objects square and rect. It computes the respective area values separately for the 2 objects.

Now, this is what happens when you declare variables as instance variables. Every object retains its own copy of the variable.

Class Variables (Static Variables):

  • We declare a Static variable with the keyword static.
  • Like instance variables, we declare them inside a class but outside any method or block.
  • Only a single copy of the variable is present in the memory for the whole program irrespective of how many objects of that class exist.
  • Mostly we use static variables to declare constants which have a fixed value throughout the program.
  • When the program execution starts and Class loads into the memory, the static variables are created.
  • The variables are destroyed automatically when the program ends.
  • The scope of these variables depends upon access specifiers.
  • We can access static variables by calling with the class name as follows: ClassName.variableName;.
  • No object of the class required in order to access them. However, we can also call them using object names like instance variables.
  • Mostly we declare static variables as public because it can be used by all other methods inside the class.

Final Variable:

  • We declare a final variable with the final keyword.
  • Java does not support any Const keyword to declare a constant variable. If we declare the variable with final keyword, then it is a constant in Java.
  • Final variable may or may not be static but its better for a programmer to declare final variable as static.

The program below shows the declaration and use of static variable and final variable.

package test;

public class StudentDetails {

  // static variables 
  public static int marks;
  
  /* this static variable acts as a constant. 
   * The value remains same throughout the program. 
   * A new value cannot be assigned to NAME.
   */
  
  public final static String NAME ="Ipsita"
}

public class StudentDisplay {
  
  public static void main(String[] args) {
    
    System.out.println("The name of the student = "+StudentDetails.NAME);	
    
    // before assigning any values to the static variable
    System.out.println("The default value of marks = "+StudentDetails.marks);
    
    // for subject 1
    // assigning values to the static variable
    StudentDetails.marks= 80;
    System.out.println("The value of marks for subject 1 = "+StudentDetails.marks);	
    
    /* static variables can also be accessed through objects of the class,
     * but only 1 copy of static variable is present per class.
     * The value is modified after successive assignments and always displays the latest value
     * for subject 2
     */
    
    StudentDetails subject2 = new StudentDetails();
    subject2.marks = 90;
    System.out.println("The value of marks for subject 2 = "+subject2.marks);	
    
    // the value of marks has been modified and will always display the latest value
    StudentDetails subject3= new StudentDetails();
    subject3.marks = 60;
    System.out.println("The value of marks for subject 3 = "+subject3.marks);	
    
    System.out.println("The value held by the variable marks = "+StudentDetails.marks);	
    
    // displays the latest value 60 irrespective of the object used to call it
    
    System.out.println("The value of marks for subject 2 = "+subject2.marks);
    System.out.println("The value of marks for subject 1 = "+StudentDetails.marks);
  }
}

The output of the above program :

static variable

In the above program, you can see how the single copy of static variable marks holds different values at different points of time. As the program has only a single copy of the static variable, so its values are modified.

But this is not the case in instance variables. Modifications done by one object does not affect the copies held by other objects.

In the next article, I will explain various data types supported by Java.