Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Variables

A variable is a named slot in memory where a program keeps a value. In Java every variable has a type: it defines which values the variable can hold, and it never changes during the variable's life.

Declaring a variable

To create a variable, write the type, the name and, after an = sign, the initial value:

void main() {
    int age = 25;
    IO.println(age);
}

Output:

25

int is the type for whole numbers. The = sign here is not a comparison but assignment: the value on the right is stored in the variable on the left.

Changing the value

A variable can be given a new value. The type is written only once — in the declaration:

void main() {
    int score = 10;
    score = 15;
    score = score + 5;
    IO.println(score);
}

Output:

20

In score = score + 5 Java first takes the current value 15, adds 5 and stores the result back in score.

Text and other types

Text uses the String type, fractional numbers use double, and yes/no values use boolean. Variables can be joined with text using +:

void main() {
    String name = "Anna";
    double price = 4.99;
    boolean inStock = true;
    IO.println(name + " bought coffee for $" + price + ", in stock: " + inStock);
}

Output:

Anna bought coffee for $4.99, in stock: true

var

When the type is obvious from the value, you can write var instead — the compiler infers the type itself:

void main() {
    var city = "London";
    var year = 2025;
    IO.println(city + ", " + year);
}

Output:

London, 2025

The type is still there: city is a String and year is an int. You cannot store a string in year.

Constants

The word final forbids changing a variable after its first assignment. Such values are called constants, and their names are often written in capital letters:

void main() {
    final double VAT = 0.2;
    double price = 100;
    IO.println(price * VAT);
}

Output:

20.0

Trying to assign a new value to VAT stops compilation.

Variable names

A name can contain letters, digits, _ and $, but cannot start with a digit. Java uses camelCase: the first word starts with a lowercase letter, every next one with a capital: totalPrice, userName. Case matters: age and Age are different variables.

Common mistake

A variable declared without a value cannot be read until something is stored in it:

void main() {
    int total;
    IO.println(total);
}

Output:

Main.java:3: error: variable total might not have been initialized
    IO.println(total);
               ^
1 error
error: compilation failed

The compiler is strict about this. Give the variable a value before its first use — the easiest way is right in the declaration.

Thanks for reading!

Donate to the site — we work hard for you.