← Learning Hub
Beginner

Variables and Data Types

A variable stores a value. In Java you must say its type when you create it.

A variable is a named box that holds a value. Java asks you to label the box with its type up front - "this box only holds whole numbers". If you later try to put text in it, the compiler refuses. This catches a whole family of bugs before your program runs.

Java has two kinds of types. Primitive types are simple values stored directly (numbers, true/false, single characters). Reference types like String, arrays and your own classes are objects; the variable holds a reference (an address) pointing to the object.

Primitive types (simple values)

  • int whole numbers: int qty = 3;
  • long big whole numbers: long views = 5000000000L;
  • double decimal numbers: double price = 499.99;
  • boolean true or false: boolean inStock = true;
  • char one character: char grade = 'A';

Why so many number types? Memory and range. int holds up to about 2.1 billion - fine for quantities and prices in paise. For bigger values (like views or bank transaction ids) use long. For money in real apps, professionals often use long paise or BigDecimal, because double can give tiny rounding errors (0.1 + 0.2 is not exactly 0.3).

Text with String

String holds text. Join strings with +.

Strings are objects with many useful methods: length(), toUpperCase(), contains(), substring(). Compare their text with .equals(), never with == (which compares whether they're the same object). This is one of the most common Java beginner bugs.

Example
You can edit this code.
Use final for a value that must not change: final double GST = 0.18;
Key points
  • Every variable has a type: int, long, double, boolean, char, String...
  • Primitives hold values; objects like String are reached through references.
  • Compare Strings with .equals(), not ==.
  • Use final for constants.

📝 Test yourself

1. Which type stores decimal numbers?
2. Which type holds text like "Hello"?
3. Fill in the keyword for a value that cannot change:
int MAX = 10;