Part 1 · The core language

2Values, variables and types

A program that only prints fixed text could be replaced by a poster. Real programs remember things: a score, a price, a name, a result they calculated a moment ago. This lesson is about how Java remembers values, how it decides what kind of value each one is, and what happens when you calculate with them. Most of the surprises in beginners' programs, such as an average that comes out as 7 instead of 7.5, come from the rules in this lesson.

By the end you will be able to

  • declare a variable, give it a value and change it, and say what each part of int age = 30; means
  • choose between int, long, double, boolean, char and String for a piece of data
  • predict the type and value of an arithmetic expression, including integer division and + used on text
  • convert between types with a cast, and say what is lost when you do
  • explain integer overflow and floating-point imprecision, and when each one matters
  • read the compiler's messages for the mistakes this topic produces

Variables: named boxes

A computer keeps the data a running program works on in its memory. A variable is a place in memory that holds one value and has a name you choose. The usual picture is a box with a label on it. You put a value into the box, you can look at the value whenever you like, and you can later replace it with a different one.

age 30 type: int int age = 30; price 2.5 type: double double price = 2.5; grade 'A' type: char char grade = 'A'; name "Ada" type: String String name = "Ada";

The picture is a simplification, and a useful one. In reality the JVM reserves a few bytes of memory and remembers that your name stands for that spot. The type decides how much room is reserved and how the bytes are read.

Anatomy of a declaration

int age = 30;
PartRole
intThe type: what kind of value this box may hold. int means a whole number (integer is the mathematical word for a whole number, and int is short for it).
ageThe name: how the rest of the program refers to the box.
=The assignment operator: store the value on its right into the box on its left.
30The value to store.
;Ends the statement, as in lesson 1.

Here is a variable changing over several statements. Read it as the JVM does, one line at a time.

code/m02-values-and-types/Boxes.java
// A variable is a named box that holds one value. The value can change.
public class Boxes {
    public static void main(String[] args) {
        int score = 10;
        System.out.println(score);

        score = 25;
        System.out.println(score);

        score = score + 5;
        System.out.println(score);

        int bonus = score;
        score = 0;
        System.out.println(bonus);
        System.out.println(score);
    }
}
Terminal, in code/m02-values-and-types
> javac Boxes.java
> java Boxes
10
25
30
30
0

Until now println has been given text. It can print numbers too: given a variable, it prints the value currently in the box. Follow score:

score 10 after int score = 10; score = 25; score 25 the 10 has been replaced score = score + 5; score 30 read 25, add 5, store 30

The sign = means store, not equals

In mathematics score = score + 5 is impossible: no number is equal to itself plus five. In Java it is an ordinary instruction, because = does not claim that two things are equal. It is an order: work out the right side, store the result in the variable on the left. Data flows from right to left. The left side must therefore be a box to store into:

code/m02-values-and-types/broken/StoreTarget.java
public class StoreTarget {
    public static void main(String[] args) {
        int total = 5;
        total + 1 = 10;
        System.out.println(total);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac StoreTarget.java
StoreTarget.java:4: error: unexpected type
        total + 1 = 10;
              ^
  required: variable
  found:    value
1 error

The message says that a variable was required and a value was found. The expression total + 1 produces a value; it is not a box that can hold one. A single = does not ask a question; it stores. Java has a separate symbol for asking whether two values are equal, which lesson 3 introduces.

Predict

What do these statements print? Work through them with boxes, one line at a time, before you open the answer.

code/m02-values-and-types/predict/Trace.java (lines 3 to 8)
int a = 3;
int b = 4;
a = b;
b = a + 1;
System.out.println(a);
System.out.println(b);
Reveal the answer
Terminal, in code/m02-values-and-types/predict
> javac Trace.java
> java Trace
4
5

It prints 4 and then 5. a = b; copies the 4 from b into a, so both boxes hold 4. Then b = a + 1; reads a (4), adds 1 and stores 5 in b. If you answered 3 and 4, you read a = b; as a statement about equality instead of as an order to copy. The copy goes from right to left, and the box on the right is left unchanged.

Types: what kind of value is in the box

Every value in Java has a type. The type decides which values are allowed, how much memory they take and which operations make sense. The whole number 42, the decimal number 3.14 and the text "hello" are stored in different ways, and you cannot add 1 to a text the way you add 1 to a number.

Java is statically typed. Every variable has a type, you state it when you declare the variable, and it cannot change. The compiler checks every statement against the types before the program runs. This is the compile-time checking from lesson 1, now applied to your data:

code/m02-values-and-types/broken/IntText.java
public class IntText {
    public static void main(String[] args) {
        int age = "30";
        System.out.println(age);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac IntText.java
IntText.java:3: error: incompatible types: String cannot be converted to int
        int age = "30";
                  ^
1 error

An int box holds whole numbers, and "30" is text, so the compiler refuses to put one into the other. Many type mismatches are reported in this shape: incompatible types: X cannot be converted to Y says that a value of type X was offered where a Y was needed. The compiler caught the mistake without running anything.

The primitive types

Java has eight primitive types. A primitive variable holds the value itself, and the types are named in lower case. Here they are, with their sizes and ranges.

TypeHoldsSizeRangeUse it?
intwhole numbers32 bits-2,147,483,648 to 2,147,483,647Yes, the default for whole numbers
longwhole numbers64 bits-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807Yes, when int is too small
doubledecimal numbers64 bitsup to about 1.8 x 10308, with about 15 to 16 significant digitsYes, the default for decimals
booleantrue or falsenot specified by the languagetwo valuesYes, from lesson 3 onwards it drives decisions
charone character16 bits0 to 65,535Yes
bytewhole numbers8 bits-128 to 127Exists, rarely needed
shortwhole numbers16 bits-32,768 to 32,767Exists, rarely needed
floatdecimal numbers32 bitsup to about 3.4 x 1038, with about 6 to 7 significant digitsExists, rarely needed

A bit is one binary digit, a 0 or a 1. A 32-bit number can take 232 (4,294,967,296) different values, which is why the int range holds about four billion numbers, half of them negative. You do not need to memorise the table. Remember that int goes up to about 2 billion and long to about 9 quintillion. The standard library holds these limits as named constants, such as Byte.MAX_VALUE, so you can print them. (The + joining text and numbers in the program below is explained in the section Joining text and values.)

code/m02-values-and-types/Ranges.java
// The smallest and largest value of each numeric type, taken from the standard library.
// The + between text and a number joins them into one line of text; a later section explains it.
public class Ranges {
    public static void main(String[] args) {
        System.out.println("byte   " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);
        System.out.println("short  " + Short.MIN_VALUE + " to " + Short.MAX_VALUE);
        System.out.println("int    " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
        System.out.println("long   " + Long.MIN_VALUE + " to " + Long.MAX_VALUE);
        System.out.println("float  largest " + Float.MAX_VALUE);
        System.out.println("double largest " + Double.MAX_VALUE);
    }
}
Terminal, in code/m02-values-and-types
> javac Ranges.java
> java Ranges
byte   -128 to 127
short  -32768 to 32767
int    -2147483648 to 2147483647
long   -9223372036854775808 to 9223372036854775807
float  largest 3.4028235E38
double largest 1.7976931348623157E308

The output 1.7976931348623157E308 means 1.7976931348623157 x 10308; the E stands for times ten to the power. The range of char is shown in the section Converting between types, once casts have been introduced.

Which should you reach for? A whole number is an int unless it might exceed about two billion, when it is a long. A measurement or anything with a fractional part is a double. A yes-or-no fact is a boolean, which is not a number but its own kind of value. A single letter, digit or symbol is a char. You may meet byte, short and float in other people's code; they save memory when millions of values are stored, and this course does not use them.

String

Text is so common that Java gives it a type of its own, String. Notice the capital S. String is not one of the eight primitives. It is a class from the standard library, and a String variable works differently from a primitive one in ways that lesson 6 explains. For now you may use it for what you did in lesson 1: store text, print it, and join pieces of it with +. Primitive types are written in lower case, while class names start with a capital.

Literals: writing values in your code

A literal is a value written directly into the source code. You have used string literals since lesson 1. Every type has its own way of writing literals, and the way you write a value decides its type.

LiteralTypeNotes
42intA whole number with no suffix is an int.
5_000_000_000LlongThe suffix L makes it a long. Use the capital: a lower-case l looks like the digit 1.
3.14, 5.0doubleA number with a decimal point is a double, even when the fraction is zero.
3.14ffloatThe suffix f is required.
true, falsebooleanLower case, and no quotes.
'A'charOne character between single quotes.
"A"StringText between double quotes, of any length.
code/m02-values-and-types/Literals.java
// A literal is a value written directly into the source code.
public class Literals {
    public static void main(String[] args) {
        System.out.println(42);                 // int
        System.out.println(5.0);                // double: it has a decimal point
        System.out.println(3.14);               // double
        System.out.println(true);               // boolean
        System.out.println('A');                // char: one character, single quotes
        System.out.println("A");                // String: double quotes
        System.out.println(1_000_000);          // underscores are only for the reader
        System.out.println(3_000_000_000L);     // long: note the L on the end
        float small = 3.14f;                    // float needs an f on the end
        System.out.println(small);
    }
}
Terminal, in code/m02-values-and-types
> javac Literals.java
> java Literals
42
5.0
3.14
true
A
A
1000000
3000000000
3.14
code/m02-values-and-types/broken/CharString.java
public class CharString {
    public static void main(String[] args) {
        char grade = "A";
        System.out.println(grade);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac CharString.java
CharString.java:3: error: incompatible types: String cannot be converted to char
        char grade = "A";
                     ^
1 error

When you see this, check the quotes. Single quotes hold one char; double quotes make a String. The mirror-image mistake, a char offered to a String variable, is rejected in the same way.

Naming variables

A variable's name is chosen by you, within these rules:

code/m02-values-and-types/Names.java
// Legal variable names. The first three follow the convention; the last three are legal but unusual.
public class Names {
    public static void main(String[] args) {
        int age = 30;
        int daysInWeek = 7;
        int score2 = 15;
        int _hidden = 1;
        int $cost = 2;
        int Age = 31;   // a different variable from age

        System.out.println(age);
        System.out.println(Age);
        System.out.println(daysInWeek + score2 + _hidden + $cost);
    }
}
Terminal, in code/m02-values-and-types
> javac Names.java
> java Names
30
31
25

Breaking these rules gives messages that are less helpful than most, because the compiler is trying to read your line as something else:

code/m02-values-and-types/broken/DigitFirst.java
public class DigitFirst {
    public static void main(String[] args) {
        int 1stPlace = 100;
        System.out.println(1stPlace);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac DigitFirst.java
DigitFirst.java:3: error: not a statement
        int 1stPlace = 100;
        ^
DigitFirst.java:3: error: ';' expected
        int 1stPlace = 100;
           ^
DigitFirst.java:4: error: ')' or ',' expected
        System.out.println(1stPlace);
                            ^
DigitFirst.java:4: error: ';' expected
        System.out.println(1stPlace);
                                   ^
4 errors

Java reads int and then sees the number 1 where a name should be. It decides that int by itself is not a statement and that a semicolon is missing, and the damage continues to later lines that use the name. The message does not say names cannot start with a digit. What it does give you is the right line, and the first error is the one to act on. A reserved word used as a name is also an error, and the messages are just as indirect.

Conventions

Legal is not the same as good. Java programmers follow conventions so that anyone can read anyone's code.

The more important convention is to choose names that say what the value means. The compiler treats these two fragments identically. A person reading them does not.

int x = 40;
int y = 60;
int z = x * y;
int hoursWorked = 40;
int hourlyPay = 60;
int weeklyPay = hoursWorked * hourlyPay;

With the second version, multiplying the wrong two variables looks wrong on sight. A good name describes the content, not the type (weeklyPay, not intNumber), and is long enough to be unambiguous.

Declaring, assigning and changing

The statement int total = 7; does two things at once, and they can be written separately. A declaration creates the box by stating a type and a name. An assignment puts a value into a box that already exists.

code/m02-values-and-types/Declare.java
// Declaration creates the box. Assignment puts a value in it.
public class Declare {
    public static void main(String[] args) {
        int total;              // declaration: the box exists, but holds nothing yet
        total = 7;              // assignment: the first value goes in
        System.out.println(total);

        total = 9;              // assignment again: the old value is replaced
        System.out.println(total);

        int doubled = total * 2;    // declaration and assignment in one statement
        System.out.println(doubled);
    }
}
Terminal, in code/m02-values-and-types
> javac Declare.java
> java Declare
7
9
18

You declare a variable once, and you give its type only then. After that you refer to it by name. Writing the type again tries to make a second variable with the same name. Java does not allow that while the first variable still exists, and here it does. (Lesson 3 explains exactly how long a variable exists.)

code/m02-values-and-types/broken/Twice.java
public class Twice {
    public static void main(String[] args) {
        int total = 10;
        int total = 20;
        System.out.println(total);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac Twice.java
Twice.java:4: error: variable total is already defined in method main(String[])
        int total = 20;
            ^
1 error

The fix is to delete the word int on line 4, so the line becomes an assignment.

A variable must have a value before you read it. You may declare a variable without a value, but the compiler then requires that you assign one before the variable is used:

code/m02-values-and-types/broken/NoValue.java
public class NoValue {
    public static void main(String[] args) {
        int total;
        System.out.println(total);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac NoValue.java
NoValue.java:4: error: variable total might not have been initialized
        System.out.println(total);
                           ^
1 error

To initialise a variable is to give it its first value. The rule behind this error is called definite assignment: the compiler must be able to prove that, whatever path the program takes to reach a line, every variable on that line has been given a value. Java would rather stop you at compile time than let you read a box that nothing was ever put into. Right now there is only one path through main, so the rule is easy to meet. When lesson 3 gives your programs choices, you will see the compiler apply it to each path. (Variables declared in other places, which you meet in lesson 8, are given a starting value automatically. A variable declared inside a method is not.)

The message from lesson 1, cannot find symbol, appears when a name has not been declared, and the usual cause is a misspelling. A variable exists only from its declaration downwards, so a name used above its declaration is also unknown.

code/m02-values-and-types/broken/Undeclared.java
public class Undeclared {
    public static void main(String[] args) {
        int total = 10;
        System.out.println(totl);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac Undeclared.java
Undeclared.java:4: error: cannot find symbol
        System.out.println(totl);
                           ^
  symbol:   variable totl
  location: class Undeclared
1 error

The message names the symbol it could not find, which is the quickest clue: compare the name it printed with the one you meant to type.

Arithmetic

An operator is a symbol that performs an operation, and the values it works on are its operands. In 17 + 5 the operator is + and the operands are 17 and 5. A combination of values, variables and operators that produces a value is an expression. Java has five arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division) and % (remainder, also called modulo). The first three behave as you expect. The last two need care.

Integer division and the remainder

When both operands of / are whole numbers, Java performs integer division: the answer is a whole number, and the fractional part is thrown away. For non-negative numbers, % gives what is left over after that division. 7 divided by 2 is 3.5, so 7 / 2 is 3, and 7 is three twos (6) plus 1, so 7 % 2 is 1. The two always fit together: the dividend equals the quotient times the divisor plus the remainder, here 7 = 3 x 2 + 1.

The remainder is more useful than it first looks. For a non-negative n, n % 2 is 0 when n is even and 1 when it is odd, n % 10 is the last digit, and minutes % 60 is the minutes left after taking out whole hours. You will use it in an exercise.

code/m02-values-and-types/Division.java
// Whole-number division throws the fraction away.
public class Division {
    public static void main(String[] args) {
        System.out.println(7 / 2);      // int / int  ->  int
        System.out.println(7 % 2);      // what is left over
        System.out.println(7 / 2.0);    // int / double  ->  double
        System.out.println(7.0 / 2);    // double / int  ->  double
        System.out.println(-7 / 2);     // the fraction is dropped, not rounded down
        System.out.println(-7 % 3);     // the sign follows the left-hand number
        System.out.println(7 % -3);     // the sign of the right-hand number is ignored
    }
}
Terminal, in code/m02-values-and-types
> javac Division.java
> java Division
3
1
3.5
3.5
-3
-1
1

Precedence and parentheses

Operators have precedence, an order in which they are applied. As in school arithmetic, *, / and % bind more tightly than + and -. Operators on the same level are applied from left to right. Parentheses override both.

code/m02-values-and-types/Precedence.java
// Multiplication, division and remainder bind tighter than addition and subtraction.
public class Precedence {
    public static void main(String[] args) {
        System.out.println(2 + 3 * 4);       // 3 * 4 first
        System.out.println((2 + 3) * 4);     // parentheses first
        System.out.println(10 - 4 - 3);      // same level: left to right
        System.out.println(100 / 10 * 5);    // same level: left to right
        System.out.println(100 / (10 * 5));  // parentheses change the answer
    }
}
Terminal, in code/m02-values-and-types
> javac Precedence.java
> java Precedence
14
20
3
50
2

Look at the last two lines. 100 / 10 * 5 is 50, because it means (100 / 10) * 5, working left to right. People often expect 2. When the order matters to a reader, add parentheses even where they are not needed.

The operands decide the type of the result

This is the most important rule in the lesson, and it catches most beginners at least once. The type of an operation comes from its operands. It does not come from the variable that will receive the result. Every operator in an expression is decided separately, working in the order given by precedence, so a double that arrives late cannot repair an int operation that has already happened.

code/m02-values-and-types/Percent.java
// The type of a division comes from its operands, not from the variable that receives it.
public class Percent {
    public static void main(String[] args) {
        int correct = 18;
        int questions = 24;

        double wrong = correct / questions * 100;       // 18 / 24 is 0 in whole numbers
        double right = 100.0 * correct / questions;     // 100.0 makes every later step a double

        System.out.println(wrong);
        System.out.println(right);

        int marks = 7 + 8;
        double halfWrong = marks / 2;                   // divides first, converts afterwards
        double halfRight = marks / 2.0;
        System.out.println(halfWrong);
        System.out.println(halfRight);
    }
}
Terminal, in code/m02-values-and-types
> javac Percent.java
> java Percent
0.0
75.0
7.0
7.5

The variable wrong is a double, yet it holds 0.0. Step by step: correct / questions divides two int values, 18 / 24, which is 0 in whole numbers. Then 0 * 100 is 0. Only at the very end is that 0 stored into a double box, where it becomes 0.0. By then the fraction was already gone. (Storing an int in a double is automatic; the section Converting between types explains why.) marks / 2 goes wrong in the same way and gives 7.0 where 7.5 was wanted.

The fix is to make sure a double is involved before the division happens. 100.0 * correct / questions works left to right: 100.0 * 18 is the double 1800.0, and dividing that by 24 is a double division, giving 75.0. Writing marks / 2.0 fixes the average the same way. You will meet two more places where this rule bites: casts and overflow, later in the lesson.

Dividing by zero

You met 10 / 0 in lesson 1: with whole numbers it throws an exception. With a double there is a value for the answer, and nothing is thrown:

code/m02-values-and-types/ZeroDouble.java
// Floating-point division by zero does not throw. It produces a special value.
public class ZeroDouble {
    public static void main(String[] args) {
        System.out.println(1.0 / 0);
        System.out.println(-1.0 / 0);
        System.out.println(0.0 / 0);
        System.out.println(0.0 / 0 + 5);    // the special value survives later arithmetic
        System.out.println("Still running.");
    }
}
Terminal, in code/m02-values-and-types
> javac ZeroDouble.java
> java ZeroDouble
Infinity
-Infinity
NaN
NaN
Still running.

Infinity and -Infinity are what a positive or negative number divided by zero becomes. NaN means not a number, the result of something with no sensible answer, such as zero divided by zero, and it survives later arithmetic (the fourth line). The program carries on. When NaN or Infinity turns up in output, look for a division by zero earlier in the calculation.

Joining text and values

The + operator has a second job. When at least one operand is a String, + does not add: it concatenates, which means it joins the two into one longer text. The other operand is converted to text first.

code/m02-values-and-types/Joining.java
// + joins text with other values.
public class Joining {
    public static void main(String[] args) {
        String name = "Ada";
        int age = 36;
        double height = 1.7;
        boolean tall = false;

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println(name + " is " + age + " years old.");
        System.out.println("Height: " + height + ", tall: " + tall);
    }
}
Terminal, in code/m02-values-and-types
> javac Joining.java
> java Joining
Name: Ada
Age: 36
Ada is 36 years old.
Height: 1.7, tall: false

The 36 became the two characters 36, the 1.7 became 1.7 and the false became the word false. This is how you label output and build one line from several values.

Each + is decided on its own, from the types of the two values beside it at that moment, and the pluses are worked out from left to right. The result of a concatenation is a String, so the next + joins as well. This is the rule from the section Arithmetic again, applied to +, and it has surprising consequences.

Predict

Write down all six lines before you open the answer. Each + looks at the two things beside it, left to right.

code/m02-values-and-types/Order.java (lines 4 to 9)
System.out.println(1 + 2 + 3);
System.out.println("1" + 2 + 3);
System.out.println(1 + 2 + "3");
System.out.println("1" + (2 + 3));
System.out.println("Total: " + 2 + 3);
System.out.println("Total: " + (2 + 3));
Reveal the answer
Terminal, in code/m02-values-and-types
> javac Order.java
> java Order
6
123
33
15
Total: 23
Total: 5

The output is 6, 123, 33, 15, Total: 23 and Total: 5. Trace the second and third statements.

  • "1" + 2 + 3: first "1" + 2 joins to "12", a String. Then "12" + 3 joins again, giving 123.
  • 1 + 2 + "3": first 1 + 2 are two int values, so they are added, giving 3. Then 3 + "3" joins, giving 33.

The same reading explains "Total: " + 2 + 3: the text is already on the left, so each following number is joined and no addition happens. When you want a sum inside a piece of text, put it in parentheses: "Total: " + (2 + 3). The parentheses are evaluated first, so the 5 exists before it meets the text.

A char adds a further surprise, which the section Converting between types explains. Two char values added together are numbers, not text, so you need a String in the chain to join them:

code/m02-values-and-types/CharJoin.java
// Two chars added together are numbers. Add a char to text and it is joined as a character.
public class CharJoin {
    public static void main(String[] args) {
        System.out.println('A' + 'B');
        System.out.println("" + 'A' + 'B');
        System.out.println("x" + 'A');
    }
}
Terminal, in code/m02-values-and-types
> javac CharJoin.java
> java CharJoin
131
AB
xA

Shorthand for changing a variable

Statements like score = score + 5; are so common that Java has a shorter form for each operator. A compound assignment applies the operator to the variable and its right-hand side and stores the result back.

ShorthandSame as
x += 5;x = x + 5;
x -= 5;x = x - 5;
x *= 5;x = x * 5;
x /= 5;x = x / 5;
x %= 5;x = x % 5;
x++;x = x + 1; (the increment)
x--;x = x - 1; (the decrement)
code/m02-values-and-types/Shorthand.java
// Compound assignment: change a variable using its own current value.
public class Shorthand {
    public static void main(String[] args) {
        int count = 10;
        count += 5;                  // count = count + 5
        System.out.println(count);
        count -= 3;                  // count = count - 3
        System.out.println(count);
        count *= 2;                  // count = count * 2
        System.out.println(count);
        count /= 5;                  // count = count / 5, whole-number division
        System.out.println(count);
        count %= 3;                  // count = count % 3
        System.out.println(count);

        count++;                     // count = count + 1
        System.out.println(count);
        count--;                     // count = count - 1
        count--;
        System.out.println(count);
    }
}
Terminal, in code/m02-values-and-types
> javac Shorthand.java
> java Shorthand
15
12
24
4
1
2
0

The program starts from 10 and prints 15, 12, 24, 4, 1, 2, 0. Note the fourth: count /= 5 divides 24 by 5 using integer division, so it gives 4, not 4.8.

Because + also joins, += works on a String and adds to the end of it. This is how a text is built up a piece at a time:

code/m02-values-and-types/StringAppend.java
// += also works on a String: it joins onto the end.
public class StringAppend {
    public static void main(String[] args) {
        String message = "Hello";
        message += ", world";       // text onto the end of a text
        System.out.println(message);
        message += 2;               // a number onto the end of a text
        System.out.println(message);
    }
}
Terminal, in code/m02-values-and-types
> javac StringAppend.java
> java StringAppend
Hello, world
Hello, world2

message += 2; means message = message + 2;. The variable is a String, so the + joins, and the number 2 is converted to the text 2.

Prefix and postfix

++ and -- can also appear inside a larger expression, and then it matters on which side of the variable they stand. Written after (a++, postfix), the expression's value is the variable's old value and the variable goes up afterwards. Written before (++a, prefix), the variable goes up first and the expression's value is the new value.

code/m02-values-and-types/PrefixPostfix.java
// Inside a larger expression, ++ before or after the variable gives different results.
public class PrefixPostfix {
    public static void main(String[] args) {
        int a = 5;
        int b = a++;     // postfix: b gets the OLD value of a, then a goes up
        System.out.println(a);
        System.out.println(b);

        int c = ++a;     // prefix: a goes up first, then c gets the NEW value
        System.out.println(a);
        System.out.println(c);
    }
}
Terminal, in code/m02-values-and-types
> javac PrefixPostfix.java
> java PrefixPostfix
6
5
7
7

After int b = a++;, a is 6 but b is 5. After int c = ++a;, both are 7. Code like this is easy to misread, so use ++ and -- only as complete statements on their own (count++;), where the two forms do the same thing.

Converting between types

A value sometimes has to move from one type to another. Java splits these conversions into two kinds, according to whether information can be lost.

Widening: automatic

Moving a value into a type that has room for it is called widening, and Java does it for you. An int becomes a double without any special syntax. A long can hold every int, and a double can hold every int with room to spare. Automatic conversions follow the arrows of this chain (a caveat about float comes after the example):

byte short int long float double char An arrow means: converts automatically, with no cast. There is no arrow to or from boolean.
code/m02-values-and-types/Widening.java
// Widening: a value moves into a bigger type automatically.
public class Widening {
    public static void main(String[] args) {
        int whole = 7;
        double wide = whole;        // fine: every int fits in a double
        System.out.println(wide);

        long big = whole;           // fine: every int fits in a long
        System.out.println(big);

        double mixed = whole + 0.5; // int + double: the int is widened for the sum
        System.out.println(mixed);
    }
}
Terminal, in code/m02-values-and-types
> javac Widening.java
> java Widening
7.0
7
7.5

The 7 became 7.0 on its way into the double. In whole + 0.5 the same thing happens to the int operand before the addition, which is why mixing int and double gives a double.

Narrowing: you must say so

Moving a value into a type that may not have room for it is narrowing. The compiler will not do it silently, because information could be lost:

code/m02-values-and-types/broken/Lossy.java
public class Lossy {
    public static void main(String[] args) {
        double price = 3.99;
        int whole = price;
        System.out.println(whole);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac Lossy.java
Lossy.java:4: error: incompatible types: possible lossy conversion from double to int
        int whole = price;
                    ^
1 error

Read possible lossy conversion literally: converting this way could lose something (here, the .99), so you have to confirm that you know. You confirm with a cast: the target type written in parentheses in front of the value.

code/m02-values-and-types/Cast.java
// Narrowing needs a cast: you tell the compiler you accept the loss.
public class Cast {
    public static void main(String[] args) {
        double price = 3.99;
        int whole = (int) price;
        System.out.println(whole);

        double debt = -3.99;
        System.out.println((int) debt);

        int sum = 7;
        int count = 2;
        System.out.println(sum / count);
        System.out.println((double) sum / count);       // cast first, then divide
        System.out.println((double) (sum / count));     // divide first, then cast: too late
    }
}
Terminal, in code/m02-values-and-types
> javac Cast.java
> java Cast
3
-3
3
3.5
3.0

A cast does not change the variable it is applied to. It produces a converted copy of the value, which you may store or use. It also applies only to the single value right after it, so it binds more tightly than * and /:

code/m02-values-and-types/CastPrecedence.java
// A cast applies to the one value right after it, not to everything that follows.
public class CastPrecedence {
    public static void main(String[] args) {
        double price = 3.99;
        System.out.println((int) price * 2);
        System.out.println((int) (price * 2));
    }
}
Terminal, in code/m02-values-and-types
> javac CastPrecedence.java
> java CastPrecedence
6
7

In (int) price * 2, the 3.99 is truncated to 3 first, and then doubled: 6. In (int) (price * 2), the parentheses make 7.98 first, and the truncation gives 7. When you mean calculate, then cut, put the calculation in parentheses.

Predict

What does each of the five statements print? Decide for each result whether it is a whole number, a number with a decimal point, or a letter.

code/m02-values-and-types/predict/Casts.java (lines 3 to 7)
System.out.println((int) 9.99);
System.out.println((int) 9.99 + 0.5);
System.out.println((int) (9.99 + 0.5));
System.out.println('a' + 2);
System.out.println((char) ('a' + 2));
Reveal the answer
Terminal, in code/m02-values-and-types/predict
> javac Casts.java
> java Casts
9
9.5
10
99
c

The output is 9, 9.5, 10, 99 and c. In the second statement the cast binds tightly, so it is 9 + 0.5, which is 9.5. Only the third statement casts the whole sum, giving 10. The fourth is 'a' + 2, arithmetic on a char, which produces a number: 99. The fifth casts that number back to a char, which prints as the letter c. The next part explains why.

The char type is a number underneath

A computer stores everything as numbers, so characters are stored as numbers too. Every character has a numeric code, and a char variable holds that code. The codes for the letters, digits and punctuation on an English keyboard come from a standard called ASCII, which Unicode, the modern standard that Java uses, contains unchanged.

code/m02-values-and-types/CharCodes.java
// A few character codes, and the range of char.
public class CharCodes {
    public static void main(String[] args) {
        System.out.println("A " + (int) 'A');
        System.out.println("Z " + (int) 'Z');
        System.out.println("a " + (int) 'a');
        System.out.println("z " + (int) 'z');
        System.out.println("0 " + (int) '0');
        System.out.println("9 " + (int) '9');
        System.out.println("space " + (int) ' ');
        System.out.println("char runs from " + (int) Character.MIN_VALUE + " to " + (int) Character.MAX_VALUE);
    }
}
Terminal, in code/m02-values-and-types
> javac CharCodes.java
> java CharCodes
A 65
Z 90
a 97
z 122
0 48
9 57
space 32
char runs from 0 to 65535

The capital letters run from 65 to 90 with no gaps, the lower-case letters from 97 to 122, and the digit characters from 48 to 57. A lower-case letter is 32 more than its capital. (Character.MIN_VALUE and Character.MAX_VALUE are library constants like Integer.MAX_VALUE.) The last line also settles the range of char in the table in the section Types. What you do with the codes follows from the rule that arithmetic on a char produces an int.

code/m02-values-and-types/CharMath.java
// A char is a number underneath. Arithmetic on it gives an int.
public class CharMath {
    public static void main(String[] args) {
        char letter = 'A';
        System.out.println(letter);                 // printed as a character
        System.out.println(letter + 1);             // int arithmetic: a number
        System.out.println((char) (letter + 1));    // cast back: a character
        System.out.println((int) 'a');              // the number behind 'a'
        System.out.println((char) 66);              // the character behind 66

        letter++;                                   // ++ keeps the type: still a char
        System.out.println(letter);

        char digit = '7';
        System.out.println(digit - '0');            // from the character 7 to the number 7
    }
}
Terminal, in code/m02-values-and-types
> javac CharMath.java
> java CharMath
A
66
B
97
B
B
7

The limits of numbers

Computers store numbers in a fixed amount of memory, and a fixed amount means a limit. There are two limits to know about, and both can give wrong answers without any message.

Integer overflow

An int has 32 bits, so it can hold only a fixed range of numbers. What happens when a calculation goes past the largest one? Nothing is reported. The value overflows: it wraps around to the other end of the range, like a car's mileometer rolling over from 99999 to 00000, except that an int rolls from the largest value to the most negative one.

code/m02-values-and-types/Overflow.java
// An int that goes past its largest value wraps round to the smallest.
public class Overflow {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Long.MAX_VALUE);

        int biggest = Integer.MAX_VALUE;
        System.out.println(biggest + 1);

        long roomy = biggest;
        System.out.println(roomy + 1);

        System.out.println(1_000_000 * 1_000_000);
        System.out.println(1_000_000L * 1_000_000);
    }
}
Terminal, in code/m02-values-and-types
> javac Overflow.java
> java Overflow
2147483647
-2147483648
9223372036854775807
-2147483648
2147483648
-727379968
1000000000000

Integer.MAX_VALUE and Integer.MIN_VALUE are named constants from the standard library holding the largest and smallest int; Long.MAX_VALUE is the largest long. (Integer is a class like System, and MAX_VALUE is a value stored inside it; lesson 11 explains how.) Adding 1 to the largest int gives -2147483648, the smallest, with no error and no exception. A calculation does not need to look large to do this: a million times a million is a trillion, far beyond the range, and 1_000_000 * 1_000_000 prints -727379968.

The remedy is a bigger type. A long holds numbers up to about 9.2 x 1018. In the program above, roomy + 1 gives 2147483648 because roomy is a long, and the literal 1_000_000L makes the multiplication a long calculation that comes out right.

Switching to long too late

This is the rule from the section Arithmetic once more: you must make the calculation a long calculation before the overflow happens.

Predict

Predict all three lines. Which of them show the correct value of two billion doubled, and why do the others not?

code/m02-values-and-types/WrapTrap.java (lines 4 to 9)
int big = 2_000_000_000;
long tooLate = big + big;
long inTime = (long) big + big;
System.out.println(tooLate);
System.out.println(inTime);
System.out.println((int) 3_000_000_000L);
Reveal the answer
Terminal, in code/m02-values-and-types
> javac WrapTrap.java
> java WrapTrap
-294967296
4000000000
-1294967296
  • long tooLate = big + big; adds two int values. The sum overflows, giving -294967296, and only then is that wrong answer widened to a long.
  • (long) big + big casts the first operand, so the addition is a long addition and the answer is 4000000000.
  • The last statement narrows a long that does not fit. (int) 3_000_000_000L compiles, because you asked for it, and gives -1294967296: a cast from long to int keeps the low 32 bits and discards the rest. The cast silences the compiler but does not make the value safe. Use one only when you know the value fits.

Decimals are approximate

The second limit is the precision of double. Look at what ten pence plus twenty pence comes to:

code/m02-values-and-types/Imprecise.java
// double stores most decimal fractions only approximately.
public class Imprecise {
    public static void main(String[] args) {
        System.out.println(0.1 + 0.2);      // ten pence plus twenty pence?
        System.out.println(1.1 + 2.2);
        System.out.println(1.0 / 3);
        System.out.println(0.5 + 0.25);     // sums of halves and quarters are exact
        System.out.println(2.50);           // the trailing zero is not printed
        System.out.println(1_000_000.0);
        System.out.println(10_000_000.0);   // from ten million up, a different notation
        System.out.println(12345678.9);
    }
}
Terminal, in code/m02-values-and-types
> javac Imprecise.java
> java Imprecise
0.30000000000000004
3.3000000000000003
0.3333333333333333
0.75
2.5
1000000.0
1.0E7
1.23456789E7

The first line is not 0.3. You know that a third cannot be written exactly with decimal digits: 0.3333... goes on for ever, and any finite number of 3s is slightly wrong. A double stores its number in binary, using powers of two, and in binary a tenth is in the same position as a third is in decimal: it never ends. The double holds the nearest value it can, a minute amount away from 0.1, and the small errors show up when you add. println prints enough digits to tell the stored value apart from its neighbours, which is why you see the ...04. Numbers made of halves and quarters, such as 0.5 + 0.25, are stored exactly. This way of storing a number, in a fixed number of binary digits with the point free to move, is called floating-point, and the small errors it causes are what the goals at the top of this lesson call floating-point imprecision.

Three smaller points from the same output. A trailing zero is not printed: 2.50 appears as 2.5. A double of ten million or more is printed in scientific notation: 10_000_000.0 prints as 1.0E7, meaning 1.0 x 107, while 1000000.0 still prints in full. And 12345678.9 prints as 1.23456789E7, the same value written another way.

What this means for money

The consequence is that double is the wrong tool for money, where an answer that is a hundredth of a penny out can be unacceptable. The library has a class called BigDecimal for this, which you do not need yet. What you can do now is keep money as a whole number of the smallest unit, pence, in an int or long, which is exact. Convert to pounds and pence only when printing, with the / and % you now know:

code/m02-values-and-types/Pence.java
// Money in whole pence: every amount is an exact integer.
public class Pence {
    public static void main(String[] args) {
        int priceInPence = 1999;       // 19.99
        int quantity = 3;
        int totalInPence = priceInPence * quantity;

        System.out.println(totalInPence);
        System.out.println(totalInPence / 100);     // whole pounds
        System.out.println(totalInPence % 100);     // pence left over
    }
}
Terminal, in code/m02-values-and-types
> javac Pence.java
> java Pence
5997
59
97

Three items at 19.99 cost 5997 pence: 59 pounds and 97 pence. Be careful, though: totalInPence % 100 prints 5, not 05, when the pence part is five. Handling that is part of exercise 4.

Constants

Some values should not change while the program runs: the number of minutes in an hour, a tax rate, the number of seconds in a day. A constant is a variable that is given a value once and cannot be reassigned. You make one by putting the keyword final in front of the declaration.

code/m02-values-and-types/Constants.java
// A constant: a variable that may be given a value once and never changed.
public class Constants {
    public static void main(String[] args) {
        final int SECONDS_PER_MINUTE = 60;
        final int MINUTES_PER_HOUR = 60;

        int hours = 3;
        int seconds = hours * MINUTES_PER_HOUR * SECONDS_PER_MINUTE;
        System.out.println(seconds);
    }
}
Terminal, in code/m02-values-and-types
> javac Constants.java
> java Constants
10800

By convention a constant is written in UPPER_SNAKE_CASE: all capitals, with underscores between the words. The compiler enforces the promise:

code/m02-values-and-types/broken/ReassignFinal.java
public class ReassignFinal {
    public static void main(String[] args) {
        final int MINUTES_PER_HOUR = 60;
        MINUTES_PER_HOUR = 100;
        System.out.println(MINUTES_PER_HOUR);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac ReassignFinal.java
ReassignFinal.java:4: error: cannot assign a value to final variable MINUTES_PER_HOUR
        MINUTES_PER_HOUR = 100;
        ^
1 error

Why bother? Compare hours * 60 * 60 with hours * MINUTES_PER_HOUR * SECONDS_PER_MINUTE. A bare number such as 60 or 0.2 in the middle of a calculation is called a magic number, because a reader has to guess where it came from and what it stands for. A named constant explains itself, appears in one place so that you change it in one place, and cannot be changed by accident. Lesson 11 covers final fully, including constants shared between different parts of a program.

You may see: var

Since Java 10 you may write var in place of a variable's type, and the compiler works the type out from the value on the right.

code/m02-values-and-types/Var.java
// var lets the compiler work out the type from the value on the right.
public class Var {
    public static void main(String[] args) {
        var count = 10;         // the compiler decides: int
        var price = 2.5;        // double
        var name = "Ada";       // String
        count = count + 1;
        System.out.println(count);
        System.out.println(price);
        System.out.println(name);
    }
}
Terminal, in code/m02-values-and-types
> javac Var.java
> java Var
11
2.5
Ada

Here count is an int, price a double and name a String. The variable still has one fixed type. It has not become any type:

code/m02-values-and-types/broken/VarChange.java
public class VarChange {
    public static void main(String[] args) {
        var count = 10;
        count = "ten";
        System.out.println(count);
    }
}
Terminal, in code/m02-values-and-types/broken
> javac VarChange.java
VarChange.java:4: error: incompatible types: String cannot be converted to int
        count = "ten";
                ^
1 error

You will see var in other people's code. This course writes the type out in full throughout Part 1, because the type is what you are learning to see.

A guide to this lesson's mistakes

This table collects the messages from the sections above, with the usual cause. The first nine are compiler messages and the tenth is a run-time exception.

What you seeUsually meansSection
incompatible types: X cannot be converted to Y (for example String cannot be converted to int, or to char)A value of the wrong type for the variable. Other pairs give the same shape, such as int cannot be converted to boolean. Check quotes and types.Types, Literals
incompatible types: possible lossy conversion from double to intA narrowing conversion with no castConverting
not a statement then ';' expected, on a declarationOften an illegal name, such as one that starts with a digitNaming
integer number too largeA whole-number literal beyond the int range, missing its LLiterals
variable total might not have been initializedReading a variable before giving it a valueDeclaring
variable total is already defined in method main(String[])The type was written a second time on a name that already existsDeclaring
cannot find symbol with symbol: variable totlA misspelt name, or a name used before its declarationDeclaring
unexpected type, required variable, found valueSomething that is not a variable on the left of =Variables
cannot assign a value to final variableReassigning a constantConstants
java.lang.ArithmeticException: / by zeroInteger division by zero at run time (lesson 1)Arithmetic
No message; the answer is wrongInteger division, a cast in the wrong place, + joining instead of adding, an overflow, or double imprecisionSections Arithmetic to Limits

The last row deserves attention. The compiler catches mistakes of grammar and type, and the mistakes in this lesson that cost most time produce no message: the program runs and prints a wrong number. The defence is to work out one or two answers by hand and compare them with what the program prints.

Exercises

Each exercise has a folder waiting in work/m02-values-and-types/ in your course kit. Compile and run from the terminal, inside the exercise's folder. Open a hint only after a real attempt. Several exercises ask for a written answer in a file: these count as much as the code.

warm-up

Exercise 2.1 · Minutes to days, hours and minutes

Work in work/m02-values-and-types/ex1-minutes-converter/ in your course kit

Write Duration.java (class Duration) that breaks a number of minutes into days, hours and minutes. Declare int totalMinutes = 4000; in main and print these two lines:

Required output of java Duration
4000 minutes = 2 days, 18 hours, 40 minutes
As decimal hours: 66.66666666666667

Constraints:

  • The numbers 60 and 24 may be typed only once each, as named constants declared with final.
  • Use only / and % to split the total. The words are plural even for 1 (1 days), because you cannot yet choose between words.
  • The second line is the total divided by 60 with a decimal answer. Do not type the answer yourself.

When it works, change the 4000 to 59, then 1440, then 1441. Work out by hand what each should print, then check that the program agrees. Leave the file at 4000.

Hint 1

Think about a clock. How many whole days fit into the total? What is left over after taking those days out? Then ask the same two questions of the leftover, with hours.

Hint 2

For the second line, remember the rule in the section Arithmetic: if both operands are int, the fraction is gone before any double is involved.

To check it, run python check.py m02 ex1 in your course kit folder.

warm-up

Exercise 2.2 · Predict the type

Work in work/m02-values-and-types/ex2-predict-the-type/ in your course kit

Your folder contains Worksheet.java, a complete program that prints the value of twelve expressions, and predictions.md, a table to fill in. Do not run the program yet. Here it is:

work/m02-values-and-types/ex2-predict-the-type/Worksheet.java
// Worksheet.java - do not edit, and do not run it until predictions.md is filled in.
// Each line prints the value of one expression from the worksheet.
public class Worksheet {
    public static void main(String[] args) {
        System.out.println("1) " + (9 / 2));
        System.out.println("2) " + (9 % 2));
        System.out.println("3) " + (9 / 2.0));
        System.out.println("4) " + (9 / 2 * 2.0));
        System.out.println("5) " + (2 + 3 * 4 - 1));
        System.out.println("6) " + (10 - 2 - 3));
        System.out.println("7) " + ("7" + 1 + 2));
        System.out.println("8) " + (7 + 1 + "2"));
        System.out.println("9) " + ('a' + 1));
        System.out.println("10) " + (char) ('a' + 1));
        System.out.println("11) " + (int) 2.99 * 2);
        System.out.println("12) " + (int) (2.99 * 2));
    }
}

Each output line has the form 3) value, where the number is the row of the table. For each of the twelve expressions, write in predictions.md the type of the expression (int, double, char or String) and the value as Java will print it. Work on paper first if you like, but follow the rules from the lesson rather than guessing.

Then compile and run Worksheet and compare. For every row you got wrong, add two or three sentences below the table: which rule you applied, which rule Java applied instead, and what you will look for next time. If all twelve are right, choose the two you were least sure of and explain how you decided.

Hint 1

For each expression, write the order the operators are applied in, with brackets, before you work out any value. Left to right within a level, and parentheses first.

Hint 2

The type of each operation is decided by its operands. Ask at every operator: are both operands whole numbers? Is either one text? Has a cast already happened?

To check it, run python check.py m02 ex2 in your course kit folder.

core

Exercise 2.3 · Bug hunt: the report

Work in work/m02-values-and-types/ex3-report-bugs/ in your course kit

Your folder contains Report.java, which has six mistakes, and bug-log.md. The comments in the program say what each part is meant to calculate. Two mistakes stop it compiling; the other four compile and give wrong answers. Fix the program until it prints these six lines:

Output of java Report when all six are fixed
Total: 62 out of 80
Average: 15.5
Percentage: 77.5
Whole percentage: 77
Doubled average, whole part: 31
Maths and science together: 31
  • Fix one mistake at a time and run again each time.
  • For every mistake, add an entry to bug-log.md: the compiler message or the wrong output, the line, what was actually wrong in your own words, and what you changed.
  • Do not change the starting values of the variables, except that bonus may be given the value its comment describes. Do not type any answer into the program in place of a calculation.

At the end of bug-log.md, answer the question given there: why could the compiler not report four of the six, and how could you have caught each one without reading the source code?

Hint 1

For the wrong outputs, calculate the expected answer by hand first (62 divided by 4 is easy). The gap between your answer and the program's is the clue to which rule is involved.

Hint 2

Five rules are in play: when a variable counts as having a value, when a narrowing conversion needs a cast, what / does to two int values (this one accounts for two bugs), where a cast binds, and what + does once text is on its left. Match each mistake to one of them.

To check it, run python check.py m02 ex3 in your course kit folder.

core

Exercise 2.4 · Shop receipt in whole pence

Work in work/m02-values-and-types/ex4-receipt/ in your course kit

Write Receipt.java (class Receipt) that prints a receipt for a stationery shop. All money is held as whole pence in int variables. Use these starting values:

  • 3 notebooks at 249 pence each; 2 pens at 130 pence each; 1 ruler at 89 pence; 1 tape dispenser at 503 pence.
  • VAT is 20 per cent of the subtotal, declared as final int VAT_PERCENT = 20;. The VAT is rounded down to a whole penny.

The program must print:

Required output of java Receipt
Notebooks x 3: 7.47
Pens x 2: 2.60
Ruler x 1: 0.89
Tape x 1: 5.03
Subtotal: 15.99
VAT (20%): 3.19
Total: 19.18

Constraints:

  • No double or float anywhere. Every amount is an int number of pence.
  • Every amount is printed as pounds, a point, and two digits of pence, using only /, % and +. Note 5.03 above: a naive attempt prints 5.03 as 5.3.
  • The VAT percentage must appear in the output through the constant, not typed again.

Test your program by changing a price so that some amount has a pence part such as 05, and check the digits come out right. Then change it back.

Hint 1

Print the pounds, then a point, then the tens digit of the pence, then the units digit. What are 503 / 100, 503 % 100 and 503 % 10? How could you get the tens digit?

Hint 2

In text + a % 100 / 10 + b, the % and / are done before either +, left to right. The joining then starts at the first +, where the text is on the left, so every number after it is joined as digits. Write the expression for one amount, test it, then repeat it for the others.

Hint 3

For the VAT, think about what whole-number division does to a fraction and when you want that to happen: before or after multiplying by the percentage. Try both orders on a subtotal of 1599 and compare them with the required 3.19.

To check it, run python check.py m02 ex4 in your course kit folder.

stretch

Exercise 2.5 · Shifting letters

Work in work/m02-values-and-types/ex5-letter-shift/ in your course kit

Write Shift.java (class Shift) that moves each letter of a three-letter word a number of places along the alphabet, wrapping round from z to a, and then moves them back. Declare these variables in main:

char first = 'z';
char second = 'o';
char third = 'o';
int shift = 3;

The output must be:

Required output of java Shift
zoo shifted by 3: crr
crr shifted back by 3: zoo

Constraints:

  • The letters are lower-case a to z, and the shift is from 0 to 25. A shift of 3 moves z to c.
  • Do not type any character code such as 97 or 122. Use the characters 'a' and so on, and a final constant for the 26 letters of the alphabet.
  • The second line must be computed from the shifted letters, undoing the shift. It must not just print the original letters again.
  • The program must still be right if you change the three letters or the shift. Try 'a', 'b', 'c' with a shift of 25, and check by hand.

Answer the two questions in answers.md: why your code contains a cast and what would go wrong without it; and what the % step does, showing it step by step for z, and what the program would print for z if the % step were missing.

Hint 1

A letter's position in the alphabet is its code minus the code of 'a', a number from 0 to 25. Shift the number, wrap it, and turn it back into a letter by adding 'a' again and casting.

Hint 2

Going backwards, subtracting the shift from a small position can make it negative, and % of a negative number is negative (see the section Arithmetic). Add a whole alphabet before taking the remainder so the number is never negative.

To check it, run python check.py m02 ex5 in your course kit folder.

stretch

Exercise 2.6 · A lifetime of seconds

Work in work/m02-values-and-types/ex6-lifetime-seconds/ in your course kit

Write Lifetime.java (class Lifetime) that investigates overflow. Declare int years = 80; in main and ignore leap years (a year is 365 days). The program must print four lines:

Required output of java Lifetime
int: -1772087296
long variable, int arithmetic: -1772087296
long arithmetic: 2522880000
Whole years that fit in an int: 68
  • Line 1: the number of seconds in years years, calculated and stored entirely in int.
  • Line 2: the same calculation, written the same way, but stored in a long variable.
  • Line 3: the correct answer, calculated in long arithmetic. Do not type the number yourself, and do not use a different formula for it.
  • Line 4: how many whole years of seconds fit in an int, calculated from Integer.MAX_VALUE and the seconds in one year, not typed.

Then fill in explanation.md: why line 1 is negative and what the negative number is made of, why line 2 repeats it despite the long variable, what you changed for line 3, and what line 4 means.

Hint 1

In the expression years * 365 * 24 * 60 * 60, which multiplication is done first, and what type are its operands? When would a long variable on the left have any say?

Hint 2

To explain the negative number, find the true answer and subtract the number of values an int can hold (4,294,967,296, from the section Types).

To check it, run python check.py m02 ex6 in your course kit folder.

Summary

Words introduced in this lesson

TermMeaning
VariableA named place in memory that holds one value.
TypeThe kind of value a variable may hold, fixed when it is declared.
Statically typedTypes are fixed and checked by the compiler before the program runs.
Primitive typeOne of the eight basic types whose variables hold the value itself.
DeclarationCreating a variable by stating its type and name.
AssignmentStoring a value in an existing variable with =.
InitialiseGive a variable its first value.
Definite assignmentThe rule that the compiler must be able to prove a variable has a value before it is read.
LiteralA value written directly in source code, such as 42 or 'A'.
Reserved wordA word the language uses itself, which cannot be a name.
camelCaseThe naming convention for variables: totalPrice.
Operator, operandA symbol that performs an operation, and a value it works on.
ExpressionValues, variables and operators that together produce a value.
Integer divisionDivision of two whole numbers, giving a whole number with the fraction dropped.
Remainder (modulo)The amount left over after whole-number division, written %.
PrecedenceThe order in which operators are applied.
ConcatenationJoining text with +.
Compound assignmentAn operator such as += that changes a variable using its own value.
Increment, decrement++ and --: add 1 to, or subtract 1 from, a variable.
Widening, narrowingConverting to a type with more room (automatic) or less room (needs a cast).
CastA type in parentheses before a value, converting it to that type.
TruncationDropping the fractional part of a number without rounding.
OverflowA whole-number result outside the type's range, which wraps round silently.
ConstantA variable declared final, which cannot be reassigned.
Magic numberA bare number in code whose meaning the reader has to guess.