Understanding Variables in Java with Examples

  • Last updated Apr 25, 2024

In Java, a variable is a name that acts as a container for storing a data value in a program, allowing your program to store and manipulate data dynamically. Each variable in Java is of a specific data type, and these data types specify the kind of data a variable can hold. In simple terms, a variable is a name assigned to a memory to allocate space for storing a data value in a program.

Types of Variables in Java

Variables in Java are of three types:

  1. Instance variables: Instance variables are declared within a class but outside of any method and constructor. They are associated with an instance of a class and are initialized when an object of that class is created. Instance variables are declared without the static keyword, therefore they are also called non-static variables. Here's an example:
  2. public class Example {
        int instanceVar; // Declaration of an instance variable
    }
  3. Class(Static) variables: Static variables are declared with the static keyword inside a class but outside of any constructor or method. They are also known as class variables. Static variables are commonly used for declaring constants—variables with a fixed value that cannot be changed after assignment. Static variables are initialized only once, and only a single copy of such variables is created and shared at the class level, regardless of how many times they are called in a program. Here's an example:
  4. public class Example {
        static int CLASS_VAR; // Declaration of a class variable
    }
  5. Local variables: Local variables are declared within the body of a method and constructors. We can use local variables only within the method where they are declared. Other methods in the same class aren’t even aware that a variable from one method exists. The compiler never assigns a default value to an uninitialized local variable. Therefore, a local variable must always be assigned a value before it is used; otherwise, accessing an uninitialized local variable will result in a compile-time error. Here's an example:
  6. public class Example {
        public void myMethod() {
            int localVar = 10; // Declaration and initialization of a local variable
            // Code utilizing localVar
        }
    }
Variable Declaration and Initialization

Java is a statically-typed programming language, meaning that a variable must always be declared before it is used. Declaring of a variable involves stating the variable's type and name. Declare a variable by specifying its type followed by the variable name. For example:

int myVar; // Declaration of an integer variable

Initialize a variable by assigning a value to it. For example:

int myVar = 47; // Declaration and initialization of an integer variable
Accessing Instance Variables

Instance variables are associated with an instance of a class, making them accessible throughout the entire class. The instance variables are visible to all methods, constructors, and blocks in the class where they are declared.

Here's an example a Car class with instance variables:

public class Car {
    // Instance variables
    String brand;
    String model;
    int year;

    // Constructor to initialize instance variables
    public Car(String brand, String model, int year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    // Method to display information about the car
    public void displayInfo() {
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Year: " + year);
    }

    public static void main(String[] args) {
        // Creating objects of the Car class
        Car car1 = new Car("Toyota", "Camry", 2022);
        Car car2 = new Car("Honda", "Accord", 2021);

        // Accessing instance variables through objects
        System.out.println("Car 1 Information:");
        car1.displayInfo();
        System.out.println(); // Adding a blank line for better output separation

        System.out.println("Car 2 Information:");
        car2.displayInfo();
    }
}

In this example, the Car class has three instance variables: brand, model, and year. The constructor public Car(String brand, String model, int year) initializes these instance variables when a Car object is created. The displayInfo() method prints the information about the car, including its brand, model, and year. In the main method, two Car objects (car1 and car2) are created with different specifications, and their information is displayed using the displayInfo() method.

The output of the above code is as follows:

Car 1 Information:
Brand: Toyota
Model: Camry
Year: 2022

Car 2 Information:
Brand: Honda
Model: Accord
Year: 2021
Accessing Class(Static) Variables

Static variables belong to the class and not individual objects. Therefore, we do not need any object to access static variables in Java. In simple terms, class variables are shared among all instances of a class, allowing them to be accessed using the class name. Generally, public variables can be accessed from everywhere, and private variables can only be accessed from within the class where they are declared. However, it's important to note that if a static variable in a class has the private modifier, it won't be accessible from other classes.

To access static variables in another class, all we need to do is use the name of the class followed by a dot (.) and the name of the static variable. Here is an example of how we can access the static variable of one class in another class:

public class MathOperations {
    // Static variables as constants
    public static final double PI = 3.14159;
    public static final double EULER_NUMBER = 2.71828;
    public static final double GOLDEN_RATIO = 1.61803;

    // Other methods for mathematical operations can be added here
}

public class MathApp {
    public static void main(String[] args) {
        // Accessing static variables as constants from the MathOperations class
        System.out.println("Value of Pi: " + MathOperations.PI);
        System.out.println("Value of Euler's Number: " + MathOperations.EULER_NUMBER);
        System.out.println("Value of Golden Ratio: " + MathOperations.GOLDEN_RATIO);

        // Using constants in mathematical calculations
        double circleArea = MathOperations.PI * Math.pow(5, 2); // Area of a circle with radius 5
        System.out.println("Area of a Circle with Radius 5: " + circleArea);

        double exponentialResult = Math.pow(MathOperations.EULER_NUMBER, 2); // e^2
        System.out.println("e^2: " + exponentialResult);
    }
}

In this example, the MathOperations class contains static variables (PI, EULER_NUMBER, and GOLDEN_RATIO) that serve as constants representing commonly used mathematical values. The MathApp class demonstrates how to access these static variables as constants and use them in mathematical calculations.

The output of the above code is as follows:

Value of Pi: 3.14159
Value of Euler's Number: 2.71828
Value of Golden Ratio: 1.61803
Area of a Circle with Radius 5: 78.53975
e^2: 7.3890461584
Accessing Local Variables

Local variables are accessible only within the block where they are defined. They must be initialized before use.

public class Calculator {

    public static int add(int num1, int num2) {
        // Local variable sum is declared and initialized within this method
        int sum = num1 + num2;

        // The local variable sum is used within this method
        System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);

        // The local variable sum is not accessible outside of this method
        return sum;
    }

    public static void main(String[] args) {
        // Accessing the add method with different values
        int result1 = add(4, 7);
        int result2 = add(11, 18);
        
        System.out.println("First result: " + result1);
        System.out.println("Second result:" + result2);
        // Trying to access the local variable sum outside of the method will result in a compile-time error
        // Uncommenting the line below will result in an error:
        // System.out.println("Trying to access sum outside of the method: " + sum);
    }
}

In this example, the add method has a local variable sum that is used to calculate the sum of two numbers (num1 and num2). The sum variable is accessible only within the add method. It cannot be accessed outside of this method or in the main method. The main method calls the add method with different values and assigns the result in variables (result1 and result2). Attempting to access the local variable sum outside of the add method would result in a compile-time error because sum is a local variable with limited scope.

The output of the above code is as follows:

Sum of 4 and 7 is: 11
Sum of 11 and 18 is: 29
First result: 11
Second result:29
Naming Conventions for Variables
  • Use a meaningful variable names that will tell the reader what the variable is for and what the variable is representing in the program. For example, if you wish to store a roll number on Student, a variable name such as rollNo would be easier to remember than a variable name such as var2.
  • Java variable names are case sensitive. Start variable names with a lowercase letter and capitalize subsequent words (camelCase). For example, firstName, lastName, etc.
  • Java variable names must start with a letter or underscore _ or a dollar sign $ character. After the first character in a variable name, the name can also contain numbers from 0 to 9 (in addition to letters, the dollar sign $, and the underscore _ character). No special characters are allowed.
  • We cannot use reserved keywords as variables name in Java. For example: the words String or while are reserved words in Java. Therefore, you cannot String or while as a variable name.
  • All uppercase letters with underscores to separate subsequent words are used to name constant variables, for example, DATE_PATTERN.

Here are some examples of valid and invalid variable names:

Valid Variable Names
Invalid Variable Names
name #name
name2 2name
_name21 21_name
NAME ()NAME
Name -Name
first_name first_name()
$lastName @lastName