Codiqo

Learn Java · lesson 4 of 61 · about 7 minutes

Arithmetic

Work out ticket totals in whole cents with + - * / %, and predict when division drops the decimals.

What you'll learn

  • Use the arithmetic operators
  • Predict integer division
  • Know when + adds and when it joins

Money in cents

Back-end code that handles money keeps it in whole cents, not as a decimal: 12.35 dollars is stored as 1235. Decimals in a computer can be very slightly off, and nobody wants to lose a cent.

Java has + - * / %. When both sides of / are ints, the result is an int and the decimals are dropped: 4940 / 100 is 49. % gives the remainder: 4940 % 100 is 40.

Why cents

public class Main {
    public static void main(String[] args) {
        System.out.println(0.1 + 0.2);
        int cents = 10 + 20;
        System.out.println(cents);
    }
}

Output

0.30000000000000004
30

Dollars and cents

public class Main {
    public static void main(String[] args) {
        int total = 4940;
        System.out.println(total / 100);
        System.out.println(total % 100);
        System.out.println(total / 100.0);
    }
}

Output

49
40
49.4

+ does two jobs

With two numbers, + adds. With text on either side, it joins. Java works from left to right, so "Total: " + 2 + 3 is Total: 23: the text is joined with 2 first, then with 3.

Put a sum in brackets to work it out first: "Total: " + (2 + 3) is Total: 5. *, / and % already happen before +, so they need no brackets.

Now try it yourself

This lesson is free in Codiqo, with 9 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.