← Chapter 2 — Core Syntax & Data

6. Variables & Constants

mixed

Description

A variable is a named location that holds a value which may change. Declare its type before using it so Java knows what kind of data it should store.

A constant uses final and receives a value once. Constants make important fixed values, such as a passing score, visible and safer to reuse.

Subtopics

Declaring variables

Description

Declaration gives a type and a name.

Explanation

Initialization assigns the first value.

Example

int score = 76;

Using final

Description

A final variable cannot be reassigned.

Explanation

By convention, named constants use uppercase letters.

Example

final int PASSING_SCORE = 40;

Explanation

Java requires local variables to be assigned before they are read. This protects you from accidentally using an unknown value.

Example

public class VariableDemo {
    public static void main(String[] args) {
        final int PASSING_SCORE = 40;
        int score = 76;
        System.out.println(score >= PASSING_SCORE);
    }
}

Key points

  • Variables have a type and name.
  • final prevents reassignment.
  • Initialize local variables before reading them.

Open reference