Skip to content
KALANBLON
Show contents

Chapter 3 of 4 · 20 min

Variables, types and text

By the end of this chapter, you'll be able to

  • Declare int, double, boolean, char and String variables
  • Use final for a constant and var to let Java deduce the type
  • Predict the result of an integer division and of a conversion
  • Display a number with a fixed number of decimal places with String.format

The basic types

void main() {
    String customer = "Kwame";
    int hours = 3;
    double rate = 4.5;
    boolean helmet = true;
    char category = 'B';

    IO.println(customer + " rents a category " + category + " bike for " + hours + " h");
    IO.println("Helmet included: " + helmet);
    IO.println("To pay: " + hours * rate + " €");
}
Kwame rents a category B bike for 3 h
Helmet included: true
To pay: 13.5 €
TypeHoldsExample
inta whole number (up to about 2 billion)42, -7
longa very large whole number8000000000L
doublea decimal number4.5, -0.25
booleantrue or falsetrue, false
chara character, between single quotes'B'
Stringa text, between double quotes"Kwame"

String starts with a capital letter: it isn't a basic type, but a class. A String variable holds a text object, which offers methods like length() or toUpperCase(). Decimals are written with a dot in the code: 4.5.

Changing, protecting, deducing

We display the rank and the points.

Step 7 of 7
Text description of the animation
  1. A player earns points in a game.
  2. points is 100.
  3. = computes the right-hand side with the old value, then replaces: points is 120.
  4. points *= 2 is a shortcut for points = points * 2.
  5. A String variable holds a text.
  6. + sticks on a new piece: rank now refers to the text "Bronze II".
  7. We display the rank and the points.
  • final makes a variable unchangeable: final double VAT = 0.2;. Any attempt to change it is refused at compile time. By convention, constants are written in capital letters.
  • var lets Java deduce the type from the value: var total = 12.5; creates a double. The type stays fixed: var isn't an "anything goes" variable.
  • The shortcuts +=, -=, *=, /= and ++ (add 1), -- (subtract 1) are used a lot.

Calculations and displaying decimals

As in many languages, dividing two integers gives an integer: the decimal part is cut off. % gives the remainder.

void main() {
    int minutes = 135;
    IO.println(minutes / 60 + " h " + minutes % 60 + " min");
    IO.println(7 / 2);
    IO.println(7.0 / 2);
    IO.println((double) 7 / 2);
    IO.println(0.1 + 0.2);
}
2 h 15 min
3
3.5
3.5
0.30000000000000004
  • (double) 7 is an explicit conversion (a "cast"): we turn the integer into a double before the division.
  • 0.1 + 0.2 isn't exactly 0.3: doubles are stored in binary, and some decimals don't come out exactly. That's normal, and it's why we round when displaying.

To display a number with a fixed number of decimal places, use String.format with a format:

void main() {
    double price = 12.0 * 1.2;
    IO.println(price);
    IO.println(String.format("%.2f €", price));
    IO.println(String.format("%d items at %.2f €", 3, 4.5));
}
14.399999999999999
14.40 €
3 items at 4.50 €

%.2f displays a decimal number with 2 decimal places, %d a whole number, %s a text. Careful: String.format follows the computer's language settings. On a system set to English, it writes 14.40; on a system set to French, for example, 14,40. IO.println of a double, on the other hand, always uses a dot.

Your turn

Worked exercise

Worked exercise: the restaurant bill

Three friends share a bill of €87.60, and add a 10% tip. Declare the bill and the number of people, along with a final constant for the tip rate. Display the total and each person's share, with two decimal places: Total: 96.36 € and Per person: 32.12 €.

Hint 1
The total is bill * (1 + TIP), with final double TIP = 0.10;.
Hint 2
The share is total / people. Since total is a double, the division isn't an integer division.
Show the solution and common mistakes
void main() {
    final double TIP = 0.10;
    double bill = 87.60;
    int people = 3;
    double total = bill * (1 + TIP);
    double share = total / people;
    IO.println(String.format("Total: %.2f €", total));
    IO.println(String.format("Per person: %.2f €", share));
}
Total: 96.36 €
Per person: 32.12 €

Common mistakes:

  • Writing TIP = 10: the rate is a proportion, 0.10, not a percentage. And since the variable is final, the compiler would refuse to change it anyway.
  • Displaying total with IO.println(total): you'd get 96.36000000000001, not very readable for a restaurant bill.

Summary

  1. 1The common types: int, long, double, boolean, char and String (a class, with a capital letter).
  2. 2final stops a variable from changing; var deduces its type, which stays fixed.
  3. 3Dividing two ints gives an int: convert first with (double).
  4. 4Java refuses to store a double in an int without an explicit conversion.
  5. 5String.format("%.2f", x) displays two decimal places, with the decimal separator of the system's language.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.