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 €
| Type | Holds | Example |
|---|---|---|
int | a whole number (up to about 2 billion) | 42, -7 |
long | a very large whole number | 8000000000L |
double | a decimal number | 4.5, -0.25 |
boolean | true or false | true, false |
char | a character, between single quotes | 'B' |
String | a 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.
Text description of the animation
- A player earns points in a game.
- points is 100.
- = computes the right-hand side with the old value, then replaces: points is 120.
- points *= 2 is a shortcut for points = points * 2.
- A String variable holds a text.
- + sticks on a new piece: rank now refers to the text "Bronze II".
- We display the rank and the points.
finalmakes 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.varlets Java deduce the type from the value:var total = 12.5;creates adouble. The type stays fixed:varisn'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) 7is an explicit conversion (a "cast"): we turn the integer into adoublebefore the division.0.1 + 0.2isn't exactly0.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
bill * (1 + TIP), with final double TIP = 0.10;.Hint 2
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 isfinal, the compiler would refuse to change it anyway. - Displaying
totalwithIO.println(total): you'd get96.36000000000001, not very readable for a restaurant bill.
Summary
- 1The common types: int, long, double, boolean, char and String (a class, with a capital letter).
- 2final stops a variable from changing; var deduces its type, which stays fixed.
- 3Dividing two ints gives an int: convert first with (double).
- 4Java refuses to store a double in an int without an explicit conversion.
- 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.