Project Based Learning in Java

Variables and Constants

Declarations, initialisation, variable kinds, and final constants.

Lecture 1.1.2 CO1 aligned Unit 1

Learning outcome: Declare, initialise, and use variables and constants correctly in Java programs.

A variable is a named storage location with a specific type. A final variable can be assigned only once. In everyday Java usage, a shared named constant is usually a static final field; in the precise language rules, a constant variable is a final primitive or String variable initialised with a constant expression.

Variable Declaration and Initialisation

Declaring a variable means giving it a type and a name. Initialising a variable means giving it its first value.

In simple terms: Declaring is labelling an empty box with what it may hold. Initialising is putting the first thing inside it.

Parts of a Java variable declaration int age = 25; type name initial value
Figure 1. A variable declaration identifies the type, name, and optional initial value.

Examples:

int age;                 // declaration only
age = 25;                // initialisation later

int count = 50;          // declaration and initialisation together
int x = 1, y = 2, z = 3; // multiple variables of the same type

Kinds of Variables

Java has different kinds of variables based on where they are declared.

In simple terms: Where a variable is declared decides how long it lives: a local variable lasts as long as the method call, an instance field as long as its object, and a static field as long as the class stays loaded.

Kind Where declared Lifetime Default value?
Local variable Inside a method, constructor, or block Exists only while that block runs No
Instance variable Inside a class, outside methods, without static One copy per object Yes
Static variable Inside a class with static One shared copy for the class Yes
Parameter In a method or constructor header Exists during the method call Value supplied by caller

Example:

public class Counter {
    int instanceCount;          // instance variable
    static int totalCounters;   // static variable

    public void increase(int step) { // step is a parameter
        int result = instanceCount + step; // result is local
        instanceCount = result;
    }
}

Local Variables Must Be Initialised

Local variables do not receive default values.

In simple terms: Fields are handed a default; local variables are not. The compiler refuses to read one you have not written to — a rejected program rather than a mysterious value.

public class LocalDemo {
    public static void main(String[] args) {
        int total;
        // System.out.println(total); // error: variable might not have been initialised

        total = 10;
        System.out.println(total);
    }
}

Fields do receive default values:

public class FieldDemo {
    int total;          // defaults to 0
    boolean ready;      // defaults to false
    String name;        // defaults to null
}

final Variables and Constants

Use final when the variable must not be assigned again after its first assignment.

In simple terms: final means assigned once, not frozen forever. A final reference cannot be pointed at a different object, but the object it points at may still change inside.

final double PI = 3.14159;
final int MAX_MARKS = 100;

For a constant shared by every object, declare a class field with both static and final:

class ExamRules {
    static final int MAX_MARKS = 100;
}

Attempting to reassign a final variable causes a compilation error:

final int MAX_MARKS = 100;
// MAX_MARKS = 90; // error

By convention, constants use uppercase letters with underscores.

Constant Meaning
MAX_MARKS Maximum marks in an exam
PI Mathematical constant
MIN_AGE Minimum allowed age

final prevents reassignment of a reference; it does not make the referenced object immutable.

final int[] scores = {70, 80};
scores[0] = 95;          // allowed: the same array is modified
// scores = new int[2];  // compilation error: the reference is final

Assignment and Reassignment

The assignment operator = stores a value in a variable.

int score = 80;
score = 95;        // allowed: score is not final

The left side must be a variable that can receive a value. The right side is an expression that produces a value compatible with the variable's type.

int a = 10;
int b = 20;
int sum = a + b;

Worked Example: Profile Card

public class Profile {
    public static void main(String[] args) {
        String name = "Aarav Sharma";
        int age = 19;
        double height = 1.75;
        char initial = 'A';
        boolean isStudent = true;

        System.out.println("Name      : " + name);
        System.out.println("Age       : " + age);
        System.out.println("Height(m) : " + height);
        System.out.println("Initial   : " + initial);
        System.out.println("Student?  : " + isStudent);
    }
}

Output:

Name      : Aarav Sharma
Age       : 19
Height(m) : 1.75
Initial   : A
Student?  : true

Worked Example: Circle with a Constant

public class Circle {
    public static void main(String[] args) {
        final double PI = 3.14159;
        double radius = 5;

        double area = PI * radius * radius;
        double circumference = 2 * PI * radius;

        System.out.println("Area          = " + area);
        System.out.println("Circumference = " + circumference);
    }
}

Output:

Area          = 78.53975
Circumference = 31.4159

Common Mistakes

Mistake Correction
Using a local variable before assigning it Give it a value before reading it.
Naming constants like normal variables Use UPPER_SNAKE_CASE.
Trying to change a final variable Assign a final variable once only.
Assuming a final reference makes an object immutable The reference cannot change, but the object may still be mutable.
Declaring multiple variables with unclear names Prefer clear individual declarations when readability improves.
Choosing a type that is too small Use a type that fits the possible range of values.

Practice

  1. Declare variables for name, age, height, first initial, and student status.
  2. Declare a constant named MAX_MARKS with value 100.
  3. Write a program that calculates the perimeter and area of a rectangle.
  4. Explain the difference between a local variable and an instance variable.

Quick Check

1. What is the difference between declaration and initialisation?

Declaration gives a variable its type and name. Initialisation gives the variable its first value.

2. Which keyword prevents a variable from being assigned again?

final prevents a variable from being assigned again. Shared class constants are normally declared static final.

3. Do local variables have default values?

No. Local variables must be assigned a value before they are read.

4. What naming style is used for constants?

Constants use UPPER_SNAKE_CASE, for example MAX_MARKS or MIN_AGE.

5. What is the difference between an instance variable and a static variable?

An instance variable belongs to each object, so every object has its own copy. A static variable belongs to the class, so one shared copy is used by all objects of that class.

6. Does final List<String> names make the list immutable?

No. It prevents names from referring to a different list; the existing list can still change unless its own API or implementation prevents modification.

Summary

Variables store values with a defined type. Local variables must be initialised before use, while fields get default values. final means a variable is assigned once, not that every referenced object is immutable. Shared named constants are normally static final fields and use uppercase letters with underscores.