SyntaxPilot
Courses/Java/Lesson 2
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 2 of 51

Variables and data types

scheduled

These are the notes for Java episode 2. You will learn why programs need variables, how to declare and change one, the eight primitive types, and the bugs that catch every beginner: overflow, the float trap and uninitialised variables. Every example below runs as-is in the SyntaxPilot compiler.

The problem: one value copied everywhere

Raju runs a chai stall. One chai costs ₹10, and his program prints bills:

public class Main {
    public static void main(String[] args) {
        System.out.println("Chai x 2 = " + 10 * 2);
        System.out.println("Chai x 3 = " + 10 * 3);
        System.out.println("Chai x 5 = " + 10 * 5);
    }
}

Output:

Chai x 2 = 20
Chai x 3 = 30
Chai x 5 = 50

When the price goes up to ₹12, every 10 must be changed by hand. Change only one line and the program happily prints a wrong bill: no error, wrong answer. Java cannot know that every 10 means "the price of chai".

The fix: write the value once, give it a name, and use the name everywhere. That named box is a variable.

Variables: a labelled box

Think of kitchen jars: the label (sugar) is the name, what's inside is the value, and you can refill the same jar.

int price = 12;
System.out.println("Chai x 2 = " + price * 2);   // 24
System.out.println("Chai x 3 = " + price * 3);   // 36
System.out.println("Chai x 5 = " + price * 5);   // 60

Change 12 to 15 in one place and the whole bill updates.

Anatomy of a variable

Part In int price = 12; Meaning
Type int what kind of box (whole numbers)
Name price the label you use in code
= assignment put the value on the right into the box
Value 12 what goes inside
int cups;        // declaration: make the box
cups = 3;        // assignment: put a value in
price = 15;      // change it later: no type the second time

In Java = does not mean "is equal to"; it means "put into". (Comparison is ==, covered with operators.)

Data types: the right box for each thing

int price = 12.5; fails:

error: incompatible types: possible lossy conversion from double to int

An int holds only whole numbers. Instead of silently dropping the .5, Java refuses to compile. Use a box made for decimals:

double price = 12.5;
char size = 'L';
boolean isOpen = true;
String shop = "Raju Chai";
System.out.println(shop + " | size " + size + " | open: " + isOpen);
System.out.println("Chai x 4 = " + price * 4);

Output:

Raju Chai | size L | open: true
Chai x 4 = 50.0
  • char uses single quotes and holds one character; String uses double quotes and holds many.
  • String starts with a capital S because it is a class, not a primitive type.

The 8 primitive types

Type Size Range / values Use it for
byte 1 byte -128 to 127 raw bytes, tiny numbers
short 2 bytes -32,768 to 32,767 rarely used
int 4 bytes about ±2.1 billion (2,147,483,647) default whole number
long 8 bytes about ±9.2 × 10¹⁸ big counts, money in paise, IDs
float 4 bytes ~7 significant digits memory-tight decimals
double 8 bytes ~15–16 significant digits default decimal
char 2 bytes one Unicode character 'A', '₹'
boolean — true / false yes/no flags

Interview point: these sizes are fixed by the Java specification on every machine (unlike C, where int size depends on the platform). This is part of "write once, run anywhere".

Overflow: when a number is too big

int india = 1400000000;      // fine, below 2.1 billion
int world = 8000000000;      // compile error
error: integer number too large

Java catches a literal that cannot fit. It cannot catch overflow that happens while the program runs:

int views = 2147483647;      // Integer.MAX_VALUE
views = views + 1;
System.out.println(views);   // -2147483648  (no error!)

The value wraps around like an old odometer. The fix is a bigger box, with L on big literals:

long world = 8000000000L;
System.out.println(world);   // 8000000000

The float trap

A decimal literal like 3.14 is a double by default, so this fails:

float pi = 3.14;   // error: possible lossy conversion from double to float
float pi = 3.14f;  // OK: the f makes it a float literal

In practice, just use double unless you have a reason not to.

Constants with final

Some values must never change, like 5% GST:

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

final locks the box; the mistake is caught before the program runs. Constants are named in UPPER_CASE.

Naming rules and conventions

  • Allowed: letters, digits, _ and $; must not start with a digit (2cups is invalid).
  • No spaces, no keywords (class, int, public …).
  • Case-sensitive: name and Name are different variables.
  • Convention: camelCase for variables (totalPrice), UPPER_CASE for constants (GST).

Common mistakes (and the real error messages)

Mistake Code Error
Using an empty box int cups; System.out.println(cups); variable cups might not have been initialized
Wrong name or case System.out.println(Price); cannot find symbol
Name starts with a digit int 2cups = 2; not a statement (and more)
Decimal into int int p = 12.5; possible lossy conversion from double to int
Decimal into float float f = 1.5; possible lossy conversion from double to float

Mini project: the chai bill

public class Main {
    public static void main(String[] args) {
        String shop = "Raju Chai Stall";
        int cups = 3;
        double price = 12.5;
        final double GST = 0.05;
        double bill = cups * price;
        double total = bill + bill * GST;
        System.out.println("=== " + shop + " ===");
        System.out.println("Cups:\t" + cups);
        System.out.println("Bill:\t" + bill);
        System.out.println("Total:\t" + total);
    }
}

Output:

=== Raju Chai Stall ===
Cups:   3
Bill:   37.5
Total:  39.375

(Rounding money to two decimals comes in a later episode.)

Practice

  1. Store your age, height in metres, first initial and whether you are a student in four variables with the best types, and print them on one line.
  2. Make a bill for your favourite shop with at least three items and a final tax rate.
  3. Print Integer.MAX_VALUE + 1 and explain the output.
  4. Which type would you use for a 10-digit phone number, and why?
Solutions and hints
  1. int age = 21; double height = 1.72; char initial = 'A'; boolean isStudent = true;
  2. Use double for prices and final double TAX = 0.05;, then total = subtotal + subtotal * TAX.
  3. It prints -2147483648: int overflow wraps around to the minimum value.
  4. A phone number is an identifier, not a quantity: store it as a String (it may have a leading 0 or +91). If you must use a number, it needs long, because 10 digits exceed int.

Quick quiz

Which line gives a compile error?

  • A. int a = 10;
  • B. double b = 10;
  • C. float c = 1.5;
  • D. long d = 10L;
Answer

C. 1.5 is a double literal, and putting a double into a float is a lossy conversion. Fix: float c = 1.5f;. (B is fine: a small whole number fits in a bigger decimal box.)

Interview questions

  • What is the difference between declaration and initialisation?
  • How many primitive types does Java have? Name them with their sizes.
  • Why is String not a primitive type?
  • What is integer overflow, and how do you prevent it? (long, Math.addExact)
  • What does final do to a local variable?

Summary

  • A variable is a named box: type name = value;.
  • Pick the type for what goes inside: int, double, char, boolean, String, and long for big values.
  • Watch for overflow, add L to big long literals and f to float literals.
  • Use final for values that must never change.

Next episode: operators. Four friends split ₹250 and Java says each pays ₹62. Where did the 50 paise go?