Codiqo

Learn Java · lesson 2 of 61 · about 6 minutes

Variables

Keep count of seats and sales in int variables, change them, and print them.

What you'll learn

  • Make a variable with a type
  • Use int for whole numbers and double for decimals
  • Change a value with =

Keep count

A booking system has to remember numbers that change: seats left, tickets sold. Keep each one in a variable: a value with a name. In Java you say what type it holds when you make it:

  • int holds whole numbers, like 120 or -3
  • double holds numbers with a decimal point, like 4.5

When you print, + joins text and a value: "Sold: " + sold.

Seats and sales

public class Main {
    public static void main(String[] args) {
        int seatsLeft = 120;
        int sold = 0;
        System.out.println("Seats left: " + seatsLeft);
        System.out.println("Sold: " + sold);
    }
}

Output

Seats left: 120
Sold: 0

Values change

Once a variable exists, = gives it a new value, and the old one is gone. Here = stores a value: it doesn't ask whether two things are equal.

seatsLeft = seatsLeft - 4; works out the right side first, using the old value, then stores the answer.

Step through it to watch the seats go

public class Main {
    public static void main(String[] args) {
        int seatsLeft = 120;
        seatsLeft = seatsLeft - 4;
        seatsLeft = seatsLeft - 2;
        System.out.println("Seats left: " + seatsLeft);
    }
}

Output

Seats left: 114

Tip

Write the type only once, when you make the variable. After that, use just the name: writing int seatsLeft a second time would make another variable with the same name, and the compiler stops you.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.