Skip to main content

Java Variables

Java variables: declarations, types, scope, naming conventions, instance/class variables, type inference, widening, narrowing, and promotions

Updated 10 min readMarkdown
Part of seriesJava Basics
Java Variables

In this article, we're going to talk about variables in Java. We use variables to temporarily store data in a computer's memory.

What is a Variable?

A variable, as the name suggests, acts as a placeholder whose value can change during program execution. In Java, a variable represents a named reference to a specific memory location where its value is stored.

How to Declare a Variable?

Before using a variable, you must declare it. The syntax for declaring a variable in Java is as follows:

[data_type] [variable_name] = [variable_value];

Here’s what each part means:

  • data_type: Refers to the type of information stored in the memory area. It determines the operations that can be performed on the variable and the valid values it can hold.

  • variable_name: The name of the variable, distinguishing it from others. Variable names cannot start with a digit; they usually begin with a letter. Choosing meaningful and readable names improves code clarity.

  • variable_value: The initial value to be stored in the memory area.

Examples of valid variable declarations in Java:

int i = 10; // Variable of int type
String str = "howtodoinjava.com"; // Variable of String type
Object obj = new Object(); // Variable of Object type
int[] scores = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // Variable of int array type

You can also declare multiple variables of the same type in a single statement:

int i = 1, j = 2;

Or separate declaration and initialization:

int i;
i = 1;

Example

Once a variable is declared, you can access and modify its value using its name.

int i = 10;
int j = 10;

int sum = i + j;

System.out.println(sum); // Prints 20

Remember that you can only assign a value of the same type as the initial variable. For instance, sum must be an int or another numeric type; it cannot be a String, Boolean, or any other type.

Type Inference

Type inference is a feature that enables the compiler to deduce the type of a variable from the context in which it is used. This means you don't have to explicitly specify the type of the variable; the compiler figures it out for you.

Starting from Java 10, you can use the var keyword to allow automatic type inference based on the assigned value:

var language = "Java"; // String
var num = 1; // int

While this makes code concise, use it judiciously to maintain readability.

Example

public class TypeInferenceExample {
    public static void main(String[] args) {
        var language = "Java"; // Inferred as String
        var num = 1; // Inferred as int
        var list = List.of(1, 2, 3); // Inferred as List<Integer>

        System.out.println("Language: " + language);
        System.out.println("Number: " + num);
        System.out.println("List: " + list);
    }
}

In this example, the types of language, num, and list are inferred by the compiler based on the assigned values. This makes the code more concise while still being readable.

Widening / Promotions

Widening

Widening occurs when a smaller primitive type value is automatically accommodated in a larger/wider primitive data type. This process is also known as implicit type casting or type promotion. In Java, widening conversions are safe because they do not result in data loss. The smaller type is converted to a larger type, which can hold all possible values of the smaller type.

For example:

int smallValue = 10;
long largerValue = smallValue; // No data loss or error

In this example, the int value smallValue is automatically converted to a long value largerValue. Since long is a larger data type than int, this conversion is safe and does not result in any data loss.

Promotions

Promotions occur when operands of different types are used in an operation. Java promotes smaller types to larger types to prevent data loss during the operation. This is common in arithmetic operations where operands of different types are involved. The smaller type is promoted to the larger type to ensure that the operation can be performed without losing information.

For example:

byte b = 10;
int i = b; // byte is promoted to int

In this example, the byte value b is promoted to an int value i. This promotion ensures that the byte value can be used in operations that require an int without any risk of data loss.

Another example involving arithmetic operations:

byte b = 10;
int i = 5;
int result = b + i; // byte is promoted to int before addition

Here, the byte value b is promoted to an int before the addition operation with i. This ensures that the addition is performed correctly and the result is stored in an int variable.

Key Points

  1. Widening: Automatic conversion from a smaller to a larger primitive type. Safe and does not result in data loss.

  2. Promotions: Automatic promotion of smaller types to larger types during operations to prevent data loss. Common in arithmetic operations.

Narrowing / Type Conversions

Narrowing

Narrowing happens when a larger primitive type value is assigned to a smaller size primitive data type. This process can lead to data loss because the smaller type has fewer bits available to store the value. Therefore, explicit type-casting is required to perform narrowing conversions.

Example:

int intValue = 198;
byte byteValue = (byte) intValue; // Data loss
System.out.println(byteValue); // Prints -58

In this example, the int value 198 is cast to a byte. Since the byte type can only hold values from -128 to 127, the value 198 cannot be represented accurately. This results in data loss, and the printed value is -58.

Type Conversions

Type conversions can be either implicit or explicit.

Implicit Conversions

Implicit conversions happen automatically when a smaller primitive type is assigned to a larger primitive type. This is safe because the larger type can accommodate all possible values of the smaller type without any data loss.

Example:

int i = 10;
double d = i; // int is implicitly converted to double

In this example, the int value 10 is implicitly converted to a double. The double type can hold much larger values than int, so this conversion is safe and automatic.

Explicit Conversions

Explicit conversions, also known as casting, are required when converting a larger primitive type to a smaller primitive type. This is necessary because the smaller type may not be able to hold the value of the larger type, leading to potential data loss.

Example:

double d = 10.5;
int i = (int) d; // double is explicitly converted to int

In this example, the double value 10.5 is explicitly cast to an int. The fractional part .5 is lost in this conversion, and the resulting value of i is 10.

Key points

  • Narrowing: Converting a larger primitive type to a smaller one, requiring explicit casting and potentially leading to data loss.

  • Implicit Conversions: Automatic conversion from a smaller to a larger primitive type, safe and without data loss.

  • Explicit Conversions: Manual conversion from a larger to a smaller primitive type, requiring casting and potentially leading to data loss.

Types of Variables and Scope and Lifetime

The scope of a variable refers to the region of the code where the variable is accessible. Variables can have different scopes:

  • Instance Variables

  • Static Variables

  • Local Variables

  • Method Arguments

Instance Variables

  • Instance variables are non-static fields declared within a class but outside any method, constructor, or block.

  • Each instance (object) of the class has its own copy of these variables.

  • They are initialized when an object of the class is created.

  • They exist as long as the object exists and are destroyed when the object is destroyed.

  • Instance variables are used to store the state of an object. For example, in a Car class, instance variables might include color, model, and year.

Example:

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

    // Constructor
    public Car(String color, String model, int year) {
        this.color = color;
        this.model = model;
        this.year = year;
    }
}

Class Variables (Static Variables)

  • Class variables are declared with the static keyword within a class but outside any method, constructor, or block.

  • There is only one copy of a class variable, and it is shared among all instances of the class.

  • They are initialized only once, at the start of the program execution.

  • They exist for the duration of the program and are destroyed when the program ends.

  • Class variables are used to store data that is common to all instances of the class. For example, in a Car class, a class variable might be numberOfWheels, assuming all cars have the same number of wheels.

Example:

public class Car {
    // Class variable
    static int numberOfWheels = 4;

    // Instance variables
    String color;
    String model;
    int year;

    // Constructor
    public Car(String color, String model, int year) {
        this.color = color;
        this.model = model;
        this.year = year;
    }
}

Local Variables

Local variables are declared within a method, constructor, or block. They are created when the method, constructor, or block is entered and destroyed once it is exited. Local variables are not accessible outside the method, constructor, or block in which they are declared.

Example:

public class Example {
    public void method() {
        int localVariable = 10; // Local variable
        System.out.println(localVariable);
    }
}

Method Arguments

Method arguments are variables that are passed to a method when it is called. They are used to provide input to the method. Method arguments are also local to the method in which they are declared.

Example:

public class Example {
    public void method(int argument) { // Method argument
        System.out.println(argument);
    }
}

Variable Naming Conventions in Java

Java has specific conventions for naming variables to improve code readability and maintainability.

  • Variable names should start with a letter, dollar sign ($), or underscore (_).

  • Subsequent characters can be letters, digits, dollar signs, or underscores.

  • Variable names are case-sensitive.

  • Use camelCase for variable names, starting with a lowercase letter and capitalizing subsequent words (e.g., myVariable).

Difference between Instance and Class Variables

Instance variables are associated with an instance of a class, while class variables (also known as static variables) are associated with the class itself.

AspectInstance VariablesClass Variables (Static Variables)
AssociationTied to a specific instance of a class.Tied to the class itself and shared among all instances.
Memory AllocationStored in the heap memory, one for each object.Stored in the method area (part of the heap) and only one copy exists.
AccessAccessed using the object reference.Can be accessed using the class name or an object reference.
InitializationInitialized when an object is created.Initialized when the class is loaded.

Example

public class Car {
    // Instance variable
    private String color;

    // Class variable (static variable)
    private static int numberOfWheels = 4;

    // Constructor
    public Car(String color) {
        this.color = color;
    }

    // Instance method
    public String getColor() {
        return color;
    }

    // Class method (static method)
    public static int getNumberOfWheels() {
        return numberOfWheels;
    }

    public static void main(String[] args) {
        // Creating instances of Car
        Car car1 = new Car("Red");
        Car car2 = new Car("Blue");

        // Accessing instance variable
        System.out.println("Car 1 color: " + car1.getColor());
        System.out.println("Car 2 color: " + car2.getColor());

        // Accessing class variable
        System.out.println("Number of wheels: " + Car.getNumberOfWheels());
    }
}

In this example:

  • color is an instance variable, unique to each Car object.

  • numberOfWheels is a class variable, shared among all Car objects.

Conclusion

Variables in Java are placeholders for storing data in memory. They can be declared with a specific data type and name, and their values can change during program execution. Java supports type inference with the var keyword, automatic type promotions, and explicit type conversions. Variables have different scopes: instance variables, class variables, local variables, and method arguments. Proper naming conventions and understanding the differences between instance and class variables are crucial for writing clear and efficient Java code. The Java tutorial page lists down all the important topics you can go through to get a deeper understanding of the language basics and advanced concepts.

About the author

No comments yet. Be the first to comment.