Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 02 / Topic 1 of 9

Variables: a type, a name, a value

In Java, every variable has a type that is fixed the moment you declare it, and that type never changes. This is the biggest difference from Python, where a name can point to a string today and a number tomorrow. Think of a variable as a labelled box of a fixed shape: a box built for coins cannot suddenly hold a laddoo.

int quantity = 3;                  // a whole number
double price = 149.50;             // a decimal number
String item = "Masala Chai";       // text, in double quotes
boolean inStock = true;            // true or false
char grade = 'A';                  // exactly one character, single quotes

Output (examples/01_variables.java):

Masala Chai
3
149.5
true
A
169.0
0.05
true

Notice 149.50 printed as 149.5: a trailing zero in the decimal part carries no information, so Java drops it.

Reassignment gives a variable a new value of the same type:

price = 169.00;

This does not compile, because the type of quantity is fixed at int forever:

quantity = "three";
// error: incompatible types: String cannot be converted to int

final makes a variable a constant: write it once, never change it again.

final double GST_RATE = 0.05;
// GST_RATE = 0.18;
// error: cannot assign a value to final variable GST_RATE

By convention, constants are written in UPPER_SNAKE_CASE; ordinary variables use camelCase (totalAmount, not total_amount or TotalAmount). A name cannot start with a digit and cannot be a reserved word like class or int.

For primitives, == compares the value directly — there is no separate "same object" check like Python's is, because a primitive is not an object at all.

System.out.println(quantity == 3);   // true

Full program: examples/01_variables.java.

Done here? The practice set for Part 2 — including the solutions — is on the part page.

Search the guide