Object-Oriented Programming with Java · Lecture Notes
Chapter 1.1: Computers
Every line of Java you write ends up as numbers that a processor understands. Why can an int never exceed 2,147,483,647? Why does "😀".length() return 2, and why is 0.1 + 0.2 not exactly 0.3? The answers all lie in that translation. These notes build the computer layer by layer. First, electrical signals become bits and bits become numbers. Numbers stand for letters and text, and sequences of numbers stand for images, sound and video. Last comes the stored-program idea, in which the instructions themselves sit in memory as numbers, and the von Neumann architecture that puts it into hardware. At every layer we show what the idea looks like in Java, using short programs whose output we trace step by step.
Learning outcomes
- Hardware
- Explain the roles of the processor, memory, disk and bus, and trace step by step how a program runs on the processor through the fetch–decode–execute cycle.
- Numbers
- Convert numbers between binary, octal, hexadecimal and decimal; add binary numbers; and compute with negative numbers in two's complement.
- Text
- Explain the difference between ASCII, Unicode and UTF-8, and show how a string is represented in memory as numbers.
- Connection to Java
- Explain the limits of
byteandintand overflow through two's complement; work with number bases in Java; relatecharandStringlength to UTF-16; and show how assembly instructions map to machine code.
1.1.1Computer basics
A computer is a machine that carries out given instructions very fast and without error, one after another. Each instruction is very simple on its own: add two numbers, read a number from memory, write the result to memory, jump to another instruction if a condition holds. What makes a computer powerful is that it can do these simple steps billions of times a second. The classes, objects and methods of an object-oriented program are in the end reduced to these same simple steps, so starting Java from the machine itself explains a good deal of behavior you will meet later.
1.1.1.1Basic components
A computer contains a great many components, but three stand out from a programmer's point of view. They are connected by paths that carry data between them.
- Processor (CPU, Central Processing Unit): regarded as the computer's "brain". It performs all arithmetic and logical computation: addition, subtraction, comparing two numbers and logic operations on bits are its job.
- Memory (RAM, Random Access Memory): temporarily stores the running program and its data. "Random access" means any cell can be reached in the same amount of time, without stepping through the others in order. The capacity and access speed of memory directly affect the speed of the computer.
- Disk (HDD or SSD): stores data permanently. When the power is cut, everything in RAM is erased, while the files on disk stay where they are. An HDD uses spinning magnetic platters, whereas an SSD uses semiconductor memory chips with no moving parts; both are much larger and much slower than RAM.
A kitchen analogy makes the relationship among the three easy to remember. The cook is the processor. The counter is RAM: small, but right within the cook's reach. The pantry is the disk: very large, but far away. The cook does not cook directly from the pantry. First the cook carries the needed ingredients from the pantry to the counter and works there. Likewise, when a program is started, its code and data are first loaded from disk into memory, and the processor works only with the instructions and data in memory. If the counter fills up, the cook keeps walking to the pantry and the cooking slows down; a computer slows down for the same reason when RAM runs short.
From an electronics point of view, the difference between RAM and disk comes from how information is held. The widely used dynamic RAM (DRAM) stores each bit as a charge on a tiny capacitor. That charge leaks away by itself, so it must be refreshed many times a second, and the information is lost when the power goes off. Flash memory in an SSD, by contrast, traps the charge inside an insulated gate, and the charge stays there for years even without power. This is why RAM is called volatile and disk non-volatile memory.
1.1.1.2How a computer works, and programming
How a computer works can be summed up in three basic steps. Instructions are sent to the processor. The processor carries them out in order. The results are presented to the user or to other software. Printing text on the screen, saving a file and sending a network packet are all products of this cycle.
Programming is the process of writing instructions for a computer, in a form it can understand, so that it performs a desired task. The whole body of instructions written is called a program.
The shortest Java program is one that writes a single line to the screen. It contains just one instruction: "print to the screen".
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Hello, World!The boilerplate of the program can look crowded at first. The line public class HelloWorld defines a class; in Java all code lives inside a class, and the file must be named HelloWorld.java. The main method is where the program starts; when the Java Virtual Machine (JVM) runs a program, it calls this method first. The real work is in the line System.out.println(...), which writes the quoted string to standard output and ends the line.
The processor does not know the word println. Instructions written in a language like Java are run by translating them into machine code, which the processor understands. In Java this translation has two stages. First the javac compiler translates the source code into an intermediate code called bytecode. Then the JVM interprets this code, or compiles its frequently executed parts into the machine code of that processor. In the end, even drawing a letter on the screen amounts to the processor moving numbers from one place to another. The rest of these notes explains what those numbers represent and how.
1.1.1.3A computer in layers
It is hard to grasp how a computer works all at once. It is easier to build the computer up layer by layer, each layer resting on the one below and using the building blocks it provides.
- First, electrical signals are turned into numbers.
- Numbers represent letters, and letters represent text.
- Sequences of numbers store structured information such as images, sound and video.
- Instructions are also stored in memory as numbers.
- The von Neumann architecture brings it all together.
This order also determines the sections of these notes. At each layer we ask the same question: how is a concept from the layer above expressed with the numbers below it? The answers also explain why Java's primitive types (byte, int, char, double) are designed the way they are.
1.1.2Binary numbers
1.1.2.1From electrical signal to bit
The basic job of a computer is to process electrical signals according to fixed rules. These rules give rise to functions such as addition, comparison and copying. A signal carries no meaning on its own. Only when we associate signals with numbers and symbols that people understand can the computer present us with meaningful information.
Computers process signals using a binary (base 2) representation. If the voltage on a wire is above a certain threshold, it is read as 1; if below, as 0. All operations are built on this binary foundation.
A bit (binary digit) is the smallest unit of information, able to take only the value 0 or 1. A group of eight bits is called a byte.
The values 0 and 1 go by different names depending on context. Table 1.1.1 shows the most common ones. In logic, 0 is false and 1 is true; on a switch, 0 is off and 1 is on; in a circuit, 0 is low voltage and 1 is high voltage. They are all different readings of the same duality.
| 0 | 1 |
|---|---|
False (false) | True (true) |
| Off | On |
| Low voltage | High voltage |
Why two states rather than ten? On a real wire the voltage never sits exactly at the intended value. Heat, interference from neighboring wires and ripple in the power supply add noise to the signal. It is easy to tell whether a voltage is "present or absent" despite noise, because a wide safety margin can be left between the two states. Dividing the same voltage range into ten equal levels, on the other hand, narrows every level. A little noise pushes the signal into the neighboring level, and a digit sent as 7 is read as 6. This is why logic gates in electronics work with two states, and digital circuits are extremely reliable thanks to that safety margin.
Memory and file sizes are measured in bytes. Prefixes are used in two different ways. In the International System of Units (SI), 1 kilobyte (KB) is 1000 bytes. In the binary prefixes based on powers of two, 1 kibibyte (KiB) is 1024 bytes. The gap grows as the units get larger: 1 GB = 109 bytes, while 1 GiB = 230 = 1,073,741,824 bytes. A disk labeled 1 TB shows up as roughly 931 "GB" in the operating system because the operating system actually computes in GiB.
1.1.2.2Place value
The decimal system we use every day is a positional system. In the number 603, the 6 is worth 600 because it sits in the hundreds place. The same digit carries a different value in a different position. The binary system works on the same principle, except that the base is 2 instead of 10.
An integer is written as a sum of powers of 2, where each power is either not used (0) or used once (1). Four consecutive powers, 20, 21, 22, 23, represent all integers from 0 to 15. The number 13 is written as follows:
1310 = 1·23 + 1·22 + 0·21 + 1·20 = 8 + 4 + 0 + 1 = 11012
The small digit at the lower right of the number, the subscript, shows the base. 11012 is read "one one zero one, base two", not "one thousand one hundred one". Numbers without a subscript are taken to be decimal. The same rule holds in the other bases (Table 1.1.2).
| Base | Example |
|---|---|
| Decimal (10) | 60310 = 6·102 + 0·101 + 3·100 |
| Octal (8) | 2078 = 2·82 + 0·81 + 7·80 = 13510 |
| Hexadecimal (16) | FF16 = 15·161 + 15·160 = 25510 |
Converting a binary number to decimal is therefore easy: add up the weights of the places that hold 1. In 101101102, the 1s are in places 7, 5, 4, 2 and 1 (the rightmost place is place 0). The value is 128 + 32 + 16 + 4 + 2 = 182. Knowing the weights by heart speeds this up: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024. Programmers know this sequence like a multiplication table.
1.1.2.3Any base, and bit limits
The idea of place value generalizes to every base. If the base is b ≥ 2, each digit takes one of the values 0, 1, …, b − 1. In binary the digits are 0–1, in octal 0–7, and in hexadecimal 0–9 and A–F, where A = 10, B = 11, C = 12, D = 13, E = 14 and F = 15. To count up to 15 with a single digit, six new symbols are needed.
With base b ≥ 2 and d digits, every integer from 0 to bd − 1 can be written, and no other integer can.
Each digit can take b different values, so d digits give bd different digit strings in total. The smallest string is 00…0 = 0. In the largest string every digit is b − 1; adding 1 to it carries all the way and opens a new digit on the far left, giving bd. So the largest value is bd − 1. There are bd numbers in between, and each corresponds to a different string. ∎
In decimal, three digits write 0–999: 103 − 1 = 999. In binary, the largest unsigned value with d bits is 2d − 1 (Table 1.1.3). A 64-bit computer can count, unsigned, up to 264 − 1 = 18,446,744,073,709,551,615.
| Bits | Largest (2d − 1) |
|---|---|
| 4 | 15 |
| 8 | 255 |
| 16 | 65.535 |
| 32 | 4.294.967.295 |
Java's integer types, however, are signed: half of the values the bits can represent are set aside for negative numbers. That is why the 8-bit byte goes up to 127, not 255. The following program prints the largest value of the four integer types.
System.out.println(Byte.MAX_VALUE); // 8 bit
System.out.println(Short.MAX_VALUE); // 16 bit
System.out.println(Integer.MAX_VALUE); // 32 bit
System.out.println(Long.MAX_VALUE); // 64 bit
// all 64 bits 1, read unsigned:
System.out.println(Long.toUnsignedString(-1L));127
32767
2147483647
9223372036854775807
18446744073709551615Each constant is about half the unsigned limit in the table. Byte.MAX_VALUE = 127 = 27 − 1, Short.MAX_VALUE = 32,767 = 215 − 1, Integer.MAX_VALUE = 2,147,483,647 = 231 − 1 and Long.MAX_VALUE = 263 − 1. One bit is evidently used to tell negative numbers apart. All 64 bits of -1L are 1. When Long.toUnsignedString reads those bits as unsigned, it returns 264 − 1. The same bits can be −1 or a number larger than 18 quintillion, depending on how they are interpreted. This duality returns when we get to negative numbers.
In Java, int is 32 bits on every platform and long is 64 bits on every platform. In C, the size of int can vary with the compiler and the processor. Java's fixed sizes ensure that the same program gives the same result on every machine.
1.1.2.4Decimal to binary: repeated division by 2
The most systematic way to convert a decimal number to binary is to divide it by 2 repeatedly. At each division the remainder is 0 or 1, and this remainder is the rightmost bit of the number not yet written down. Stop when the quotient is 0 and read the remainders from bottom to top.
To see why the method works, it is enough to look at how a number is written in binary. If 13 = 11012, then 13 = 2·6 + 1. The remainder 1 is the rightmost bit, and the quotient 6 is the number formed by the remaining bits, namely 1102. Applying the same step to 6 produces the next bit. Each division "snips off" one bit and shifts the number one bit to the right. The following program implements this method in Java.
public static void main(String[] args) {
int n = 13;
String bits = "";
while (n > 0) {
int rem = n % 2;
System.out.println(n + " % 2 = " + rem);
bits = rem + bits;
n = n / 2;
}
System.out.println("Result: " + bits);
}Four points in the code matter. n % 2 is the remainder (modulo) operation and yields the last bit. n / 2 is integer division, because it is between two ints: the fraction is discarded, so 13 / 2 = 6. In the line bits = rem + bits, rem is an int and bits is a String. A number added to a string is converted to a string, and the two strings are concatenated. Because each new bit is added to the front of the string, the bits accumulate in the right order and the remainders do not need to be reversed separately. The loop ends when n reaches 0. Table 1.1.4 shows each iteration for 13.
| Iteration | Condition | rem | Line printed | bits | New n |
|---|---|---|---|---|---|
| 1 | 13 > 0 true | 1 | 13 % 2 = 1 | "1" | 6 |
| 2 | 6 > 0 true | 0 | 6 % 2 = 0 | "01" | 3 |
| 3 | 3 > 0 true | 1 | 3 % 2 = 1 | "101" | 1 |
| 4 | 1 > 0 true | 1 | 1 % 2 = 1 | "1101" | 0 |
| — | 0 > 0 false | The loop ends; Result: 1101 is printed. | |||
13 % 2 = 1
6 % 2 = 0
3 % 2 = 1
1 % 2 = 1
Result: 1101The loop ran four times because the binary form of 13 has four bits. In general, for n ≥ 1 the number of iterations is ⌊log2 n⌋ + 1: the number is halved each time, and this is how many halvings it takes to fall below 1. The number 1000 is converted in 10 iterations, and one billion in 30.
The code has one limitation: for n = 0 the loop never runs and bits stays empty, so only Result: is printed. For negative numbers too, the condition is false on the first iteration. A real program needs a separate case for 0. Java's built-in Integer.toBinaryString method handles these details itself.
How is 45 written as an 8-bit binary number? The chain of divisions is: 45 / 2 = 22 remainder 1; 22 / 2 = 11 remainder 0; 11 / 2 = 5 remainder 1; 5 / 2 = 2 remainder 1; 2 / 2 = 1 remainder 0; 1 / 2 = 0 remainder 1. Reading the remainders from bottom to top gives 101101. To fill out eight bits, two zeros are added on the left: 00101101. Check: 32 + 8 + 4 + 1 = 45.
The same result can be reached by subtracting powers. The largest power that fits in 45 is 32, leaving 13. The largest power that fits in 13 is 8, leaving 5. Then 4, leaving 1; then 1, leaving 0. The powers used are 32, 8, 4 and 1; those places get a 1 and the others a 0.
1.1.2.5Octal and hexadecimal
Binary numbers are long. Writing a 32-bit int with thirty-two digits is both tiring and error-prone. Programmers therefore use octal and hexadecimal to write binary numbers more compactly. These two bases are chosen because 8 and 16 are powers of 2: 8 = 23 and 16 = 24.
This relationship makes conversion a matter of regrouping rather than arithmetic. One hexadecimal digit corresponds to exactly four bits, and one octal digit to exactly three. To convert from binary to hexadecimal, split the bits into groups of four starting from the right and convert each group to a single hexadecimal digit. For octal the groups have three bits.
Let us convert 101111102 to hexadecimal and octal.
For hexadecimal, groups of four: 1011 1110. 1011 = 8 + 2 + 1 = 11 = B, and 1110 = 8 + 4 + 2 = 14 = E. The result is BE16.
For octal, groups of three from the right: 10 111 110. The incomplete leftmost group is padded with a zero to give 010. 010 = 2, 111 = 7, 110 = 6; the result is 2768.
Check: 11·16 + 14 = 190 and 2·64 + 7·8 + 6 = 190. The decimal value of the binary number is also 128 + 32 + 16 + 8 + 4 + 2 = 190.
Today hexadecimal is far more common than octal. Since a byte is eight bits, it fits exactly two hexadecimal digits: 00–FF. Memory addresses, color codes (#FF0000 is red), the raw contents of files and Unicode code points are all written in hexadecimal. Octal survives in only a few places, such as Unix file permissions (chmod 755).
1.1.2.6Base conversions in Java
Java provides ready-made methods for converting between bases, and prefixes for writing integer literals in different bases. The following program uses both.
System.out.println(Integer.toBinaryString(13)); // binary
System.out.println(Integer.toOctalString(135)); // octal
System.out.println(Integer.toHexString(255)); // hex
System.out.println(Integer.parseInt("1101", 2)); // 2 → 10
System.out.println(Integer.parseInt("207", 8)); // 8 → 10
System.out.println(0b1101 + " " + 0207 + " " + 0xFF);1101
207
ff
13
135
13 135 255The first three lines convert an int value to a string. Integer.toBinaryString(13) gives the binary form, toOctalString(135) the octal form and toHexString(255) the hexadecimal form. Note that toHexString uses lowercase letters: the output is ff, not FF. Integer.parseInt does the conversion in the opposite direction. Its second argument says which base the string is written in. parseInt("1101", 2) reads the string as binary and returns 13. The returned value is now an ordinary int; the base is a property of the notation, not of the number.
The last line shows how to write literals directly in different bases in source code. These notations are called literals, and their prefixes are summarized in Table 1.1.5.
| Prefix | Base | Example | Note |
|---|---|---|---|
0b ya da 0B | Binary | 0b1101 = 13 | Introduced in Java 7. |
0 | Octal | 0207 = 135 | 010 is 8, not ten. |
0x ya da 0X | Hexadecimal | 0xFF = 255 | Common in color and byte values. |
| (none) | Decimal | 135 | Must not start with 0. |
Prefixes change only the notation. 0b1101, 015, 0xD and 13 produce the same int value and sit in memory as the same 32 bits. Long literals can be grouped with underscores: 1_000_000 or 0b1011_1110. The compiler ignores the underscores; readability improves.
Putting a leading zero in front of a number to align it. int x = 010; compiles, but since the literal is read as octal, x is 8, not 10. int y = 08; does not compile at all: there is no digit 8 in octal, and javac reports "error: ';' expected". The message looks unrelated at first glance; the compiler takes 0 as a complete literal and then sees the following 8 as an unexpected token.
1.1.2.7Binary addition
Addition follows the same principles in whatever base is used. Numbers are written one under the other by place value and added from right to left. A value that does not fit in one place is passed to the next place as a carry. In decimal, when 7 + 8 = 15, we write 5 and carry 1. In binary, when 1 + 1 = 2 = 102, we write 0 and carry 1. If three 1s are added together with the carry, 3 = 112: write 1 and carry 1.
All cases of binary addition fit in a four-line table: 0 + 0 = 0, 0 + 1 = 1, 1 + 0 = 1, 1 + 1 = 10. Once the carry is included, three bits are added in each column and the result stays between 0 and 3. In electronics this job is done by a full adder circuit: three bits go in, and a sum bit and a carry bit come out. Chaining eight full adders gives an 8-bit adder.
Let us add 57 and 28 as 8-bit binary numbers. 57 = 001110012 and 28 = 000111002. Addition starts at the rightmost column (Table 1.1.6).
| Column | Bit of 57 | Bit of 28 | Carry in | Sum | Written | Carry out |
|---|---|---|---|---|---|---|
| 1 | 1 | 0 | 0 | 1 | 1 | 0 |
| 2 | 0 | 0 | 0 | 0 | 0 | 0 |
| 3 | 0 | 1 | 0 | 1 | 1 | 0 |
| 4 | 1 | 1 | 0 | 2 = 102 | 0 | 1 |
| 5 | 1 | 1 | 1 | 3 = 112 | 1 | 1 |
| 6 | 1 | 0 | 1 | 2 = 102 | 0 | 1 |
| 7 | 0 | 0 | 1 | 1 | 1 | 0 |
| 8 | 0 | 0 | 0 | 0 | 0 | 0 |
The result 010101012 = 64 + 16 + 4 + 1 = 85 agrees with 57 + 28 = 85. No carry came out of the eighth column, so the result fit in 8 bits. Had the sum exceeded 255, a carry would have spilled out of the eighth column and the 8-bit result would have been wrong. This is the first example of overflow, which we examine in detail together with negative numbers.
1.1.3Negative numbers and overflow
1.1.3.1Two's complement
So far only zero and positive integers have been written. The first idea for negative numbers is to reserve the leftmost bit for the sign: 0 for positive, 1 for negative. This representation is called sign-magnitude, and it looks natural on paper. But it has two flaws. Zero gets two separate representations (+0 and −0). More importantly, the adder circuit would have to behave differently depending on the signs. This is why computers use another method.
In two's complement representation, the negative of a positive number is found like this: all bits of the number are flipped (0 ↔ 1), and then 1 is added to the result. The intermediate result obtained by only flipping the bits is called the one's complement.
In this representation the leftmost bit behaves like a sign bit: if it is 0 the number is positive, if 1 it is negative. The range that 8 bits can represent is −128 … 127. In general, with n bits the range is −2n−1 … 2n−1 − 1. There is one more number on the negative side, because zero takes up a place on the positive side.
Let us find −3 on an 8-bit computer. The number 3 is 00000011.
- All bits are flipped:
00000011→11111100(the one's complement). - 1 is added:
11111100+ 1 =11111101.
The result 11111101 is the 8-bit two's complement representation of −3.
The same operation works in the opposite direction. To find the absolute value of a negative number, the bits are again flipped and 1 is added: 11111101 → 00000010 → 00000011 = 3. The operation is its own inverse; applying it twice returns to the start.
The 8-bit representation of −20 is found as follows. 20 = 16 + 4 = 000101002. Flip the bits: 11101011. Add 1: 11101100. As a check, reading this bit pattern as unsigned gives 128 + 64 + 32 + 8 + 4 = 236, and 236 = 256 − 20. This equality is no coincidence; the next section explains why.
1.1.3.2Why two's complement works
The main advantage of two's complement is that the adder circuit works unchanged with negative numbers too. Consider the sum 3 + (−3):
00000011 + 11111101 = 1 00000000
The result is nine bits. Since the computer holds only eight bits, the ninth bit on the far left is discarded, leaving exactly 00000000 = 0. The adder circuit never knows the sign of the number; it adds the bits as usual and gives the right result. Subtraction does not need a separate circuit either: a − b is computed as a + (−b). Inverting gates and one adder do both addition and subtraction.
There is a second way to look at the same representation, and it is the shortest way to convert a signed number to decimal. In 8-bit two's complement, the weight of the leftmost bit is not +128 but −128. The weights of the other bits do not change. So if the leftmost bit is 1, the number is necessarily negative: the other seven bits can add at most 127 and cannot get past −128.
What is the bit pattern 10110110 as an unsigned and as a signed number?
Read as unsigned, all weights are positive: 128 + 32 + 16 + 4 + 2 = 182.
Read as signed, the weight of the leftmost bit is −128: −128 + 32 + 16 + 4 + 2 = −74. The same result follows from 182 − 256 = −74. When the leftmost bit is 1, the signed value is always 28 = 256 less than the unsigned value, because that bit contributes −128 instead of +128, a difference of 256.
This observation gives a general rule. In an n-bit two's complement number, −x is stored as 2n − x when read as unsigned. That is why −20 appears as 236 and −3 as 253. It helps to picture the numbers arranged like a clock face: the positives run clockwise from 0 up to 127, then come −128 and the negatives up to −1. One step after −1 you are back at 0.
1.1.3.3Two's complement in Java
All of Java's integer types (byte, short, int, long) use two's complement. This is stated explicitly in the Java language specification and is the same on every platform. The following program tests the same rule in Java.
int n = 3;
int neg = ~n + 1; // invert, add 1
System.out.println(neg);
byte b = (byte) 0b11111101;
System.out.println(b);
System.out.println(Integer.toBinaryString(-3));
System.out.println(Byte.MIN_VALUE + " .. "
+ Byte.MAX_VALUE);-3
-3
11111111111111111111111111111101
-128 .. 127The ~ operator flips all bits of an integer; it is the bitwise NOT operator. ~n + 1 is exactly the two's complement rule, and the result is −3. In Java, -x and ~x + 1 give the same value for every integer.
In the second part, the literal 0b11111101 is converted to a byte. To Java this literal is an int with the value 253. Since 253 does not fit in the range of byte, an explicit cast is needed: (byte). The cast keeps only the rightmost 8 bits; these are 11111101, which read as signed is −3.
Integer.toBinaryString(-3) prints all thirty-two bits: thirty 1s at the start and 01 at the end. The representation does not change when it is widened to 32 bits; the bits added on the left are copies of the sign bit. This rule is called sign extension. A positive number is extended to the left with zeros and a negative number with ones, and the value is preserved. The last line prints the limits of the byte type: -128 .. 127.
That Java's byte is signed can sometimes be surprising. Raw bytes read from the network or a file are often thought of as lying between 0 and 255. In Java, however, a byte with the value 200 appears as −56. To read a byte as unsigned, use the expression b & 0xFF: the & operation clears the ones that sign extension brought in and gives back 200. The Byte.toUnsignedInt(b) method does the same job.
1.1.3.4Overflow
Overflow is the situation in which the result of an operation does not fit in the range of the type. In Java, integer overflow raises no error: the result wraps around "like a clock" and continues from the other end of the range.
byte b = 127;
b++;
System.out.println(b);
int m = Integer.MAX_VALUE;
System.out.println(m + 1);
System.out.println(Math.addExact(m, 1));-128
-2147483648
Exception in thread "main" java.lang.ArithmeticException: integer overflow
at java.base/java.lang.Math.addExact(Math.java:911)
at Overflow.main(Overflow.java:7)In the first three lines, b is 127, and after being incremented by 1 it should become 128. Adding 1 to 127 = 01111111 gives 10000000. Read as signed, this bit pattern is −128. The adder worked correctly; only the result moved into the negative region because of the carry into the sign bit. On the clock face, one step forward from 127 lands on −128. The same happens with Integer.MAX_VALUE + 1, which gives −231 = −2,147,483,648.
The danger of overflow is that it is silent. The program does not crash or warn; it simply keeps running with a wrong number. If a bank balance or a counter overflows, the error shows up much later, somewhere else. That is why Java offers the Math.addExact, Math.subtractExact and Math.multiplyExact methods for checked operations. When these methods see that the result does not fit, they throw an ArithmeticException and the program stops at that point. The call on the last line therefore prints no number; the exception message reports the place and cause of the error. The at lines in the output show which method calls the exception was thrown through. Here the code was placed in the main method of a class named Overflow and run, and the line numbers refer to that file.
One way to prevent overflow is to use a wider type. The product of two ints fits in a long, but the multiplication itself must be done as a long. Writing long x = 100000 * 100000; does not help: the right-hand side is a product of two ints, computed first in 32 bits, where it overflows; only then is the overflowed result assigned to a long. The right way is to make one of the factors a long: 100000L * 100000. The L suffix on the literal makes it a long, and the whole product is carried out in 64 bits.
What is 01101101 + 00110110, and how is the result read as an 8-bit signed byte?
In decimal, 109 + 54 = 163. Adding the bits gives 10100011: 128 + 32 + 2 + 1 = 163. No carry spilled into a ninth bit; read as unsigned, the result is correct. Read as signed, however, the leftmost bit is 1 and the value is 163 − 256 = −93. The sum of two positive numbers came out negative. This is exactly the sign of overflow in signed addition: two numbers of the same sign are added and the result has a different sign. In Java, the expression (byte) (0b01101101 + 0b00110110) gives −93.
1.1.4Fractional numbers: floating point
1.1.4.1Fraction and exponent
With a limited number of digits, only a limited number of values can be represented. A 32-bit int counts up to about ±2 billion. That is not even enough to square the speed of light (about 3·108 m/s). And it cannot write the charge of an electron (about 1.6·10−19 coulomb) at all. Engineering calculations need both very large and very small numbers.
The solution is the idea behind scientific notation. A number is split into two parts: the mantissa (also called the significand), which carries the significant digits, and the exponent, which fixes the position of the decimal point. The parts are stored separately. Suppose 31415901 is written in a field of eight digits. Let the first six digits (314159) stand for the mantissa and the last two digits (01) for the power of 10, that is, 101. If the mantissa is read as 0.314159, the number is 0.314159 × 101 = 3.14159.
double type: 1 sign bit, 11 exponent bits and 52 fraction bits.The name of this representation comes from here: floating point. As the exponent changes, the decimal point floats. If the same mantissa is multiplied by 103, we get 0.314159 × 103 = 314.159. The digits are the same; only the position of the point has moved. In this way, a limited number of digits can write both very large and very small numbers. The price is that every number is stored with only as many significant digits as fit in the mantissa, that is, approximately.
1.1.4.2IEEE 754 and Java's float and double
Computers apply the same idea in binary. The rules are set by the IEEE 754 standard, which almost all processors follow today. Java has two floating-point types: float is 32 bits and double is 64 bits.
| Type | Sign | Exponent | Fraction | Significant decimal digits | Largest value |
|---|---|---|---|---|---|
float | 1 | 8 | 23 | about 7 | ≈ 3,4·1038 |
double | 1 | 11 | 52 | about 15–16 | ≈ 1,8·10308 |
In binary floating point, a number is put into the form (−1)sign × 1.fraction2 × 2exponent. Since every nonzero binary number can be shifted so that it starts with "1.…", the leading 1 is not stored; the fraction field holds only the bits after the point. The exponent is written as a non-negative number by adding a constant, called the bias; in float this constant is 127, and in double it is 1023.
The float representation of −6.5 is found in five steps.
- The sign is negative: the sign bit is 1.
- 6.5 = 4 + 2 + 0.5. In binary it is written 110.12 (the weight of the first place after the point is 2−1 = 0.5).
- The point is shifted two places to the left: 110.12 = 1.1012 × 22.
- The exponent is 2; adding 127 gives 129 =
10000001, which is what is stored. - The fraction is
101followed by 20 zeros, with the leading 1 dropped.
The result is 1 10000001 10100000000000000000000. In Java, Integer.toBinaryString(Float.floatToIntBits(-6.5f)) prints exactly these 32 bits.
Numbers like −6.5 are written exactly in binary, because 0.5 is a power of two. 0.1 is not. Just as 1/3 goes on forever in decimal as 0.3333…, 0.1 repeats forever in binary as 0.000110011001100…2. Because the fraction field is finite, it is cut off somewhere and rounded. The 0.1 in memory is really a number very close to 0.1, but not equal to it.
1.1.4.3Rounding error and comparison
The best-known consequence of rounding is that in Java 0.1 + 0.2 comes out as 0.30000000000000004. The small errors in the stored values of 0.1 and 0.2 add up, and the result is not equal to the stored value of 0.3. So the expression 0.1 + 0.2 == 0.3 gives false. This is not a Java bug; the same result appears in C, Python and JavaScript, because they all use the same IEEE 754 hardware.
For this reason floating-point numbers are not compared with ==. Instead, we check whether the difference of the two numbers is small enough:
double a = 0.1 + 0.2;
double b = 0.3;
System.out.println(a == b); // false
System.out.println(Math.abs(a - b) < 1e-9); // trueThe bound 10−9 here is called the tolerance, and it is chosen according to the scale of the problem. For a voltage measured in volts, 10−9 is a very small difference; but for a capacitance on the order of 10−12 farad it is very large. For values such as money, which must be correct to the last kuruş, double is never used. Either amounts are stored as a long number of kuruş, or Java's BigDecimal class, which computes in decimal, is used.
Tying a loop to an equality condition on a floating-point counter: for (double x = 0; x != 1.0; x += 0.1). It looks as if x will be 1.0 after ten steps, but because of accumulated rounding errors x becomes 0.9999999999999999 and is never equal to 1.0; the loop runs forever. Counters should be integers, or the condition should be written as an inequality such as x < 1.0.
1.1.5Letters and strings
1.1.5.1Character encoding and ASCII
A computer works only with numbers. For it to process text, each letter must be assigned a number. Which letter is shown by which number is an arbitrary choice, but everyone has to make the same choice. Otherwise the number written as "A" on one computer would be read as a different letter on another.
A character encoding is the rule that determines which numbers characters are stored as, and with which byte sequences in memory.
The oldest and most influential encoding is ASCII (American Standard Code for Information Interchange). ASCII was published in 1963 by the American standards body ASA (today's ANSI). It represents uppercase and lowercase English letters, digits, punctuation marks and some special characters with numbers.
ASCII is a 7-bit code and defines 27 = 128 characters (0–127). Codes 0–31 and 127 are control characters, which do not appear on screen. They were originally designed to control printers and teletype machines: return to the start of the line, move down one line, ring the bell. Codes 32–126 are the printable characters. Table 1.1.8 shows a few important codes.
| Character | Decimal | Binary |
|---|---|---|
'A' | 65 | 1000001 |
'a' | 97 | 1100001 |
'0' | 48 | 0110000 |
| space | 32 | 0100000 |
newline \n | 10 | 0001010 |
The layout in the table was chosen deliberately. Letters are arranged in consecutive codes in alphabetical order: 'A' = 65, 'B' = 66, …, 'Z' = 90. This turns comparing letters into comparing numbers. A lowercase letter is 32 more than its uppercase letter: 'a' = 97 = 65 + 32. In binary this difference is a single bit, the 25 place. 'A' = 1000001 and 'a' = 1100001. Converting between uppercase and lowercase is just switching one bit on or off. Digits are also arranged starting from 48; the numeric value of a digit character is found with c - '0': '7' - '0' = 55 − 48 = 7.
In Java, char is a numeric type and can take part in arithmetic. The expression (char) ('a' - 32) gives 'A'. This closeness can be surprising at times: the line System.out.println('a' + 'b'); prints 195, not ab. The sum of two chars is an int: 97 + 98 = 195. If the same line is written as "" + 'a' + 'b', 'a' is first added to the empty string, and since the result is a string, 'b' is appended too, giving ab. In Java the + operator works from left to right and turns into concatenation as soon as one of the operands is a string.
Seven bits leave one of the eight bits of a byte unused. Eight-bit extensions use this bit to place extra letters in 128–255, reaching 256 symbols. ISO 8859-9 (Latin-5) and Windows-1254 are encodings of this kind for Turkish; they place the letters ğ, ş, ı and İ in this upper half. But trouble arose once every language defined its own upper half. The same value 253 was the letter ı in one table and ý in another. When a Turkish text was opened with the wrong encoding, the letters looked garbled. A single 8-bit table cannot serve all the world's languages; Chinese and Japanese have thousands of characters.
1.1.5.2The ASCII table
When the printable ASCII characters are laid out in a table of 16 columns, their codes are easy to read (Table 1.1.9). The code of a character is the sum of its row header and its column header. For example, 'J' is in row 64 and column 10: 64 + 10 = 74.
| + | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 32 | SP | ! | " | # | $ | % | & | ' | ( | ) | * | + | , | - | . | / |
| 48 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | : | ; | < | = | > | ? |
| 64 | @ | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O |
| 80 | P | Q | R | S | T | U | V | W | X | Y | Z | [ | \ | ] | ^ | _ |
| 96 | ` | a | b | c | d | e | f | g | h | i | j | k | l | m | n | o |
| 112 | p | q | r | s | t | u | v | w | x | y | z | { | | | } | ~ | DEL |
The last cell of the table, DEL (127), is a control character. Three of the control characters between 0 and 31 are still used every day: 9 tab (\t), 10 newline (\n) and 13 carriage return (\r). In Windows text files the end of a line is marked with the pair \r\n, and in Linux and macOS with \n alone. This difference is often why a file looks right on one system and like a single line on another. The complete 0–255 range, and a search by character or code, are on the ASCII Table page.
1.1.5.3Unicode
The confusion created by country-specific code tables gave rise to the idea of a single table for all languages.
Unicode is the standard that gives a number to every letter, symbol and mark of all the world's writing systems. This number is called a code point and is written in hexadecimal with the prefix U+: U+0041 = A, U+00E7 = ç.
Unicode has been developed by the Unicode Consortium since 1991. Its international counterpart, the ISO/IEC 10646 standard, is kept in step with it. The first version was 16 bits, and it was thought that 65,536 characters would be enough. When historical scripts, mathematical symbols and all the Chinese-Japanese-Korean ideographs were added, that space proved too small. The code space was extended to U+10FFFF, giving 1,114,112 code points; today more than 150,000 of them have been assigned characters.
The first 128 code points of Unicode are identical to ASCII: U+0041 is 65 in both ASCII and Unicode. The first 256 code points also coincide with Latin-1 (ISO 8859-1), the table used for Western European languages; so ç is 231 in both Latin-1 and Unicode. The Turkish-specific ğ, ş and ı are not in Latin-1 and lie above 256 (Table 1.1.10).
| Character | Code point | Decimal | UTF-8 bytes |
|---|---|---|---|
| A | U+0041 | 65 | 41 |
| ç | U+00E7 | 231 | C3 A7 |
| ğ | U+011F | 287 | C4 9F |
| € | U+20AC | 8364 | E2 82 AC |
| 😀 | U+1F600 | 128512 | F0 9F 98 80 |
A code point is a number; it does not say how to store it in memory. The simplest way is to store every character in a fixed 32 bits. This encoding is called UTF-32. But in an English text every letter has a 7-bit ASCII code, and reserving 32 bits wastes three quarters of the space. This is why variable-length UTF (Unicode Transformation Format) encodings were defined.
1.1.5.4UTF-8
UTF-8 stores a code point in a length that varies from 1 to 4 bytes. Frequently used characters take few bytes and rare ones take many. ASCII characters are a single byte, and that byte is the same as the ASCII code. So a pure ASCII text is already a valid UTF-8 text with no change; UTF-8 is backward compatible with ASCII. Today the great majority of web pages are encoded in UTF-8.
A UTF-8 reader can tell how many bytes a character will take from the bits at the start of the first byte. Table 1.1.11 gives the patterns. The bits of the code point are placed in order into the positions marked x.
| Code point range | Byte pattern | Number of bytes | Bits carried |
|---|---|---|---|
| U+0000–U+007F | 0xxxxxxx | 1 | 7 |
| U+0080–U+07FF | 110xxxxx 10xxxxxx | 2 | 11 |
| U+0800–U+FFFF | 1110xxxx 10xxxxxx 10xxxxxx | 3 | 16 |
| U+10000–U+10FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | 4 | 21 |
The design of the patterns is clever. A byte starting with 0 is an ASCII character on its own. A byte starting with 110, 1110 or 11110 is the first byte of a character, and the number of leading 1s gives the total number of bytes. A byte starting with 10 is always a continuation byte. Even if a reader starts reading in the middle of a text, it can skip the continuation bytes and find the start of the next character.
The UTF-8 encoding of the character ç is found as follows. The code point is U+00E7 = 231, and since it lies in the range U+0080–U+07FF it uses two bytes. 231 is written in 11 bits as 00011 100111. The first five bits go into the 110xxxxx pattern of the first byte, and the last six bits into the 10xxxxxx pattern of the second byte:
110 00011 = C3 10 100111 = A7
The result is C3 A7. In the same way, € (U+20AC = 0010 000010 101100) fits into three bytes: 1110 0010 = E2, 10 000010 = 82, 10 101100 = AC.
How many bytes a string takes in UTF-8 can be seen with the getBytes method. For the code to compile, the line import java.nio.charset.StandardCharsets; must be added at the top of the file.
String word = "çikolata";
System.out.println(word.length());
System.out.println(word.getBytes(
StandardCharsets.UTF_8).length);8
9"çikolata" ("chocolate") has eight characters, and length() gives 8. In UTF-8, ç takes two bytes and each of the other seven letters one byte: 2 + 7 = 9. This is why the size of a file in bytes is not the same as the number of characters in it.
Encoding determines not only length but also readability. A text must be read with the same encoding it was written in. "ç" written in UTF-8 is two bytes (C3 A7). If these two bytes are read with the Windows-1254 table, each is taken as a separate character and "ç" appears on screen. This is the problem in most files where Turkish characters look garbled. When reading and writing files in Java, always stating the encoding explicitly, for example by passing StandardCharsets.UTF_8, prevents this error.
1.1.5.5char, UTF-16 and emoji in Java
When Java was designed, Unicode was still 16 bits. Java's char type was therefore chosen to be 16 bits, on the assumption that every character would fit in a single char. When Unicode grew, this assumption broke. Today a char is not a character but a UTF-16 code unit. The UTF-16 encoding writes characters up to U+FFFF as a single 16-bit unit; ş = 01 5F, € = 20 AC. Larger code points are written with two units. This pair is called a surrogate pair.
Most everyday text does not feel this distinction, because the common characters of Turkish, Russian, Arabic and Chinese all lie below U+FFFF. The difference shows up most with emoji. Emoji are symbols that quickly convey feelings, expressions and objects, and computers handle them as text, not as images. Their standard is set by the Unicode Consortium, and each emoji is a unique code point: 😀 = U+1F600. The code is the same on every device, so a sent emoji is read with the same meaning on the other end. Its drawing, the glyph, may look different depending on the font and the vendor.
Some emoji are combinations of several code points. The family emoji 👨👩👧 consists of five code points: man, ZWJ, woman, ZWJ, girl. ZWJ (zero width joiner) is U+200D; it is invisible on screen and only asks that the neighboring emoji be drawn as a single glyph. A system that does not recognize this joiner shows three separate faces.
String face = "😀";
System.out.println(face.length());
System.out.println(
face.codePointCount(0, face.length()));
String family = "👨👩👧";
System.out.println(family.length());2
1
8The string 😀 has a length() of 2, because U+1F600 is a surrogate pair of two chars: \uD83D and \uDE00. codePointCount, on the other hand, counts code points and gives 1. In the family emoji, the three person emoji take two chars each and the two ZWJs one char each: 3·2 + 2·1 = 8. Although a single symbol appears on screen, length() is 8 and the number of code points is 5. In UTF-8 this emoji takes 3·4 + 2·3 = 18 bytes.
The conclusion of this section for Java is this: String stores characters in UTF-16, and length() is the number of chars, not the "number of characters". In Turkish text the two are almost always the same. In text with emoji, mathematical symbols or historical scripts they differ. To iterate over the characters of such text one by one, use codePoints() or codePointAt instead of charAt. Since Java 9, String stores strings containing only Latin-1 characters internally with one byte per character. This is a memory optimization; length() and charAt() continue to work in UTF-16 units in every case.
Taking the length() of a string to be the number of symbols shown on screen or the number of bytes. "😀".length() is 2, not 1; "ağaç".length() is 4, while the same string takes 6 bytes in UTF-8. If you need to check whether it fits in a database field or a network packet, look at the number of encoded bytes; if you need to compute a length to show the user, look at code points.
1.1.5.6Code trace: the character codes of a string
A string sits in memory as two parts: an array in which the characters are laid out as numbers, and the length of that array. The length is kept separately; this is how it is known where the text ends. The following program prints the code of each character of the string "çikolata".
String word = "çikolata";
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
System.out.print((int) ch + " ");
}
System.out.println();
System.out.println("Length: " + word.length());The loop starts at i = 0 and runs as long as i < word.length() is true. charAt(i) returns the char at position i. The cast (int) ch prints the numeric code of the character rather than the character itself; without the cast, the letter itself would be printed. Unlike println, print does not end the line, so the codes are lined up side by side. The println() after the loop ends the line. Table 1.1.12 shows each iteration.
i | Condition i < 8 | ch | (int) ch | Explanation |
|---|---|---|---|---|
| 0 | true | 'ç' | 231 | U+00E7; not in ASCII |
| 1 | true | 'i' | 105 | |
| 2 | true | 'k' | 107 | |
| 3 | true | 'o' | 111 | |
| 4 | true | 'l' | 108 | |
| 5 | true | 'a' | 97 | |
| 6 | true | 't' | 116 | |
| 7 | true | 'a' | 97 | same code as the 'a' at position 5 |
| 8 | false | The loop ends; a line break and Length: 8 are printed. | ||
231 105 107 111 108 97 116 97
Length: 8"çikolata" in memory: on the left the length (8), on the right the characters with indices 0–7 and their codes below them.All the codes other than ç are values from the ASCII table. 231 is the Unicode code point of ç (U+00E7). The same value is 231 in the Latin-1 and Turkish ISO 8859-9 tables too, so the program prints the same number whichever table one has in mind. The expression (int) ch gives the code point, not the UTF-8 bytes. The UTF-8 form of ç is the bytes C3 A7, but in Java memory ç sits as a single 16-bit char with the value 231.
1.1.6Structured information
1.1.6.1Images, sound and video
Just as numbers represent letters and letters represent text, sequences of numbers can represent far more complex information. Whatever a file stores, to the computer it is a sequence of bytes. The meaning of the sequence comes from the rules that the programs writing and reading it follow, that is, from the file format. Most of our interaction with computers rests on these rules, which let us see sequences of numbers as images, sound or video.
- Image. An image consists of tiny dots arranged in rows and columns, called pixels. Each pixel is three numbers giving the amounts of red, green and blue light, and each number lies between 0 and 255. This triple is called RGB (red, green, blue). A blue pixel is (0, 0, 255), a white pixel is (255, 255, 255) and a black pixel is (0, 0, 0). Each color component fits in one byte, and a pixel takes three bytes. The color code
#FF0000used on the web is the hexadecimal notation of these three bytes: FF red, 00 green, 00 blue. - Sound. Sound is the change of air pressure over time. A microphone turns this change into a voltage. An analog-to-digital converter (ADC) measures the voltage at regular intervals and records each measurement as a number. This process is called sampling. CD quality takes 44,100 samples per second, and each sample is a 16-bit number. The choice of sampling rate is not arbitrary. The human ear hears up to about 20 kHz. To sample a signal without losing information, one must also measure faster than twice its highest frequency.
- Video. A video is a sequence of images shown at 24 or 30 frames per second. At this rate the eye perceives the images as continuous motion. Each frame is a sequence of numbers like an image; the video is a sequence of those sequences, with a sound channel added alongside.
1.1.6.2How much space does a video take?
Computing the sizes of these numbers makes the cost of the representation concrete. The following program computes how many bytes one minute of uncompressed Full HD video and one minute of CD audio take.
long pixels = 1920L * 1080; // one Full HD frame
long frame = pixels * 3; // R, G, B: 3 bytes
long perSecond = frame * 30; // 30 frames/s
System.out.println("Pixels: " + pixels);
System.out.println("Frame (bytes): " + frame);
System.out.println("1 second (bytes): " + perSecond);
System.out.println("1 minute (MB): "
+ perSecond * 60 / 1_000_000);
// 44.1 kHz, 16 bits (2 bytes), stereo, 1 min
long audio = 44_100L * 2 * 2 * 60;
System.out.println("1 min CD audio (bytes): " + audio);Pixels: 2073600
Frame (bytes): 6220800
1 second (bytes): 186624000
1 minute (MB): 11197
1 min CD audio (bytes): 10584000The computation goes step by step. A Full HD frame is 1920 × 1080 = 2,073,600 pixels. Since each pixel takes three bytes, a frame is 2,073,600 × 3 = 6,220,800 bytes, about 6.2 MB. Thirty frames per second come to 6,220,800 × 30 = 186,624,000 bytes. A minute is 60 times that: 11,197,440,000 bytes. The program divides this by 1_000_000 to get megabytes. Because integer division discards the fraction, the output is 11197 MB; that is, one minute of uncompressed Full HD video takes about 11 GB. On the audio side, multiplying 44,100 samples, 2 bytes and 2 channels (stereo) gives 176,400 bytes per second and 10,584,000 bytes per minute, about 10.6 MB.
In real life, video and audio are stored compressed. Video codecs such as H.264 exploit the similarity between successive frames, and audio codecs such as MP3 exploit details the ear cannot hear, shrinking the file many times over. But a compressed file is still a sequence of numbers; only the rules that give the numbers their meaning change.
The most important detail of the code from Java's point of view is the L suffix in the first line. Writing 1920L * 1080 makes the multiplication a long multiplication. Without the L suffix, all the products would be computed as int. The one-second value (186,624,000) fits in an int, but the one-minute value (11,197,440,000) exceeds Integer.MAX_VALUE by more than a factor of five. The expression 1920 * 1080 * 3 * 30 * 60 therefore overflows silently and gives a meaningless negative number such as −1,687,461,888. The 44_100L in the audio computation is written with the L suffix for the same reason; there the result would fit in an int, but writing the suffix is a safe habit.
1.1.7The stored program
1.1.7.1The stored-program concept
So far we have seen how numbers represent data. The last step is that the instructions telling the processor what to do are numbers too. This idea is the basic principle of modern computers.
The stored-program concept: instructions are numbers like data, and they are stored in the same memory as the data. The instructions and data held in memory together make up the program. A machine that works on this principle is called a stored-program computer.
Each instruction represents a specific task or operation: read from memory, add, write to memory. Instructions are normally processed one after another, in the order they sit in memory. But when a condition holds, the program can jump to a different instruction. This is what lets programs follow different paths depending on the situation. The if statement and loops in Java turn into exactly this kind of jump instruction at the processor level.
The importance of the idea becomes clear when compared with the machines before it. ENIAC, completed in 1945, was one of the first large electronic computers, able to perform thousands of additions per second. But its program lived not in memory but in wires and switches. For a new computation, operators had to replug the cables on the panels by hand, and this could take days.
The EDVAC design, which the ENIAC team was working on in the same year, proposed a different path: instructions and data would be stored in memory in sequence. Changing the program meant writing new numbers into memory. This approach was flexible and extensible; a program could even read and produce another program as data. Compilers do exactly this: they read source code and produce machine code. The idea was spread by John von Neumann's 1945 report "First Draft of a Report on the EDVAC". The first machine to run a stored program was a small experimental computer at the University of Manchester in 1948, known as the "Baby".
1.1.7.2The memory hierarchy
Memory is where running programs and their data are temporarily kept. An ideal memory would be very large, very fast and cheap at once. Unfortunately these three properties conflict. Fast memory technologies are expensive and take up a lot of room on the chip. Cheap, large memories are slow. Computers resolve this conflict by arranging memories of different speeds and sizes in layers.
The memory hierarchy is the arrangement of memories from levels that are close to the processor, fast and small to levels that are far, slow and large. The order is: registers, the L1, L2 and L3 caches, main memory (RAM) and disk.
- L1 cache: the fastest cache, located inside the processor. Its size is a few tens of kilobytes per core, and it is accessed in about 1 ns.
- L2 cache: backs up L1 and is larger than it. Most processors also have an L3 cache of a few tens of megabytes, shared by all the cores.
- Main memory (RAM): gigabytes in size, but tens of times slower to access than the caches.
- Disk: terabytes in size and permanent; the access time is between microseconds and milliseconds.
The hierarchy works because programs do not access memory randomly but with a certain pattern. A program tends to reuse data it used a short while ago; loop variables are an example. A program that accesses one address often accesses the addresses right next to it too; walking through an array from start to end is an example. These two tendencies are called locality. A cache keeps recently used data and its neighbors next to the processor. In this way the great majority of accesses are served from the fast cache without going to the slow RAM. Memory close to the processor is faster but smaller and more expensive; how this hierarchy is used directly affects a program's performance. If one of two Java programs that perform the same number of additions walks through an array in order and the other jumps around at random, a speed difference of several times can be seen between them.
1.1.7.3The processor and the bus
The central processing unit (CPU) is where all of the computer's computation is done. It has three basic parts.
- Arithmetic logic unit (ALU): does computations such as addition, subtraction, comparison and bitwise logic operations. The full adders described under binary addition are inside the ALU.
- Control unit: interprets instructions, sequences the operations and directs them. It decides which register will be connected to the ALU and whether a read or a write signal goes to memory.
- Registers: very small but very fast storage areas for temporary data. The numbers the ALU works on come from registers, and the results are written to registers.
The structure that connects the processor to memory and to input/output devices is called the bus. The bus is a communication system made of many parallel wires. The wires fall into three groups according to their function.
- Address signals (address bus): select which memory cell or device is accessed.
- Data signals (data bus): carry the actual data to be processed or stored.
- Control signals (control bus): direct the operation; for example, they signal whether the operation is a "read" or a "write".
The number of wires in the address bus determines how much memory can be addressed. Each wire carries one bit; an address bus with n wires can select 2n different addresses. A 32-line address bus selects 232 = 4,294,967,296 different addresses. If each address points to one byte, that amounts to 4 GiB of memory. This is why 32-bit systems can use at most about 4 GB of RAM, and this limit is one of the main reasons for the move to 64-bit processors. Seen through Theorem 1.1.1, each wire of an address bus is like a one-bit digit, and n digits can write 2n different numbers.
1.1.7.4Registers
Figure 1.1.16 summarizes how the processor, memory and bus work together. Every memory cell has an address and a content. The registers inside the processor are the layer of memory closest to the processor, the smallest and the fastest.
- The processor tells the address bus which cell it wants.
- The contents of the cell travel over the data bus to the processor (a read) or from the processor to the cell (a write).
- PC (program counter): holds the address of the next instruction.
- IR (instruction register): holds the instruction currently being decoded.
- R1, R2 and AC (accumulator): hold intermediate results.
- The ALU computes with the numbers in the registers.
In electronics, registers are built from flip-flops. A flip-flop stores one bit; 32 flip-flops side by side make a 32-bit register. Registers can take a new value on every pulse of the clock signal, so they can be read and written within one clock cycle. There are few of them: a typical processor has a few dozen general-purpose registers. One of the compiler's important jobs is to keep frequently used variables in registers rather than in memory.
1.1.7.5Memory, addresses and the program counter
Memory is the area where data and instructions are stored. From the processor's point of view, a program is a long list of instructions laid out one after another in memory. Every memory cell has an address, and the cell holds an instruction or a piece of data encoded as a number. Instructions are fetched from memory one at a time, loaded into the processor's registers and executed in order.
The program counter (PC) is the register that holds the address of the next instruction. After the processor fetches an instruction, it advances the PC to the next address.
The processor normally proceeds in address order: 200, 201, 202 … But some instructions change this order. In the small piece of memory in Table 1.1.13, there is a JUMP 7 instruction at address 204. In this example, 7 says how far ahead of the instruction's own address to jump: 204 + 7 = 211. The instruction writes 211 into the PC, and the processor skips 205–210 and continues with the instruction at 211. On some machines the jump target is given as such a relative offset, on others directly as an absolute address (like JUMP 211); in both cases the result is that the PC changes.
| Address | Content | Kind |
|---|---|---|
| 200 | ADD to R1 | instruction |
| 201 | 102 | data |
| 202 | … | |
| 203 | … | |
| 204 | JUMP 7 | instruction (jump) |
| … | … | |
| 211 | next instruction | instruction |
The "Kind" column of the table is only there to help the reader; memory has no such column. Whether a memory cell holds an instruction or data cannot be told by looking at the cell: both are numbers. The difference is how the processor uses the cell. When the PC points to a cell, its content is decoded as an instruction; when an instruction reads the cell, its content is used as data. If the PC accidentally points to a data cell, the processor takes that number for an instruction and does meaningless things. This is why computing jump targets correctly is so important.
1.1.7.6The fetch–decode–execute cycle
The fetch–decode–execute cycle is the basic operating cycle that the processor repeats for every instruction. It describes how programs are executed on the processor.
- Fetch: the processor takes the instruction at the address the PC points to from memory and writes it into the IR. The PC advances to the next address.
- Decode: the instruction is decoded. Which operation is to be done, which registers are to be used, which address is to be accessed? Every instruction has a specific function, and the control unit reads this function from the instruction's bits.
- Execute: the operation the instruction calls for is carried out. This may be processing data, computing a result, reading from memory or writing to memory.
Then the next instruction is fetched and the cycle begins again. This cycle repeats without stopping as long as the computer is on. The whole run of a Java program is nothing but this cycle turning billions of times.
The cycle is driven by a clock signal. The clock of a 3 GHz processor "ticks" 3 billion times a second; one clock cycle lasts about 0.33 ns. In a simple processor, each instruction takes a few clock cycles. Modern processors, however, overlap the processing of several instructions: while one instruction is executed, the next is decoded and the one after is fetched. This arrangement is called a pipeline and resembles an assembly line in a factory. When the line is full, one instruction completes in every clock cycle.
1.1.7.7Code trace: 102 + 25 on a toy computer
The operation of the cycle is easy to follow on a toy computer. In this computer, memory addresses 200–203 hold four instructions and addresses 205–207 hold data. The program adds the number at 205 to the number at 206 and writes the result to 207. The parts after the semicolon on each line are comments, and the notation [x] means "the memory cell at address x".
200: LOAD R1, [205] ; R1 ← mem[205]
201: ADD R1, [206] ; R1 ← R1 + mem[206]
202: STORE R1, [207] ; mem[207] ← R1
203: HALT ; stop
204: ...
205: 102 ; data
206: 25 ; data
207: 0 ; result hereThe instructions mean the following. LOAD copies a value in memory into a register. ADD adds a value in memory to the value in a register. STORE writes the value in a register to memory. HALT stops the processor. Initially PC = 200. Table 1.1.14 shows each step.
| Step | Phase | What happens | PC | IR | R1 | [207] |
|---|---|---|---|---|---|---|
| 0 | Start | The program and data are in memory. | 200 | — | — | 0 |
| 1 | Fetch | The instruction at 200 is loaded into the IR; the PC advances. | 201 | LOAD | — | 0 |
| 2 | Decode | Operation LOAD, destination R1, address 205. | 201 | LOAD | — | 0 |
| 3 | Execute | [205] = 102 is read and written to R1. | 201 | LOAD | 102 | 0 |
| 4 | Fetch | The instruction at 201 is fetched. | 202 | ADD | 102 | 0 |
| 5 | Decode | Operation ADD; R1 and [206] are to be added. | 202 | ADD | 102 | 0 |
| 6 | Execute | The ALU computes 102 + 25 = 127; the result goes to R1. | 202 | ADD | 127 | 0 |
| 7 | Fetch | The STORE at 202 is fetched. | 203 | STORE | 127 | 0 |
| 8 | Decode | R1 is to be written to address 207 (control bus: "write"). | 203 | STORE | 127 | 0 |
| 9 | Execute | [207] ← 127. The result is now in memory. | 203 | STORE | 127 | 127 |
| 10 | Fetch | The HALT at 203 is fetched. | 204 | HALT | 127 | 127 |
| 11 | Decode + Execute | HALT: the processor stops. | 204 | HALT | 127 | 127 |
Three observations from the trace are important. First, the PC advances immediately in each Fetch step; while an instruction is being executed, the PC already points to the next one. When the program ends, the PC is 204, because it advanced once more at the moment HALT was fetched. Second, in the execute phase the bus is used in both directions. LOAD and ADD read from memory and STORE writes to memory; the "read/write" signal on the control bus decides which. Third, the ... at address 204 never runs. Since HALT stops the processor, the cell the PC points to is never fetched again.
The Java line total = a + b; also ends up as instructions of this kind. The compiler produces a few machine instructions that take a and b from memory or registers, add them, and write the result to the location of total. The instruction sets of real processors contain hundreds of instructions, but each of them runs through the same fetch–decode–execute cycle.
Suppose the following program, starting at address 200, runs on the same toy computer: 200: LOAD R1, [206]; 201: JUMP 205; 202–204: other instructions; 205: HALT; 206: 40. What are R1 and PC when the program ends?
Fetch 200: the PC becomes 201; in execution, [206] = 40 is written to R1. Fetch 201: the PC first becomes 202; in execution, JUMP writes 205 into the PC. This jump uses an absolute address. Fetch 205: the PC becomes 206; HALT stops the processor. In the end R1 = 40 and PC = 206. The instructions at 202–204 were never fetched.
1.1.8The von Neumann architecture
1.1.8.1Architecture and the bottleneck
The von Neumann architecture is the hardware blueprint of the stored-program idea: a processor, memory, input/output units, and the bus connecting them. Instructions and data sit in the same memory and travel over the same path.
In this architecture every instruction is represented by an opcode. The opcode is the part of the instruction's bits that says which operation is to be performed: addition, loading, jumping? The remaining bits of the instruction give the operands, that is, which registers or which address are to be used.
This design has a cost. The single path between the processor and memory must carry both instructions and data. Because the processor runs much faster than memory, it often waits for an instruction or datum to arrive over this path. This limitation is called the von Neumann bottleneck. Caches exist for this reason: by keeping frequently used instructions and data next to the processor, they reduce the number of trips down the slow path.
For comparison, in the Harvard architecture the instruction memory and the data memory are separate, each with its own path. The processor can fetch an instruction and read a datum at the same time. Many microcontrollers, such as the AVR on Arduino boards, use this structure: the program is in flash memory and the data in SRAM. Modern desktop processors use a hybrid. Main memory is single (von Neumann), but the L1 cache inside the processor is split in two, for instructions and for data (Harvard).
1.1.8.2Encoding instructions
What does it mean for instructions to be numbers? Let us think again about a toy computer: an 8-bit machine with 4 registers (R0–R3), 256 memory cells of 8 bits each, and only 4 instructions. The instructions are addition (00), subtraction (01), multiplication (10) and division (11). Each instruction is an 8-bit number, and the bits are divided into four fields.
- The first 2 bits are the opcode. 2 bits are enough to tell 4 instructions apart, because 22 = 4.
- The next 2 bits are the destination register: the register the result is written to. 4 registers need 2 bits.
- The last 4 bits are the two operand registers, 2 bits each.
The instruction "add the contents of R0 and R2 and write the result to R3" is written with its fields as 0 3 0 2: opcode 0 (addition), destination 3, operands 0 and 2. Converting each field to binary with 2 bits and putting them side by side gives 00 11 00 10 = 00110010.
The processor's "decode" step is to extract these bit fields from the number again. The same can be done in Java with place-value division and remainders.
int instr = 0b00110010;
int opcode = instr / 64; // first 2 bits
int dest = (instr / 16) % 4; // next 2 bits
int src1 = (instr / 4) % 4; // next 2 bits
int src2 = instr % 4; // last 2 bits
System.out.println(instr);
System.out.println(opcode + " " + dest
+ " " + src1 + " " + src2);50
0 3 0 2The logic of the code is easy to see with an analogy in decimal. To find the hundreds digit of 4728, first divide by 100 (47), then take the remainder modulo 10 (7). Binary works the same way. Dividing by 2k drops the k bits on the right; taking the remainder modulo 4 gives the last 2 bits, since 4 = 22. Each field is extracted in turn with these two operations.
1.1.8.3Code trace: decoding an instruction
Table 1.1.15 traces each line of the code together with its binary form.
| Line | Intermediate value | Result | Explanation |
|---|---|---|---|
instr = 0b00110010 | — | 50 | 32 + 16 + 2 = 50 |
opcode = instr / 64 | — | 0 | 64 = 26; the 6 bits on the right are dropped, leaving 00: addition. |
dest = (instr / 16) % 4 | 50 / 16 = 3 (0011) | 3 | The 4 bits on the right are dropped; % 4 takes the last 2 bits: 11 = R3. |
src1 = (instr / 4) % 4 | 50 / 4 = 12 (001100) | 0 | The 2 bits on the right are dropped; 12 % 4 = 0: R0. |
src2 = instr % 4 | — | 2 | The last 2 bits are taken directly: 10 = R2. |
The program first prints 50, then 0 3 0 2. Looked at as an int, 50 is an ordinary integer; to this toy processor it is the instruction "R3 ← R0 + R2". The meaning of a number depends on who uses it and how.
In real Java code, bit fields are usually extracted with bitwise operators rather than division. instr >> 4 shifts the number 4 bits to the right and, for positive numbers, gives the same result as instr / 16. & 3 masks out and keeps the last two bits, doing the job of % 4. The destination field is thus written (instr >> 4) & 3. This notation is closer to what the hardware actually does: the control unit does not divide, it just selects the relevant wires.
What does the instruction 10011100 do on the toy computer?
The bits are split into 2-bit fields: 10 01 11 00. The opcode 10 is multiplication. The destination is 01, that is, R1. The operands are 11 (R3) and 00 (R0). The instruction means R1 ← R3 × R0. To check with Java code, take the numeric value of the instruction, 128 + 16 + 8 + 4 = 156: 156 / 64 = 2; 156 / 16 = 9 and 9 % 4 = 1; 156 / 4 = 39 and 39 % 4 = 3; 156 % 4 = 0. The fields are 2 1 3 0.
1.1.8.4Assembly language
Writing instructions as bit strings like 00110010 is very hard for people. Assembly language gives each machine instruction a memorable abbreviation such as ADD or MOV. A program called an assembler translates text written in assembly into machine code.
MOV AL, 61h into the machine code B0 61; when the processor executes it, 97 is written to the AL register.- Assembly language is specific to a particular processor architecture. Code written for x86 does not run on an ARM processor, because the instructions and encodings of the two architectures differ.
- Each line generally corresponds to a single machine instruction. A single line of Java, on the other hand, often turns into many machine instructions.
- It is important for understanding how the computer works at a low level.
- It is used in performance tuning and in direct interaction with hardware: device drivers, embedded systems, and some parts of operating system kernels.
| x86 instruction | Meaning | Machine code |
|---|---|---|
MOV AL, 61h | Move the value 61h (= 97) into register AL | B0 61 |
MOV AX, BX | Copy the value in BX to AX | 66 89 D8 |
ADD EAX, 10 | Add 10 to EAX | 83 C0 0A |
XOR EAX, EAX | Clear EAX (x XOR x = 0) | 31 C0 |
The codes in Table 1.1.16 are the real-processor counterpart of the idea in the toy computer. In the code B0 61, B0 is the opcode for "load a constant into register AL", and 61 is the constant to load. In ADD EAX, 10, the last byte is 0A = 10. x86 instructions are not a fixed 8 bits as in the toy computer; they vary from 1 to 15 bytes. The 66 byte at the start of the MOV AX, BX code is a prefix saying that the instruction works with 16-bit rather than 32-bit registers. XOR EAX, EAX is a common way to clear a register. The XOR of a number with itself gives 0 in every bit. Moreover, this instruction is encoded shorter than MOV EAX, 0.
The 61h in the first row means hexadecimal 61 (the h suffix in assembly, the 0x prefix in Java). 61h = 0x61 = 97, and 97 is also the ASCII 'a'. Is a byte in memory a number, a letter or an instruction? The byte itself does not say; how the program uses it decides. This sentence is the common conclusion of all the layers in these notes.
Java's place among these layers also becomes clear here. The programmer writes in a high-level language, Java. javac translates this code to bytecode. Bytecode is the instruction set not of a real processor but of the JVM, and it is the same on every processor. While running, the JVM translates the bytecode into the machine instructions, at the assembly level, of that particular machine. Java's principle of "write once, run anywhere" is possible thanks to this intermediate layer.
1.1.9Common mistakes
The most common consequences of the topics in these notes show up in Java as lines the compiler rejects, or as programs that compile and run wrongly. In the list below, each mistake is given together with the compiler message or the program's actual output. The messages are from the JDK 21 compiler.
| Mistake | Code | Result | Cause and fix |
|---|---|---|---|
| Out-of-range literal | byte b = 200; | error: incompatible types: possible lossy conversion from int to byte | byte goes up to 127 at most. 200 is an int literal and does not fit; if you really want it, write (byte) 200 and the value becomes −56. |
Forgetting the L suffix | long x = 3000000000; | error: integer number too large | An integer literal without a suffix is an int, and an int cannot exceed 2,147,483,647. The fix is 3000000000L. |
| Confusing a character with a string | char c = "A"; | error: incompatible types: String cannot be converted to char | Double quotes produce a String. A character is written with single quotes: 'A'. |
| Leading zero | int x = 010;int y = 08; | x = 8error: ';' expected | A leading 0 means octal; 010 = 8. Since there is no digit 8 in octal, the second line does not compile. |
| Not noticing overflow | Integer.MAX_VALUE + 1 | -2147483648 | Integer overflow raises no error; it wraps around. Large products need long, and the product must start out as a long: 1920L * 1080. For checking, use Math.addExact. |
== on fractions | 0.1 + 0.2 == 0.3 | false | Floating-point values are approximate. Look at whether the difference is small: Math.abs(a - b) < 1e-9. |
Taking length() for the number of characters | "😀".length() | 2 | length() counts UTF-16 units. Use codePointCount for code points and getBytes(...).length for bytes. |
Taking a char sum for a string | System.out.println('a' + 'b'); | 195 | The sum of two chars is an int. To concatenate, use "" + 'a' + 'b' or String.valueOf. |
The compiler catches the mistakes in the first four rows of the list, except for 010, and the program never runs. These are annoying but harmless, because the line and cause of the error are seen immediately. The code for 010 and in the last four rows, however, compiles and silently produces wrong results, which makes it more dangerous. An overflowing counter, a floating-point equality or a wrongly computed string length is noticed only when the program behaves unexpectedly somewhere else. The common source of these mistakes is forgetting how a value is represented in memory.
1.1.10Summary
- Components. The CPU computes and consists of the ALU, the control unit and registers. RAM is temporary and disk permanent memory. The bus carries address, data and control signals; an address bus with n lines selects 2n addresses.
- Binary numbers. A bit is 0 or 1; 8 bits make 1 byte. With d digits and base b, the numbers 0 … bd − 1 can be written. To convert decimal to binary, divide by 2 and read the remainders from bottom to top. A hexadecimal digit is 4 bits and an octal digit is 3 bits.
- Bases in Java.
0bmarks a binary literal,0an octal one and0xa hexadecimal one.Integer.toBinaryString,toHexStringandparseInt(s, radix)convert. - Negative numbers. Two's complement: flip the bits and add 1. The weight of the leftmost bit is negative. With 8 bits the range is −128 … 127. If the range is exceeded, Java overflows silently and the value wraps around.
- Fractional numbers. Stored as fraction × baseexponent. By IEEE 754,
floatis 32 bits anddoubleis 64 bits. Values are approximate:0.1 + 0.2 != 0.3. - Text. ASCII is 7 bits and 128 characters. Unicode gives every character a code point (U+0000–U+10FFFF). UTF-8 writes a code point in 1–4 bytes and is compatible with ASCII. Java's
charis a 16-bit UTF-16 unit;length()gives the number ofchars. - Structured information. An image is an array of RGB pixels, sound is pressure samples, and video is a sequence of frames. One minute of uncompressed Full HD video takes about 11 GB.
- Stored program. Instructions also sit in memory as numbers. The PC holds the next address. The processor repeats the fetch–decode–execute cycle continuously; jump instructions change the order.
- The von Neumann architecture. Instructions and data share the same memory and the same path; the single path creates a bottleneck, which caches ease. In the Harvard architecture, instruction and data memories are separate.
- Levels. High-level language → assembly → machine code (bits). Assembly is processor-specific, and each line is usually a single instruction. Whether a byte is a number, a letter or an instruction is decided by the program that uses it.
1.1.11Key terms
- CPU
- RAM
- bit
- byte
- binary number system
- positional value
- hexadecimal
- carry
- two's complement
- overflow
- floating-point number
- character encoding
- ASCII
- Unicode
- code point
- UTF-8
- surrogate pair
- stored-program computer
- memory hierarchy
- cache
- bus
- register
- program counter
- fetch–decode–execute cycle
- von Neumann architecture
- opcode
- assembly language
1.1.12Test Yourself
How is 100 written as an 8-bit binary number and in hexadecimal?
Answer
The powers that fit in 100 are 64 and 32, leaving 4. 100 = 64 + 32 + 4, which is
01100100. Groups of four give0110 0100= 6 and 4, so the hexadecimal value is0x64.What is the bit pattern
11010110as an unsigned number and as an 8-bit two's complement number?Answer
Unsigned: 128 + 64 + 16 + 4 + 2 = 214. Signed: take the weight of the leftmost bit as −128, −128 + 64 + 16 + 4 + 2 = −42; or 214 − 256 = −42.
How are −1 and −128 written in 8-bit two's complement? For
byte m = -128;, why does(byte) (-m)again give −128?Answer
−1 =
11111111(1 =00000001, inverted11111110, +1). −128 =10000000. The number 128 does not exist in the range ofbyte. Flipping the bits of −128 gives01111111, and adding 1 gives10000000again. In Java,-mis first computed as theint128, but the cast tobytekeeps only the last 8 bits and the result is −128.What do these lines print?
System.out.println((byte) 130);,System.out.println((char) ('A' + 2));,System.out.println('A' + 2);Answer
−126,
Cand 67. 130 =10000010, read as signed, is 130 − 256 = −126.'A' + 2is anint(67); with the(char)cast, the character numbered 67,C, is printed; without the cast the number itself is printed.For the string
"Işık"("light"), what arelength()and the number of UTF-8 bytes?Answer
length()is 4; all four characters are below U+FFFF. In UTF-8, I (U+0049) is 1 byte, ş (U+015F) is 2 bytes, ı (U+0131) is 2 bytes and k is 1 byte: 1 + 2 + 2 + 1 = 6.What does
System.out.println(0x2A + 012 + 0b11);print?Answer
55.
0x2A= 2·16 + 10 = 42,012is octal, so 1·8 + 2 = 10, and0b11= 3. The total is 42 + 10 + 3 = 55; the result is printed in decimal.On the toy computer (2-bit opcode: 00 add, 01 subtract, 10 multiply, 11 divide; 2-bit destination; two 2-bit operands), which 8-bit number is the instruction "R1 ← R2 − R3"? Which fields come out when it is decoded with the Java code from the notes?
Answer
01 01 10 11=01011011= 91. Decoding: 91 / 64 = 1; 91 / 16 = 5, 5 % 4 = 1; 91 / 4 = 22, 22 % 4 = 2; 91 % 4 = 3. The fields are 1 1 2 3.A processor has a 20-line address bus, and each address selects one byte. What is the most memory it can address?
Answer
220 = 1,048,576 bytes, that is, 1 MiB. The Intel 8086 processor had exactly this address bus width.
Telephone-quality sound is recorded at 8000 samples per second, 1 byte per sample and a single channel (mono). How many bytes is one minute of uncompressed speech? If the computation is done with
int, does overflow occur?Answer
8000 · 1 · 1 · 60 = 480,000 bytes. This is far smaller than
Integer.MAX_VALUE, so there is no overflow. For CD audio the same computation gives 10,584,000 bytes, which also fits in anint. Overflow starts with products that run into the billions, like video.In Java, the expression
0.1f + 0.2f == 0.3fgivestrue. Does this show that equality comparison is safe withfloat?Answer
No.
float's coarser rounding happened to carry the errors to the same number for these three values. The same sum givesfalsewithdouble, and with other numbersfloatfails too. Floating-point values must always be compared with a tolerance.
1.1.13Further reading
- C. Petzold, Code: The Hidden Language of Computer Hardware and Software (2nd ed., Microsoft Press, 2022): starting from relays and logic gates, it builds the adder, the memory and a simple processor step by step; it is the most readable long-form version of the layered approach taken in these notes.
- R. E. Bryant and D. R. O'Hallaron, Computer Systems: A Programmer's Perspective (3rd ed., Pearson, 2016), Chapter 2: treats unsigned and two's complement integers, overflow, bitwise operations and IEEE 754 floating point from the programmer's viewpoint, with many exercises.
- D. Goldberg, "What Every Computer Scientist Should Know About Floating-Point Arithmetic", ACM Computing Surveys 23(1), 1991: the classic paper explaining in detail where rounding error comes from and the design rationale of the IEEE 754 standard.
- D. A. Patterson and J. L. Hennessy, Computer Organization and Design (RISC-V edition, 2nd ed., 2020), Chapters 2 and 5: explains instruction encoding on a real instruction set and the memory hierarchy with cache details.
1.1.14References
- D. A. Patterson and J. L. Hennessy, Computer Organization and Design: The Hardware/Software Interface, RISC-V edition, 2nd ed., Morgan Kaufmann, 2020.
- C. Petzold, Code: The Hidden Language of Computer Hardware and Software, 2nd ed., Microsoft Press, 2022.
- A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 1).
- Oracle, The Java Tutorials: "Primitive Data Types" and "Characters".
- J. Gosling et al., The Java Language Specification, Java SE 21, §3.10 (Literals) and §4.2 (Primitive Types).
- The Unicode Consortium, The Unicode Standard, unicode.org; IEEE 754-2019, Standard for Floating-Point Arithmetic.
- J. von Neumann, First Draft of a Report on the EDVAC, 1945.
- R. E. Bryant and D. R. O'Hallaron, Computer Systems: A Programmer's Perspective, 3rd ed., Pearson, 2016.
- D. Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic”, ACM Computing Surveys, 23(1), 5–48, 1991.