Computer Fundamentals and Introduction to Programming · Lecture Notes
Chapter 4.3: Introduction to Programming
However clearly an algorithm is written on paper, a processor cannot run it directly. The only language a processor understands is machine language, made of zeros and ones. A programming language sits between the two worlds: people can read it, and a translation tool can turn it into machine language. This note first explains what a programming language is, how source code becomes machine code, and how the compiler, the interpreter, and the virtual machine share that work. It then classifies languages by level, type, paradigm, and typing discipline. The last sections show how a problem becomes a program and what stages software development goes through. The basic constructs (variables, decisions, loops, functions, and arrays) and the ways of finding bugs are illustrated with step-by-step trace tables. The code examples are in Java, Python, and C; the outputs of the Java and Python examples come from real runs.
Learning outcomes
- Concepts
- Define a programming language, its syntax, and its semantics; distinguish source code, assembly, and machine language.
- Execution
- Explain compilation, interpretation, and hybrid execution; place bytecode, the virtual machine, and JIT compilation; list the phases of a compiler and the jobs of the linker and the loader; decide whether an error is a compile-time error, a runtime error, or a logic error.
- Languages
- Classify languages by level, type, and paradigm; explain when static and dynamic typing catch an error; translate pseudocode into Java and Python.
- Problem solving and the software process
- Define a problem by its input, output, and constraints and get from the algorithm to a program; recognize the stages of software development and the development tools.
- Basic constructs and debugging
- Use variables, data types, operator precedence, decisions, loops, functions, and arrays; trace a program step by step with a trace table to find its bug.
4.3.1Basic concepts
A recipe tells you, step by step, what to do in the kitchen. A person reading it fills in a vague phrase such as "a pinch of salt" from experience. A computer has no such experience. Every step it is given must have exactly one meaning, and that meaning must be defined precisely in advance. Programming languages were born from this need.
4.3.1.1What is a programming language?
Everyday language is flexible. The sentence "See you tomorrow" does not say at what time; the listener completes the meaning from context. A machine cannot be expected to infer meaning from context. To make a machine do work, we need a language in which every statement has a single interpretation and whose rules are written down beforehand. Such languages are called formal languages.
A programming language is a formal language that lets people express computational steps to a computer. A collection of commands written in such a language is called a program.
A programming language is the tool for writing an algorithm in a form the computer can execute. An algorithm is an idea: "add a and b, then print the result." That idea can be written in Java, in Python, or in C. The notations differ, but all of them describe the same steps and produce the same output for the same input. Figure 4.3.1 shows this for a = 3 and b = 5: all three languages print 8.
The lines in the figure are only the addition part of complete programs. For a program to run, other lines are needed around them. Below is the complete version of the same task in Java and in C. The Java program was compiled and run with JDK 21; the output of the C program was determined by tracing it line by line.
How is a complete program that adds a = 3 and b = 5 and prints the result written in Java and in C?
Java program:
public class Sum {
public static void main(String[] args) {
int a = 3;
int b = 5;
System.out.println(a + b);
}
}C program:
#include <stdio.h>
int main(void) {
int a = 3;
int b = 5;
printf("%d\n", a + b);
return 0;
}Both programs produce the same output:
8In Java every program is written inside a class, and execution starts at the main method. In C, execution starts at the main function; to print to the screen, printf from the stdio.h library is used. In printf, %d means "an integer goes here" and \n is the end of a line. In Python the same job takes one line: print(a + b). The details differ, but the three steps of the algorithm (set up a, set up b, print the sum) appear in the same order in all three programs.
That the same problem can be solved in different languages raises a question of choice: which language? The answer depends on the needs of the problem and on the environment in which the program will run. An app for a phone, a calculation on a server, and the control software of a washing machine may call for different languages.
Thinking that programming means memorizing a language. The real work of writing a program is building the algorithm: understanding the problem, finding the steps, and making sure the steps run in the right order and under the right conditions. The language is the tool for writing those steps down. A well-built algorithm can be moved from one language to another in a few hours; no language can rescue a badly built one.
4.3.1.2Syntax and semantics
In English, the sentence "Ali went to school" is well formed. "Went school to Ali" can still be understood but breaks the rules. "The school went to Ali" follows the rules but makes no sense. Programming languages also define these two dimensions separately: whether a piece of text follows the rules, and what a well-formed piece of text does.
The syntax of a programming language is the set of rules that determines which constructs may be written in which order. Semantics determines what every well-formed construct does when it is executed.
In Java, ending every statement with a semicolon is a syntax rule. If the line int b = 5 has no semicolon at the end, the text breaks the rule and the program cannot be translated. That the expression a + b computes the sum of a and b is a semantic rule. Python has different syntax: statements need no semicolon, but the indentation of blocks is part of the rule.
A program with correct syntax does not necessarily give the desired result. A line that divides by 4 instead of 3 when computing the average of three grades follows the rules perfectly. The translator accepts the line without complaint, the program runs, and it prints a wrong number. The text is valid, but what it says is not what the programmer wanted. Such errors are called logic errors.
In what way is each of the following three Java lines problematic: syntax or semantics?
int b = 5(no semicolon at the end of the line)double avg = (g1 + g2 + g3) / 4;(the average of three grades is wanted)System.out.println("Sum: " + a + b);(for a = 3, b = 5, "Sum: 8" is wanted)
The first line is a syntax error; the compiler stops with the message "';' expected". The second line follows the rules but divides by the wrong divisor: its meaning does not match the programmer's intent. The third line also follows the rules, but in Java + is evaluated from left to right: first "Sum: " is joined with 3, then 5 is appended, and the screen shows "Sum: 35". To get the intended result, the addition must be parenthesized: "Sum: " + (a + b). Only someone who knows the semantic rules of the language can spot the problem in the last two lines.
4.3.1.3Source code, assembly, and machine language
The text a programmer writes lives in a text file. This file can be opened in Notepad, read, and changed. A processor, however, cannot read this text. The commands a processor understands are encoded as binary numbers, and every processor family has its own instruction set.
Source code is the text form of a program that a developer can read and change. Machine language consists of the binary instructions the processor runs directly; a program made of these instructions is called machine code. Assembly language is the human-readable form of the machine instructions, written with symbolic names.
Figure 4.3.2 shows how a single line passes through these three forms. The compiler translates the source line sum = a + b; into three processor instructions. The first loads the value of a from memory into a processor register (R1). The second adds b to R1. The third writes the result in R1 to the location of sum in memory. Assembly writes these instructions with short names such as LOAD, ADD, and STORE. A tool called an assembler turns these names into binary codes. The binary codes in the figure are only an example; real encodings vary from processor to processor.
Two consequences follow from this translation. First, a programming language and a processor's language are not the same thing. Java or Python is not the language of any processor; for text written in these languages to reach the processor, a translation is needed. The programs that do this translation are generally called translators: compilers and interpreters. Second, one high-level line often corresponds to several machine instructions. The programmer says "add and store"; the translator spells out the load, add, and write steps.
Thinking that the processor "understands" Java or Python source code. The processor runs only its own machine language. That is why double-clicking a .java or .py file does not run it. The file must first pass through a compiler or an interpreter. In Java this job is split in two: javac translates the source code into bytecode, and the JVM runs the bytecode.
4.3.2Running a program
After source code is written, several things happen before a result appears on the screen. The text passes through a translator, the translated code runs on the processor or on a virtual machine, and the running program reads its input and produces its output. A different kind of error can arise at each stop along this path.
4.3.2.1From source code to output
Figure 4.3.3 shows the path of a Java program in five stops. The programmer writes the source code in a text file named Sum.java. The computer cannot run this text as it is. At the translation stop, the compiler reads the text and checks whether it obeys the rules of the language. If there are no errors, it produces an output file. In languages such as C, this file is machine code directly. In Java it is an intermediate-code file named Sum.class. At the execution stop the instructions are carried out on the processor; in Java this is done through the Java Virtual Machine (JVM). At the last stop the program produces its output: 8 for a = 3 and b = 5.
In Java this path is walked with two commands at the command line. javac Sum.java runs the compiler and produces the file Sum.class. java Sum starts the JVM and runs the program in that file. It matters that the two steps are separate: compilation is done once, and the resulting file can be run as many times as you like. If the source code is changed, compilation must be repeated; otherwise the JVM keeps running the old .class file.
Fixing the source code, running java Sum without recompiling, and concluding that "the fix did not work." The JVM runs the compiled .class file, not the source code. Every time the source code changes, javac must be run again. IDEs do this step automatically when you save or press the run button; for that reason the step is often overlooked.
4.3.2.2Kinds of errors
Every stop on the path exposes its own kind of error. Knowing at which stop an error shows up also tells us where to look for it.
A compile error is source code that does not obey the rules of the language; it is found during translation and the program never runs. Syntax errors and type errors are of this kind. A runtime error is an error that arises while the program is running and stops it. A logic error is when the program runs without any error message but produces a wrong result.
It is easy to see the three kinds in three small Java programs. In the first program, the semicolon at the end of the second assignment line has been forgotten:
public class MissingSemicolon {
public static void main(String[] args) {
int a = 3;
int b = 5
System.out.println(a + b);
}
}The compiler refuses to translate the program and reports the location of the error with a line number:
MissingSemicolon.java:4: error: ';' expected
int b = 5
^
1 errorThe message gives the file name, the line number (4), and the expected token (;). The ^ below it shows where the compiler expected the semicolon. In this case no .class file is produced and no line of the program runs; "8" never appears on the screen. Figure 4.3.4 shows this situation with the red mark at the translation stop of the pipeline.
In the second program the syntax is flawless, but line 5 contains a division by zero:
public class DivideByZero {
public static void main(String[] args) {
System.out.println("Hello");
int x = 10;
System.out.println(x / 0);
System.out.println("End");
}
}Compilation finishes successfully. When the program runs, "Hello" is printed first, then the JVM tries to evaluate x / 0 and stops the program:
Hello
Exception in thread "main" java.lang.ArithmeticException: / by zero
at DivideByZero.main(DivideByZero.java:5)In the output, ArithmeticException: / by zero names the division-by-zero error, and DivideByZero.java:5 gives the line of the error in the source file. The "End" line never runs. The compiler cannot catch this error, because the value of x and the division are computed only at run time. If the divisor were user input, it would be impossible to know at compile time whether it would be zero.
The third program computes the average of three grades, but a parenthesis is missing:
public class AverageBug {
public static void main(String[] args) {
int g1 = 70, g2 = 85, g3 = 90;
System.out.println(g1 + g2 + g3 / 3);
System.out.println((g1 + g2 + g3) / 3);
System.out.println((g1 + g2 + g3) / 3.0);
}
}185
81
81.66666666666667The program compiles without trouble, runs without any error message, and prints 185 on the first line. The expected result is a number between 81 and 82. Because division happens before addition, only g3 is divided by three: 70 + 85 + 90 / 3 = 70 + 85 + 30 = 185. This is a logic error. The second line adds the parentheses but is still not quite right. In Java the quotient of two integers is an integer; the fractional part of 245 / 3 is discarded and the result is 81. The third line divides by 3.0; the computation is done in floating point and the correct value, about 81.67, comes out. This is what logic errors have in common: the program "works," and only someone who compares the expected result with the actual one notices the problem.
| Kind of error | When does it appear? | Who reports it? | Example |
|---|---|---|---|
| Compile (syntax, type) | During translation; the program never runs | The compiler, with a line number | A forgotten ;, assigning text to an int |
| Runtime | During execution, when the faulty line is reached | The JVM or the operating system; the program stops | Division by zero, going outside an array |
| Logic | Never shows up by itself | Nobody; found only by testing | A missing parenthesis, a wrong divisor |
What kind of error is each of the following? (a) In Java, the line System.out.println("Hello") has no semicolon at the end. (b) When the user enters 0 for the number of students, the program stops while computing the average. (c) When computing a class average, the total is divided by n + 1 instead of the number of students n.
- (a) A compile error. The semicolon is a syntax rule; the compiler reports it with a line number and no program is produced.
- (b) A runtime error. The code obeys the rules and compiles; but the moment the divisor is 0, execution stops. The same program runs fine with non-zero inputs, so the error shows up only with certain inputs.
- (c) A logic error. The program runs with every input and prints a number; the number it prints is always smaller than it should be. For grades 60, 70, and 80, for example, it prints 210 / 4 = 52.5; the correct value is 210 / 3 = 70.
Counting the absence of an error message as proof that a program is correct. The compiler only checks whether the rules were followed; it cannot know whether the program does the intended job. Every program must be tried on a few inputs whose results have been computed by hand.
4.3.2.3Compiled, interpreted, and hybrid languages
There are three common ways to run source code. The difference lies in when the translation is done and how much of it is done.
A compiler is a program that translates the whole program into target code before it runs; this process is called compilation. An interpreter is a program that runs a program by evaluating it command by command at run time, without first translating it into an executable file; this process is called interpretation. In hybrid execution, the source code is first compiled to an intermediate code, and the intermediate code is executed on a virtual machine.
| Approach | How it works | Example languages |
|---|---|---|
| Compiled | The program is translated beforehand into target machine code | C, C++, Rust |
| Interpreted | Commands are evaluated at run time | Python, JavaScript |
| Hybrid | Intermediate code is executed on a virtual machine | Java, C# |
Figure 4.3.5 shows the three paths side by side. On the compiled path, the file source.c goes through the compiler and an executable such as program.exe comes out. This file runs on the processor directly; at run time the compiler is no longer needed. On the interpreted path, the file source.py is handed to the interpreter every time it runs. The interpreter processes the commands in order and has the processor carry them out. There is no lasting machine-code file in between. On the hybrid path, Sum.java is first compiled with javac into Sum.class. The JVM runs this file, and the JVM itself is a program running on the processor.
Which path is chosen also determines how the program is distributed. A compiled C program is valid only for the processor and operating system it was compiled for. An .exe file compiled for Windows does not run on Linux or on a computer with a different processor. An interpreted Python program is distributed as source code; it runs on every computer that has the Python interpreter installed. Java's .class file, on the other hand, is processor-independent: the same file runs on every platform that has a JVM. Java's well-known slogan "write once, run anywhere" comes from this property.
Putting Java in the same group as C as a "compiled language." Java source code is compiled, but what the compiler produces is not machine code but bytecode, which the JVM understands. This code does not run directly on the processor; a JVM is needed to run it. Placing Java in the hybrid class describes this two-stage structure correctly.
4.3.2.4The compiler and the interpreter step by step
The difference between a compiler and an interpreter is best seen on the same small program. The third line of the following three-line pseudocode contains a division by zero:
| Line | Pseudocode |
|---|---|
| 1 | print "Hello" |
| 2 | x ← 10 |
| 3 | print x / 0 |
In pseudocode, assignment is written with ←: x ← 10 means "give x the value 10." This keeps assignment from being confused with an equality comparison. Let the program be processed first by a compiler and then by a simple interpreter that runs line by line. What happens at each step is listed in Table 4.3.3.
| Step | Compiler | Simple interpreter |
|---|---|---|
| 1 | Lines 1, 2, and 3 are read and translated from start to end; no line has run yet | Line 1 is translated and runs immediately: Hello |
| 2 | The division is well formed; translation succeeds and an executable is produced | Line 2 is translated and runs: x = 10; line 3 has not been read yet |
| 3 | Execution begins; line 1: Hello | Line 3 is translated, and an error occurs while it runs: division by zero |
| 4 | Line 2: x = 10; line 3: runtime error | — |
| Screen | Hello, then the error | Hello, then the error |
In this program both paths end with the same screen: "Hello" followed by an error. The difference lies not in the kind of error but in the order of the work. The compiler translates the whole text first, and execution comes later as a separate stage. The interpreter interleaves translating and running line by line. Because division by zero is a runtime error, in both paths it shows up only when the third line runs. Figure 4.3.6 shows the final state of the two paths.
When the error is a syntax error, the two paths part ways. Suppose a parenthesis is left unclosed on the third line: print (x + 2. The compiler stumbles on this line during translation and produces no executable. The screen shows only the message "line 3: syntax error"; not even "Hello" is printed. A simple line-by-line interpreter, however, runs line 1 and prints "Hello," assigns 10 to x on line 2, and notices the error only when it reaches line 3.
Modern interpreters such as those for Python and JavaScript depart a little from this simple model: before they start running, they parse the whole file. They therefore report syntax errors at the very start. The following Python file shows this:
print("Hello")
x = 10
print((x + 2)
print("End") File "syntax_error.py", line 3
print((x + 2)
^
SyntaxError: '(' was never closed"Hello" does not appear on the screen. Before running the first line, Python read the whole file and found the unclosed parenthesis on line 3. When the same file has a division by zero instead of a syntax error, the situation changes:
print("Hello")
x = 10
print(x / 0)
print("End")Hello
Traceback (most recent call last):
File "zero_division.py", line 3, in <module>
print(x / 0)
~~^~~
ZeroDivisionError: division by zeroThis time "Hello" is printed, because a division by zero is detected only when the third line runs. Python's message resembles Java's: the file name, the line number, the kind of error (ZeroDivisionError), and a short description.
A four-line program has a syntax error on line 2 and a division by zero on line 4. What appears on the screen if the program is run (a) with a compiler, (b) with a simple line-by-line interpreter, (c) with Python? Line 1 prints "Start" and line 3 prints "Middle".
- (a) The compiler first translates all four lines. It stops at the syntax error on line 2 and produces no executable. The screen shows only a compile error message for line 2; "Start" is not printed.
- (b) The simple interpreter translates and runs line 1: "Start". When it tries to translate line 2, it stops with the syntax error. Lines 3 and 4 are never reached. The screen shows "Start" and the error message.
- (c) Python first parses the whole file and finds the error on line 2. The screen shows only the
SyntaxErrormessage; the behavior is the same as in (a). The division by zero on line 4 never shows up in any of the three cases, because the program would have to run that far.
4.3.2.5Bytecode, the virtual machine, and JIT compilation
Python is called an "interpreted language," but the Python interpreter also contains a compilation step. CPython, the most common implementation of Python, first compiles the source code into an intermediate code called bytecode. It then executes this bytecode command by command on a virtual machine inside it. No machine-code file results. The compilation step is hidden from the programmer: the command python file.py performs the two stages one after the other.
Bytecode is an intermediate code made of simple instructions designed for a virtual machine rather than for a particular processor. A virtual machine is software that reads and executes these instructions; it imitates the work of a real processor in software.
The bytecode Python produces can be seen with the dis module. The following program compiles the line area = width * height + 2 and prints its bytecode:
import dis
dis.dis(compile("area = width * height + 2", "<code>", "exec")) 0 RESUME 0
1 LOAD_NAME 0 (width)
LOAD_NAME 1 (height)
BINARY_OP 5 (*)
LOAD_CONST 0 (2)
BINARY_OP 0 (+)
STORE_NAME 2 (area)
RETURN_CONST 1 (None)Each line of the output is a virtual machine instruction. LOAD_NAME pushes the value of a variable onto the virtual machine's stack. BINARY_OP 5 (*) multiplies the top two values on the stack, LOAD_CONST pushes the constant 2, and BINARY_OP 0 (+) adds. STORE_NAME binds the result to the name area. Instruction names may change slightly between Python versions; Python 3.13 was used here. The order, however, is the same in every version: first width and height are multiplied, then 2 is added. This order comes from operator precedence.
Executing bytecode instruction by instruction is slower than running machine code directly. For every instruction the virtual machine has to answer the question "what does this instruction mean?" The way to reduce this slowness is JIT compilation.
A just-in-time (JIT) compiler is a compiler that translates frequently executed pieces of code into machine code while the program is running. The translated piece is not interpreted on later runs; it runs directly on the processor.
Figure 4.3.7 shows this idea using JavaScript. The V8 engine in the Chrome browser first interprets the code. When it sees that a function has been called thousands of times, it compiles it to machine code. The JVM follows the same path: bytecode is interpreted at first, and frequently run methods are translated into machine code by the JIT. For this reason, long-running Java programs can reach speeds close to those of compiled C programs.
These examples bring out an important point: "compiled" or "interpreted" is a property not of a language but of an implementation of that language. Implementations of Python that compile to machine code have been written, and so have interpreters for C. Most real systems combine the two methods. Calling a language "interpreted" is a short way of saying how its most common implementation works.
Saying "Python is an interpreted language, so no compilation takes place." CPython compiles the source code to bytecode on every run. It stores the bytecode of imported modules as .pyc files in the __pycache__ folder and reuses these files on later runs if the source has not changed. What makes Python interpreted is that the bytecode is executed command by command on a virtual machine, not as machine code.
4.3.2.6The phases of a compiler
A compiler does not work in one big step. It splits its job into five consecutive phases; the output of each phase is the input of the next. Following the phases on a single line also explains which error the compiler catches and where. The line to follow is this:
area = width * height + 2;1. Lexical analysis. The compiler sees the line as a sequence of characters: a, r, e, a, space, = ... The first phase splits these characters into meaningful pieces called tokens. Whitespace and comments are discarded in this phase. Eight tokens come out of the example line, and the type of each is known (Figure 4.3.8).
area = width * height + 2; is split into eight tokens: three identifiers, three operators, one constant, and one separator.The errors caught in this phase are character sequences that match no token of the language. In Java the # character is not an operator. An unclosed string cannot be turned into a token either. The JDK 21 compiler reports these two cases as follows:
IllegalCharacter.java:4: error: illegal character: '#'
int area = width # height;
^
IllegalCharacter.java:4: error: not a statement
int area = width # height;
^
2 errorsUnclosedString.java:3: error: unclosed string literal
System.out.println("Hello);
^
1 error2. Syntax analysis (parsing). The tokens are arranged into a tree according to the rules of the language; this tree is called a syntax tree. Figure 4.3.9 shows the tree of the example line. At the root is the assignment (=); its left branch is area and its right branch is the expression width * height + 2. The multiplication is deeper in the tree, so it is evaluated first. Operator precedence is built into the shape of this tree in exactly this way.
A missing semicolon, an unclosed parenthesis, and tokens written in the wrong order are caught in this phase. For example, in the line int 2x = 5; lexical analysis sees no problem: 2 is a number and x is an identifier. But a number following the int token breaks the rules. The compiler therefore reports the error in the syntax phase:
InvalidToken.java:3: error: not a statement
int 2x = 5;
^
InvalidToken.java:3: error: ';' expected
int 2x = 5;
^
2 errors3. Semantic analysis. A tree with correct syntax is checked for meaning. Every name that is used must have been declared earlier. The types of the operands must also fit together. In the example line, width and height are declared as int; the expression int × int + int yields int and can be assigned to area, which has type int (Figure 4.3.10).
If the variable height is used without being declared, javac gives this message:
public class Undeclared {
public static void main(String[] args) {
int width = 3;
int area = width * height + 2;
}
}Undeclared.java:4: error: cannot find symbol
int area = width * height + 2;
^
symbol: variable height
location: class Undeclared
1 errorThe message says that the symbol that could not be found is a variable and that its name is height. Type mismatches are also the job of this phase. Assigning text to an int variable is flawless as far as syntax goes, but invalid as far as meaning goes:
public class TypeMismatch {
public static void main(String[] args) {
int x = 5;
x = "five";
}
}TypeMismatch.java:4: error: incompatible types: String cannot be converted to int
x = "five";
^
1 errorThe message means "type String cannot be converted to int." The compiler points at the value "five" on line 4 before the program ever runs.
4. Intermediate code generation and optimization. The checked tree is turned into simple instructions, each of which performs a single operation. This form is called three-address code, because each instruction mentions at most three names:
t1 = width * height
t2 = t1 + 2
area = t2Here t1 and t2 are temporary names the compiler invents. Code optimization is performed on this form: unnecessary operations are dropped, and operations whose results are known at compile time are computed in advance. If width = 3 and height = 4 are constants that never change, the computation 3 × 4 + 2 = 14 is done before the program runs, and only area = 14 is left in the code. This optimization is called constant folding (Figure 4.3.11).
5. Code generation. In the last phase the instructions of the target processor are selected and translated into binary code. For the example line, a processor would get LOAD, MUL, ADD, and STORE instructions (Figure 4.3.12). The target of the Java compiler is not a real processor but the JVM. For this reason javac produces bytecode instead of machine instructions.
The bytecode javac produces can be read with the javap -c command that comes with the JDK. The only difference between the following two programs is that in the second, width and height are declared final (unchangeable). How do the bytecodes of the two programs differ?
public class AreaExpr {
public static void main(String[] args) {
int width = 3;
int height = 4;
int area = width * height + 2;
System.out.println(area);
}
}public static void main(java.lang.String[]);
Code:
0: iconst_3
1: istore_1
2: iconst_4
3: istore_2
4: iload_1
5: iload_2
6: imul
7: iconst_2
8: iadd
9: istore_3
10: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
13: iload_3
14: invokevirtual #13 // Method java/io/PrintStream.println:(I)V
17: return
}In the bytecode of the first program, iconst_3 and istore_1 store the value 3 in local variable number 1 (width). iconst_4 and istore_2 store 4 in height. The next five instructions (iload_1, iload_2, imul, iconst_2, iadd) compute the expression, and istore_3 stores the result in area. This sequence is the same as the "iload iload imul iconst_2 iadd istore" sequence in the slides.
public class ConstantFolding {
public static void main(String[] args) {
final int width = 3;
final int height = 4;
int area = width * height + 2;
System.out.println(area);
}
}public static void main(java.lang.String[]);
Code:
0: bipush 14
2: istore_1
3: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
6: iload_1
7: invokevirtual #13 // Method java/io/PrintStream.println:(I)V
10: return
}The second program has no multiplication or addition instructions at all. The instruction bipush 14 pushes the value 14 directly onto the stack. Because width and height are final, the compiler knows their values will not change and performs 3 × 4 + 2 at compile time. This is a real example of constant folding. Both programs print 14 when run.
The first three phases look for errors and report any they find with a line number. The last two phases produce the code that will run. Value-dependent errors such as division by zero show up in no phase, because the compiler does not run the program; it only looks at its text.
| Phase | Input → output | Error caught (javac message) |
|---|---|---|
| Lexical analysis | characters → tokens | Illegal character (illegal character), unclosed string (unclosed string literal) |
| Syntax analysis | tokens → syntax tree | Missing ; (';' expected), unclosed parenthesis |
| Semantic analysis | tree → checked tree | Undeclared name (cannot find symbol), type mismatch (incompatible types) |
| Intermediate code and optimization | tree → simple instructions | — |
| Code generation | simple instructions → machine code or bytecode | — |
Always assuming that the line number the compiler reports is the error itself. The compiler reports the place where it noticed the error; this is sometimes one line after the real error. When the semicolon at the end of a line is forgotten, some compilers see the error at the start of the next line. If the message points at one line, look at the previous line too.
4.3.2.7The linker and the loader
Real programs do not consist of a single file. In a calculator program, the user interface may live in one file and the calculation functions in another. For the program to print to the screen, open a file, or take a square root, ready-made library code is also used. The compiler translates each source file separately. Combining these pieces into one program and loading it into memory to run is the job of two separate tools.
An object file is a machine-code file, produced by compiling a single source file, that cannot run on its own (.o or .obj). The linker is the program that combines object files and the library code in use into a single executable file. The loader is the part of the operating system that brings the executable file into memory and starts it running.
Figure 4.3.13 shows the path of a C program. main.c contains the main program and calc.c contains the calculation functions. The compiler translates them into the object files main.o and calc.o. In main.o there is a call to a function in calc.c, but the address of that function is not yet known. The compiler only leaves a note: "a function with this name is being called here." The linker resolves these notes. It finds the called function in calc.o and ready-made functions such as printf in the library. It ties every call to the correct address and finally writes the file program.exe.
If a called function cannot be found in any piece, the linker reports a linking error. This error differs from a compile error. Each file may have compiled flawlessly on its own; what is missing is the connection between the pieces. For example, if the function average called in main.c is misspelled averge in calc.c, the two files compile separately, but the linker cannot find the name average anywhere.
When the program is double-clicked or invoked from the command line, the loader steps in. It copies the file from disk into memory. It also loads and links the shared libraries the program needs: .dll files on Windows, .so files on Linux. Finally it directs the processor to the first instruction of the program. Many programs share a shared library; the same code does not have to be copied into each program separately.
In Java there is no separate linking step. Each class is compiled into its own .class file. The JVM's class loader finds and loads a class's file at the moment the class is first needed while the program runs. If a class file is missing, the error appears not during compilation or linking but at run time.
Mistaking an object file (.o, .obj) for an executable program. An object file contains machine code, but calls to other files and libraries are not yet linked. To run, it must go through the linker.
4.3.2.8Compile or interpret?
The choice between compiling and interpreting is a trade-off. On one side are speed and early error checking; on the other are quick experimentation and flexibility. Table 4.3.5 compares the three approaches on five criteria.
| Criterion | Compiled (C) | Interpreted (Python) | Hybrid (Java) |
|---|---|---|---|
| Execution speed | Usually fastest: direct machine code | Slower: commands are decoded while running | Close to compiled, thanks to the JIT |
| Error reporting | Syntax and type errors before running | Type errors mostly only when that line runs | Most at compile time, the rest at run time |
| Distribution | A separate file for each operating system and processor | Source code + an interpreter installed on the target | A single .class / .jar + a JVM on every platform |
| Development cycle | Recompile after every change | Save and run immediately | Compile, then run |
| Startup | Starts immediately, no extra software needed | The interpreter must be loaded first | The JVM must be started first |
A game engine or a video encoder cares about every millisecond; compiled C or C++ is preferred for this reason. A data analyst asking different questions of a dataset does not want to wait for compilation after every attempt; Python's "save and run" cycle suits that work. A bank's server software runs for years and is moved to different hardware. Java's portable bytecode and the speed it gains from the JIT fit this need. That both a compiler and an interpreter can be written for the same language is also a result of this trade-off.
A student wants to run the same program on three different computers: a Windows laptop, a Linux server, and a macOS desktop. If the program were written in C, Python, and Java, what would have to be distributed in each case?
- C: three executables, each compiled separately for its platform. The
.exeproduced on Windows does not run on Linux. The source code can also be distributed; then every computer must have a C compiler. - Python: the source file (
.py). The Python interpreter must be installed on all three computers. - Java: a single
.classor.jarfile. All three computers must have a JVM; the same file runs unchanged on all three.
4.3.3Programming languages
The number of programming languages in use today is counted in the hundreds. It is neither possible nor necessary to know them all. Grouping languages by a few criteria makes it easier to place a new language when you meet one. The main criteria are closeness to the hardware, the era of origin, the purpose of use, the way of thinking, and the time of type checking.
4.3.3.1Language levels
A low-level language is a language whose instructions correspond one-to-one or nearly one-to-one to processor instructions: machine language and assembly. A high-level language is a language that lets you write a problem close to the way people express it and hides hardware details: C, Java, Python.
Figure 4.3.14 arranges languages on a ladder. At the bottom is machine language: 10110000 01100001. On Intel-compatible processors, these two bytes are the instruction "load the value 61h (hexadecimal 61, decimal 97) into the AL register." Assembly writes the same instruction as MOV AL, 61h. One rung up is C: the line x = x + 1; says nothing about registers; it talks about a variable. Java and C# are higher still; they take memory management away from the programmer. Python is at the top: writing print(x) needs no class or type declaration.
Climbing the ladder brings a gain and a cost. The gain is writing the same job in fewer and clearer lines. Printing a string to the screen takes one line in Python; in assembly it can take dozens. The cost is less control over the hardware. If a driver has to write to a specific memory address at a specific moment, languages on the lower rungs such as C or assembly are needed. So level is not a measure of quality; it describes a language's degree of abstraction. A high-level language is not "better" than a low-level one; it is better suited to other jobs.
What number is the second byte in the machine instruction 10110000 01100001? Why is this number written as 61h in assembly?
- The second byte is
01100001. By place values: 0·128 + 1·64 + 1·32 + 0·16 + 0·8 + 0·4 + 0·2 + 1·1 = 64 + 32 + 1 = 97. - The byte splits into two groups of four bits:
0110= 6 and0001= 1. Every four bits make one hexadecimal digit; the number is 61 in base 16. Check: 6 · 16 + 1 = 97. - The trailing h shows that the number is hexadecimal. Assembly programmers like hexadecimal notation because each digit corresponds to exactly four bits, which makes conversion to binary easy. 97 is the code of the lowercase letter "a" in the ASCII table.
4.3.3.2The evolution of programming languages
The first computers were programmed directly in machine language. Programmers wrote instructions as binary numbers, sometimes flipping switches by hand one at a time. Assembly appeared in the late 1940s: instructions were given memorable names, and assembler programs were written to translate these names into binary. Figure 4.3.15 summarizes the following seventy years on a timeline.
The development can be divided into three periods.
- 1940–1970. The era of machine language and assembly. In 1957, John Backus's team at IBM developed FORTRAN. FORTRAN was the first widely used high-level language that let scientific formulas be written almost as in mathematics. In 1959, COBOL was designed for business and accounting applications. In 1964, BASIC was developed at Dartmouth College so that students could learn programming.
- 1970–1990. In 1972, Dennis Ritchie developed the C language at Bell Laboratories. The UNIX operating system was largely rewritten in C. Because C was close to the hardware yet portable across processors, it became the basic language of systems programming. In 1983, Bjarne Stroustrup announced C++, which added the concepts of classes and objects to C.
- After 1990. Python appeared in 1991, Java and JavaScript in 1995, and C# in 2000. What these languages share are managed environments that take memory management away from the programmer, and suitability for the web. Rich libraries and open-source ecosystems also helped them spread. More recently, Go (2009) focused on concurrent server programs and Rust (version 1.0 in 2015) on safe systems programming.
One trend stands out in this history: each new generation took over a job the previous one left to the programmer. Assembly took binary encoding off the programmer's hands, FORTRAN took register management, and Java took memory management. What was left to the programmer moved a little closer to the problem itself.
4.3.3.3Application areas and choosing a language
Programs run in very different environments, and each environment has different needs. The main application areas are these:
- Web: interfaces that run in the browser (the client), server programs that answer requests, and web services.
- Mobile: phone and tablet apps.
- Data and artificial intelligence: data analysis, statistical modeling, machine learning, and automation.
- Systems: operating systems, device drivers, and the embedded software inside a household appliance.
- Scientific computing: simulation and engineering solutions; the behavior of a bridge under load or the frequency response of a circuit.
- Games: game engines, graphics, and interaction with the user.
In each area some languages stand out (Figure 4.3.16). For interfaces that run in the browser, JavaScript (and its typed extension TypeScript) is almost the only choice, because it is the language browsers run directly. Android apps are written in Kotlin or Java and iOS apps in Swift; the official tools of these platforms support these languages. In data analysis, Python and R are common thanks to their rich libraries. In embedded systems, memory and processing power are limited, so C, C++, and Rust are preferred. On enterprise servers, Java, C#, and Go are common.
When choosing a language, first consider the problem area and the platform the program will run on. Then ask these questions. Are there ready-made libraries that do the needed work? Is the language's community large enough to find answers to questions? If the program will be maintained for years, is it easy to find developers who know the language? How important are speed and memory use? Does the language have a weakness from a security point of view? Which language does the team already know? How will the program be distributed?
A group of electrical and electronics engineering students will do two projects: (a) a program that runs on a microcontroller, reads a temperature sensor, and switches a fan on and off, and (b) an analysis that plots a week of data collected from the sensor and finds its mean and maximum. Which languages are suitable?
- (a) A microcontroller may have only a few kilobytes of memory and no operating system. The program must access hardware registers directly. These conditions call for a compiled language close to the low level: C or C++. Rust is also an increasingly common option.
- (b) The program will run once on a laptop; speed is secondary. Ready-made libraries for graphics and statistics and quick experimentation matter. Python (or R) is suitable.
- Choosing different languages for the two projects is not a contradiction. The choice follows from the needs of the problem and the platform.
Choosing a language only because it is popular. The most popular language may not fit on a microcontroller, or the library you need may not exist in that language. Popularity is a plus in terms of community and abundance of resources, but it alone is not enough for the right choice.
4.3.3.4Kinds of languages
Languages are also grouped by purpose of use. A language can fall into more than one group; Python is both general-purpose and a scripting language.
| Kind | Characteristic | Example languages | Example line |
|---|---|---|---|
| General-purpose | Offers variables, decisions, loops, and functions for any kind of problem | Java, C, Python | for (int i = 0; i < 3; i++) |
| Domain-specific | Focuses on a single job | SQL, Excel formulas | SELECT name FROM student WHERE avg >= 60; |
| Scripting | Automates repetitive tasks, usually interpreted | Python, JavaScript, Bash, PowerShell | Copy-Item *.txt backup\ |
| Markup | Describes the structure of content; has no decisions or loops | HTML, XML, Markdown | <h1>Title</h1> |
General-purpose languages offer the whole set of constructs such as variables, decisions, loops, and functions. With these constructs, in principle, any computation a computer can perform can be written. The for line in the table is the head of a loop that runs three times in Java.
Domain-specific languages do one job very well. SQL is designed for querying databases. The line in the table fetches the names of those in the student table whose average is 60 or above. The line says what is wanted, not how to find the result; the database management system decides how to scan the table. Formulas in Excel such as =AVERAGE(B2:B30) are also a domain-specific language: they compute in cells.
Scripting languages are used to automate repetitive tasks. The PowerShell command in the table copies all the .txt files in the current folder to the backup folder. Instead of copying hundreds of files by hand, this single line is run. Scripting languages are usually interpreted; a line you write can be tried at once.
Markup languages describe the structure of a document. The <h1>Title</h1> in HTML says "this text is a first-level heading." Markup languages have no decisions or loops; they cannot do different things depending on a condition and cannot repeat a task. For this reason they are not counted as programming languages. In a web page, HTML defines the structure, CSS the appearance, and JavaScript the behavior; of these three, only JavaScript is a programming language.
Block-based visual languages can be added to these groups. In languages such as Scratch, you do not type commands; you drag colored blocks and snap them together. Because blocks can only fit together in rule-abiding ways, syntax errors cannot be made. This property shifts attention from syntax to the algorithm when one is just beginning to learn programming.
Counting HTML as a programming language. HTML defines the heading, paragraph, and link on a page but computes nothing: it cannot add two numbers, test a condition, or repeat a task. The "programmed" part of a web page is the JavaScript code that works alongside it.
4.3.3.5Programming paradigms
There are several ways of thinking about solving the same problem. One counts off the steps in order, one sees the problem as objects talking to each other, and one builds a chain of functions that transform data. These ways of thinking are called programming paradigms.
A programming paradigm is a fundamental approach to how a program is organized. Imperative programming specifies step by step how operations are to be done and changes the state of the program with those steps. Object-oriented programming combines data and the behavior that works on that data in objects. Functional programming builds the program as a composition of functions that work on immutable data.
Figure 4.3.17 compares the three approaches on the same task: finding the sum of the array grades = {70, 90, 80}. The Java program below contains all three approaches.
import java.util.Arrays;
public class Paradigms {
static class Student {
private final int[] grades;
Student(int[] grades) { this.grades = grades; }
int total() {
int t = 0;
for (int g : grades) t += g;
return t;
}
}
public static void main(String[] args) {
int[] grades = {70, 90, 80};
/* imperative */
int total = 0;
for (int g : grades)
total += g;
System.out.println(total);
/* object-oriented */
Student student = new Student(grades);
System.out.println(student.total());
/* functional */
System.out.println(Arrays.stream(grades).sum());
System.out.println(Arrays.toString(grades));
}
}240
240
240
[70, 90, 80]The imperative solution starts a variable named total at 0 and changes it on every turn of the loop. The successive values of the total are 0, 70, 160, and 240. The program reads like a recipe: "first do this, then do that." C and assembly are fundamentally imperative languages.
In the object-oriented solution, the grades live inside a Student object. The job of computing the total belongs to the same object: student.total(). The code that uses the object does not need to know how the total is computed; it just asks the object. This arrangement pays off as programs grow. Everything about the student lives in one place, and when a change is needed it is clear where to look. Java, C++, and C# are object-oriented languages.
In the functional solution, the expression Arrays.stream(grades).sum() turns the array into a stream of values and sums the stream. No variable holds an intermediate state, and the array itself does not change. The last line of the program confirms this: the array is still [70, 90, 80]. The functional approach favors functions that always give the same output for the same input and change nothing outside themselves. Such functions are easy to test and to combine. Haskell is a purely functional language; Python, JavaScript, and Java also offer functional features.
Many of today's languages support more than one paradigm. All three solutions can be written in Java, and in Python too:
grades = [70, 90, 80]
total = 0
for g in grades:
total += g
print(total)
print(sum(grades))
from functools import reduce
print(reduce(lambda a, b: a + b, grades, 0))240
240
240The reduce function in Python applies a small function that adds two numbers to the elements of the array in turn, starting from 0: ((0 + 70) + 90) + 80 = 240. Which approach to choose depends on the structure of the problem and the habits of the team. Large programs often use all three approaches together.
The largest of the numbers in an array is to be found. How do the imperative and functional approaches express this job? Let the array be {12, 45, 7, 30}.
- Imperative: a variable named
maxstarts at the first element of the array (12). Each element is compared withmax; if it is larger,maxis updated. The state changes step by step: 12 → 45 → 45 → 45. The result is 45. - Functional:
Arrays.stream(array).max().getAsInt()in Java,max(array)in Python. The expression says "the maximum of the array"; the order of comparisons and the intermediate variable are invisible to the programmer. The array does not change, and the result is again 45. - In both solutions the computer makes the same comparisons. The difference lies in how the program reads: one puts "how" in front, the other "what."
4.3.3.6Static and dynamic typing
Every value has a type: 5 is an integer, "five" is a string, and true is a Boolean. Languages split in two according to when types are checked.
Static typing is the discipline in which a variable's type is known in the source code and checked at compile time: Java, C, C#. Dynamic typing is the discipline in which the type is carried by the value rather than the variable and is checked at run time: Python, JavaScript.
In Java, a variable's type is written when it is declared: int x = 5;. From then on x can hold only integers. The line x = "five"; is caught in the compiler's semantic analysis phase: "incompatible types: String cannot be converted to int". The error is found before the program ever runs.
In Python, a variable's type is not declared. The same name can refer first to a number and then to a text. The type is carried by the value itself:
x = 5
print(type(x).__name__)
x = "five"
print(type(x).__name__)
print("a" + 1)int
str
Traceback (most recent call last):
File "dynamic.py", line 5, in <module>
print("a" + 1)
~~~~^~~
TypeError: can only concatenate str (not "int") to strThe output of the first two lines says that x first holds a value of type int and then one of type str (string). Both are valid. The "a" + 1 on line 5, however, tries to add a number to a string and raises a TypeError. What matters is when the error appears. When Python parses the file it sees no problem with this line, because the line's syntax is correct. The error appears only when the line runs, after the output of the two earlier print lines has been written to the screen. If this line were in a rarely executed branch of the program, the error might go unnoticed for months.
Some languages silently convert types instead of reporting an error on a type mismatch. JavaScript is the well-known example. The following lines were run with Node.js:
console.log("5" * 2);
console.log("5" + 2);
console.log(typeof ("5" * 2), typeof ("5" + 2));
console.log("5" - 2);10
52
number string
3In "5" * 2, because multiplication can be done only on numbers, JavaScript converts the string "5" to the number 5 and gets 10. In "5" + 2, however, since + also means string concatenation, 2 is converted to a string and the result is "52". The third line shows the types of the two results: one is a number, the other a string. The same two values were converted to different types depending on the operation. Silent conversions of this kind are convenient in short scripts but lead to hard-to-find logic errors in large programs.
| Characteristic | Static (Java) | Dynamic (Python) |
|---|---|---|
| Where does the type live? | In the variable, written in the declaration | In the value; there is no declaration |
| When is a type error found? | At compile time, before the program runs | When that line runs |
| Can the same name hold values of different types? | No | Yes |
| Strength | Errors are found early, and the IDE helps more | Short code, quick experimentation |
Thinking dynamic typing means "no types." In Python every value has a definite type, and Python enforces the type rules: "a" + 1 raises an error. What dynamic typing lacks is not the type rules but the checking of those rules before the program runs.
4.3.3.7From pseudocode to real languages
When an algorithm is first written in pseudocode and then translated into a language, every construct in the pseudocode has a counterpart in the language. Table 4.3.8 gives the Java and Python counterparts of the most commonly used constructs.
| Pseudocode | Java | Python |
|---|---|---|
read x | x = in.nextInt(); | x = int(input()) |
print "Sum: ", t | System.out.println("Sum: " + t); | print("Sum:", t) |
x ← x + 1 | x = x + 1; | x = x + 1 |
if x > 0 then … else … | if (x > 0) { … } else { … } | if x > 0: … else: … |
for i ← 1 to n | for (int i = 1; i <= n; i++) | for i in range(1, n + 1): |
repeat while the condition is true | while (condition) { … } | while condition: |
Pseudocode uses ← for assignment, because the = sign means equality in mathematics. Java and Python write assignment with = and the equality comparison with ==. The in in Java is a Scanner object that reads from the keyboard. In Python, input() always returns a string; if a number is wanted, it must be converted with int(...).
The most visible difference between the two languages is how blocks are delimited. Java marks a block with curly braces ({ }) and ends each statement with ;. Python wants neither; indentation determines the block. So in Python indentation is not just appearance but part of the program's meaning:
x = -3
if x > 0:
print("positive")
print("done")
if x > 0:
print("positive")
print("done")doneBecause x = −3, both conditions are false. In the first if block, print("done") is not indented, so it is outside the block and runs regardless of the condition. In the second block the same line is indented, so it is inside the block and does not run because the condition is false. The only difference between the two parts is four spaces; only one "done" appears in the output.
How is pseudocode that finds the sum of the numbers from 1 to n translated into Java and Python for n = 5?
sum ← 0
for i ← 1 to n
sum ← sum + i
print "Sum: ", sumThe Java version (n = 5 is taken as a constant):
public class SumLoop {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
}
System.out.println("Sum: " + sum);
}
}The Python version:
n = 5
sum = 0
for i in range(1, n + 1):
sum = sum + i
print("Sum:", sum)
i = 1
while i <= 3:
print(i)
i = i + 1
print("done")The Python file also prints 1, 2, 3 with a while loop. The outputs:
Sum: 15Sum: 15
1
2
3
doneThe sum changes on each turn as follows: 0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6, 6 + 4 = 10, 10 + 5 = 15. The expression range(1, n + 1) in Python starts at 1 and stops before reaching n + 1; that is, it produces 1, 2, 3, 4, 5. Had range(1, n) been written, 5 would be skipped and the sum would be 10.
4.3.4Problem solving
Writing a program does not begin at the keyboard. First you understand what the problem is, then you solve a few examples by hand, and only at the end do you write code. When this order is skipped, the result is often programs that "run but do the wrong job."
4.3.4.1From problem to program
The example problem is a simple one: a program that computes the area of a rectangle. Figure 4.3.18 shows this problem turning into a program in five stages. The output of each stage is the input of the next.
- Define the problem. What is wanted becomes clear: the area of a rectangle. The program's input is the width and height, and its output is the area. There is also a constraint: a length cannot be zero or negative, so width and height must be greater than 0. Constraints are often not written down explicitly in the problem; whoever defines the problem has to find them.
- Try examples. A few examples are solved by hand: 3 × 4 = 12, 5 × 5 = 25. A boundary case is also considered: what should happen if the width is 0? By the constraint, this input is invalid. The examples solved by hand also supply the expected results for later checking whether the program works correctly.
- Build the algorithm. The language-independent steps are written in pseudocode: read the width, read the height, compute the area, print the area.
- Convert to code. The algorithm is translated into the chosen language. In Java, the computation line becomes
area = width * height;and the printing lineSystem.out.println(area);. - Test. The program is run with the examples solved by hand. For 3 and 4 it gives 12: correct. For −2 and 4 it gives −8: since an area cannot be negative, this is wrong. The error is not in the code but in the algorithm; the algorithm never checks the constraint. We go back to the algorithm and add the step "if width and height are not greater than 0, report an error."
The return in the last stage is a natural part of the process. The stages form not a straight line but a loop: if testing finds something missing in the coding or the algorithm, we go back to the relevant stage. The corrected algorithm is this:
read width
read height
if width > 0 and height > 0 then
area ← width × height
print "Area: ", area
else
print "Invalid size"The Java version of this algorithm is below. In Java, && is the "and" operator: the result is true if both conditions are true.
import java.util.Scanner;
public class Area {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int width = in.nextInt();
int height = in.nextInt();
if (width > 0 && height > 0) {
int area = width * height;
System.out.println("Area: " + area);
} else {
System.out.println("Invalid size");
}
}
}The program was run with four inputs: (3, 4), (−2, 4), (0, 5), and (5, 2). The outputs are, in order:
Area: 12Invalid sizeInvalid sizeArea: 10Starting to write code without defining the problem. A badly defined problem turns into a program that works correctly but does the wrong job. The request "a program that computes a grade average" leaves several questions unanswered. Are the grades weighted? How many grades will be entered? What happens if an invalid grade (−5, 120) is entered? A program written without asking these questions has to be changed on its first real use.
4.3.4.2Tracing the area algorithm
The most reliable way to be sure that an algorithm works correctly is to trace it line by line on paper. At each step the values of the variables are written into a table. This table is called a trace table. Variables can be thought of as boxes in memory: the line read width writes the number coming from the keyboard into the box named "width." Boxes that have not yet been given a value are shown with "—" in the table.
Table 4.3.9 traces the algorithm on the input width = 3, height = 4.
| Step | Line | width | height | area | Explanation / output |
|---|---|---|---|---|---|
| 1 | read width | 3 | — | — | 3 is read and written into the width box |
| 2 | read height | 3 | 4 | — | 4 is read |
| 3 | if width > 0 and height > 0 | 3 | 4 | — | 3 > 0 and 4 > 0 → true; the "then" branch is entered |
| 4 | area ← width × height | 3 | 4 | 12 | 3 × 4 = 12 |
| 5 | print "Area: ", area | 3 | 4 | 12 | Output: Area: 12; the "else" branch is skipped |
Table 4.3.10 traces the same algorithm on the input width = −2, height = 4. This is the input that gave a wrong result in the testing stage.
| Step | Line | width | height | area | Explanation / output |
|---|---|---|---|---|---|
| 1 | read width | −2 | — | — | −2 is read |
| 2 | read height | −2 | 4 | — | 4 is read |
| 3 | if width > 0 and height > 0 | −2 | 4 | — | −2 > 0 is false; the whole condition joined by "and" is false → the "else" branch |
| 4 | print "Invalid size" | −2 | 4 | — | Output: Invalid size; the area was never computed |
In the second trace the area box stays empty from start to finish. The program never entered the "then" branch. The error found in testing is thus fixed: for −2, a warning is now printed instead of −8.
A perimeter computation is to be added to the area algorithm: perimeter = 2 × (width + height). How does the algorithm change? What are the outputs for width = 6, height = 1.5?
- Two lines are added to the "then" branch:
perimeter ← 2 × (width + height)andprint "Perimeter: ", perimeter. The constraint check stays the same; for an invalid size the perimeter is not computed either. - Condition: 6 > 0 and 1.5 > 0 → true.
- area = 6 × 1.5 = 9.
- perimeter: first the parentheses, 6 + 1.5 = 7.5; then 2 × 7.5 = 15.
- Output: "Area: 9" and "Perimeter: 15". Without the parentheses, the multiplication would be done first and the result would be 2 × 6 + 1.5 = 13.5.
Because width and height can be fractional with this input, the Java version must use double instead of int.
4.3.5Software development
A small program such as the rectangle area is one person's work for an hour. A bank's mobile application or a hospital's appointment system, on the other hand, is the work of dozens of people over months or even years. At this scale, organizing the work is at least as important as the code itself.
4.3.5.1The software development process
The path from problem to program is divided, at large scale, into six stages (Figure 4.3.19). The stages can be explained with an "app that computes a student's grade average."
- Requirements. What does the user want? The student will enter the grade and credit of each course, and the app will show the weighted average. A grade must be between 0 and 100. The app will run on a phone. Requirements are written by talking with the user, and all later stages rest on this text.
- Design. The screens, the data, and the algorithms are planned. What will be entered on which screen? Where will the grades be stored? By what formula will the average be computed? Flowcharts and pseudocode are the tools of this stage.
- Coding. The design is written in a programming language.
- Testing. Expected results are compared with actual results. For two courses, one with 60 points and 3 credits and one with 90 points and 2 credits, the expected average is (60 · 3 + 90 · 2) / 5 = 360 / 5 = 72. If the app shows 75 (the unweighted mean of the two grades), there is a bug and we go back to coding.
- Deployment. The program is delivered to the user: it is published in an app store or an installation file is shared.
- Maintenance. After use begins, new bugs are found and new requests arrive: "show the letter grade too." These requests are new requirements, and the cycle starts again.
Depending on the project, the stages are carried out sequentially or iteratively. Feedback from users can change the requirements and the design. Most of the effort spent over a software's lifetime goes not to the first version but to maintenance. That is why it matters to write code from day one so that it is readable and changeable.
Thinking the testing stage means "seeing that the program works." The aim of testing is not to prove that the program works correctly but to find the cases in which it works incorrectly. A good test suite includes normal inputs whose results have been computed by hand beforehand, boundary cases (0, an empty list, the smallest and largest values), and invalid inputs.
4.3.5.2Development approaches
There are different approaches to organizing the six stages (Figure 4.3.20).
In the waterfall model the stages are done in order and once each. Design does not start until the requirements are fully written, and coding does not start until the design is finished. A document is produced at the end of each stage. The strength of this arrangement is its clarity: who does what and when is known. Its weakness is that it is closed to change. If a gap in the requirements is noticed during coding, the cost of going back is high.
In the agile approach the work is divided into short cycles, each a few weeks long. In each cycle there is a little planning, a little coding, and testing. At the end of the cycle a working version is shown to the user and feedback is collected. A misunderstood requirement thus surfaces within a few weeks rather than months later. The price of this approach is the need for constant communication with the user.
In prototyping, a quick draft is prepared before starting on the real product. The draft has screens, but there may be no real computation or database behind them. If the user cannot fully explain what they want, the idea becomes clear once they see the draft. The purpose of the draft is to make the requirements visible. It must not be mistaken for the product itself and put straight into use.
| Approach | Strength | Watch out for |
|---|---|---|
| Waterfall model | Stages and documents are clear | Going back to change things is costly |
| Agile | Gets feedback in short cycles | Requires constant communication |
| Prototyping | Makes vague requirements visible | A prototype must not be mistaken for the product |
Which approach suits each of three projects? (a) Software that controls an aircraft's landing gear; the requirements have been fixed in advance by international standards. (b) A café's ordering app; the owner says "I'll decide when I see the screens." (c) A student club's events app; the features change every term at the members' request.
- (a) The waterfall model. The requirements are fixed, and documenting every stage is mandatory for audit. Since no change is expected, the model's weakness is no problem here.
- (b) Prototyping. The user can say what they want only when they see concrete screens. A quick draft clears up this vagueness.
- (c) The agile approach. Requests keep changing; short cycles and the feedback collected at the end of each cycle suit this.
4.3.5.3Development tools
A developer's daily work is a loop: write the code, translate and run it, test the result, find the bug if there is one, fix it, and try again. A different tool comes into play at each step of this loop (Figure 4.3.21).
- Code editor and IDE. Code can be written in a text editor, but programmers mostly use an integrated development environment (IDE). An IDE colors the code, completes names, underlines syntax errors as you type, and organizes the project's files. IntelliJ IDEA, Eclipse, and Visual Studio Code are common examples.
- Compiler and runtime. It translates and runs the program: javac and the JVM, the Python interpreter, a C compiler.
- Debugger. It stops the program at a chosen line, shows the current values of the variables, and steps through line by line.
- Version control. It records every change to the files and makes teamwork possible.
- Testing tools. They verify expected behavior automatically. The programmer writes once, "for this input this output is expected," and the tool reruns all the tests within seconds after every change. In Java, JUnit is the well-known tool for this.
- Package manager. It downloads the ready-made libraries (dependencies) the program uses, tracks their versions, and updates them: pip for Python, npm for JavaScript, Maven and Gradle for Java.
Assuming code the IDE does not underline is free of errors. An IDE can show syntax and type errors as you type, because it runs the first phases of the compiler in the background. It cannot see runtime and logic errors. The absence of a red underline says only that compilation will succeed.
4.3.5.4Version control
If a student keeps copies of a file while writing an assignment as hw_final.java, hw_final2.java, hw_REALLYFINAL.java, they are trying to do version control by hand. This method gets muddled within days. Which copy has which change is forgotten; and if two people work on the same file, things become hopeless.
Version control is a system that stores the history of changes to files and organizes how several people work on the same files. A commit is the storing of the state of the files at a given moment together with who changed what and when. A branch is a line of changes that splits off from the main code and proceeds independently. A merge is the transfer of one branch's changes into another branch.
Figure 4.3.22 shows the history of the rectangle program. C1 is the first version. In C2 the area computation was added, and in C3 the perimeter computation. After C2, a developer opened a branch (B1) to try a new computation and worked there without breaking the main code. When the experiment succeeded, the branch was merged into the main branch (C4). Had the experiment failed, the branch would have been deleted and the main branch never affected. If a change in C3 introduced a bug, the project can be returned to its C2 state with a single command.
The most common version control tool is Git. In Git the history above is created with a few commands. git init turns a folder into a repository. git add stages the changed files for the next commit. git commit -m "area added" creates the commit with its message. git branch experiment opens a new branch; git merge experiment merges that branch into the current one. git log lists all commits with their author, date, and message.
In teamwork, every developer has a copy of the repository on their own computer. Services such as GitHub and GitLab store the repository on the network and serve as a common meeting point between the copies. If two people changed different lines of the same file, Git merges the changes automatically. If they changed the same line, a merge conflict occurs. Git shows the two versions side by side and asks a person to choose which one stays.
Ayşe and Mehmet are working from the same repository. Line 12 of the program is double vat = price * 0.18;. Ayşe changes this line to price * 0.20 and commits. Mehmet changes the same line to price * VAT_RATE and adds the constant at the top of the file. What happens when they try to merge their changes?
- The constant line added at the top of the file is only Mehmet's change; Git takes it without trouble.
- Both changed line 12. Git cannot know which is correct and reports a conflict. Both versions of the line are shown, marked, in the file.
- The two developers talk and decide the final form of the line:
price * VAT_RATE, with the constant's value 0.20. The chosen form is committed and the merge is complete.
Thinking version control is a tool only for big teams. A student working alone also benefits from being able to go back in time. When a change breaks the program, returning to the last working version takes one command. The commit messages also help you remember later why the code was changed.
4.3.6Basic programming constructs
However different languages may look, they are all built on the same few building blocks. Values are stored in named places and computed with expressions. Different paths are chosen according to conditions, and work is repeated. Frequently performed jobs are given names, and many values are gathered under a single name. The constructs are given first in pseudocode and then with their Java and Python counterparts.
4.3.6.1Variables and data types
A variable is a named place in memory that holds a value; its value can change during the program. A data type determines how a value is represented in memory and which operations can be performed on it.
A variable can be thought of as a box with a name written on it (Figure 4.3.23). The age box holds 19, the height box holds 1.75, the name box holds "Ali," and the passed box holds the value true. When a new value is written into a box, the old one is erased. The box's type limits what can be put in it: text cannot be put in an integer box.
| Type | What it holds | Example value | Java | Operations |
|---|---|---|---|---|
| Integer | A number without a fraction | 19, −3, 0 | int | Four arithmetic operations, remainder (mod) |
| Floating-point number | A number with a fraction | 1.75, 81.67 | double | Four arithmetic operations |
| String | A sequence of characters, text | "Ali" | String | Concatenation, length, getting a character |
| Boolean | True or false | true, false | boolean | and, or, not |
In code the decimal separator is the period: Java and Python do not accept the notation 1,75 as a number. In this note decimal fractions are written with a period everywhere (1.75).
The choice of data type follows from the meaning of the value. A student's name is a string because it consists of letters. A grade average is a floating-point number because it can be fractional, like 81.67. The answer to "did the student pass the course?" is Boolean because it can only be yes or no. The number of students is an integer because it cannot be fractional.
Giving variables meaningful names makes the purpose of the program visible. The line a = b * c says nothing; the line area = width * height explains itself. Names are the cheapest and most effective tool for readability.
Keeping a value that may be fractional in an integer type. In Java, the line int avg = 245 / 3; gives no error; it stores 81, and the fractional part is silently lost. For values such as averages, ratios, and measurements, double is used. At least one operand of the division must also be fractional: 245 / 3.0.
4.3.6.2Operator precedence
When an expression contains several operations, operator precedence determines which is done first. The rules in programming languages are the same as the mathematics rules learned at school:
- What is inside parentheses is computed first.
- Multiplication, division, and mod (remainder) are done before addition and subtraction.
- Addition and subtraction are done last.
- Operations at the same level are done from left to right.
The mod operation (% in Java and Python) gives the remainder of a division: 7 mod 3 is 1, the remainder of dividing 7 by 3. Table 4.3.13 shows these rules applied to five expressions.
| Expression | Order of computation | Result |
|---|---|---|
| 2 + 3 × 4 | First 3 × 4 = 12, then 2 + 12 | 14 |
| (2 + 3) × 4 | First the parentheses 2 + 3 = 5, then 5 × 4 | 20 |
| 20 / 4 × 2 | Same level, left to right: 20 / 4 = 5, then 5 × 2 | 10 |
| 10 − 4 − 3 | Left to right: 10 − 4 = 6, then 6 − 3 | 3 |
| 7 mod 3 + 1 | First 7 mod 3 = 1, then 1 + 1 | 2 |
The compiler builds operator precedence into the expression's tree. Figure 4.3.24 shows the tree of the expression 2 + 3 × 4: the multiplication is deeper, so it is done first; the addition is at the root, so it is done last.
The expressions in the table give the same results in Java. The following program prints the table's five expressions and two extra expressions that test the left-to-right rule:
public class Precedence {
public static void main(String[] args) {
System.out.println(2 + 3 * 4);
System.out.println((2 + 3) * 4);
System.out.println(20 / 4 * 2);
System.out.println(10 - 4 - 3);
System.out.println(7 % 3 + 1);
System.out.println(20 / (4 * 2));
System.out.println(10 - (4 - 3));
}
}14
20
10
3
2
2
9The last two lines show why the left-to-right rule matters. The expression 20 / 4 × 2 gives 10; written with parentheses as 20 / (4 × 2), the result is 2. In Java this second result should really have been 2.5: because the quotient of two integers is an integer, the fractional part of 20 / 8 is discarded. Similarly, 10 − 4 − 3 = 3 while 10 − (4 − 3) = 9.
In Python the same expressions give the same results with one difference:
185.0
81.67
52.33
14 20 10.0 3 2
10In the fourth line of the output, the expression 20 / 4 * 2 gives 10.0, because in Python the / operator always produces a floating-point result. For integer division there is the // operator, which gives 10 as in the last line. The 185.0 on the first line is the result of the missing parenthesis. This error appears in Python exactly as it does in Java.
A student's midterm grade is 60 and final grade is 80; the midterm weighs 40% and the final 60%. The programmer writes avg ← midterm × 0.4 + final × 0.6. Is the result correct? What would have come out if the same computation had been written as avg ← midterm + final × 0.6 / 2?
- In the first expression the two multiplications are done first: 60 × 0.4 = 24 and 80 × 0.6 = 48. Then the addition: 24 + 48 = 72. No parentheses are needed, because multiplication is already done first. The result is correct.
- In the second expression, multiplication and division come first, left to right: 80 × 0.6 = 48, 48 / 2 = 24. Then the addition: 60 + 24 = 84. The program gives no error but prints 84; this is a logic error.
Forgetting the parentheses in the average formula: avg ← a + b / 2. This expression first divides b by two, then adds a. For a = 70, b = 90 the result is 70 + 45 = 115; the correct value is (70 + 90) / 2 = 80. The program gives no error. For this reason, such errors are found only by testing. Using parentheses wherever you are unsure of the precedence both prevents the error and shows the reader your intent clearly.
4.3.6.3Decisions and loops
If a program ran only from top to bottom in order, it would take the same steps for every input. Real problems, however, require behaving differently depending on conditions and doing the same work over and over. The two constructs that provide this are the decision and the loop (Figure 4.3.25).
A selection, or decision, chooses one of several paths of operations depending on whether a condition is true or false. A loop repeats a group of operations as long as a condition is true. The repeated group of operations is the loop's body, and each run of the body is an iteration.
In a decision, only one of the two paths is followed on each run. In the area algorithm, if the condition is true the area is computed, and if it is false a warning is printed; the two never happen together in the same run. In a loop, however, the flow returns to the condition at the end of the body. The condition is checked again at the start of every iteration. When the condition becomes false, the loop is exited and execution moves to the line after the loop.
For a loop to be able to end, the body must contain a change that affects the condition. If the condition is i ≤ 3, the body must push i above 3 someday. If there is no such change, the condition stays true forever and the loop never ends.
4.3.6.4Tracing a loop: the infinite loop
The following pseudocode was written to print the numbers from 1 to 3. In the first version the programmer forgot line 4:
i ← 1
while i ≤ 3
print i
i ← i + 1 // missing in the first version
print "done"An infinite loop is a loop that never ends because its condition never becomes false.
Table 4.3.14 traces the first few steps of the first version. With i ← 1 the loop variable is set up. The condition 1 ≤ 3 is true, the body is entered, and 1 is printed. Since there is no other line in the body, we return to the condition. i is still 1, and the condition is true again. The state is exactly the same as in the previous iteration.
| Step | Line | i | Condition | Body executions | Output |
|---|---|---|---|---|---|
| 1 | i ← 1 | 1 | — | 0 | |
| 2 | while i ≤ 3 | 1 | 1 ≤ 3 → true | 0 | |
| 3 | print i | 1 | — | 1 | 1 |
| 4 | while i ≤ 3 | 1 | 1 ≤ 3 → true | 1 | |
| 5 | print i | 1 | — | 2 | 1 |
| … | … | 1 | always true | grows without bound | 1, 1, 1, … |
Because nothing makes the condition false, the loop never ends (Figure 4.3.26). The screen fills with 1s. A program running in a console can be stopped only with Ctrl+C.
In the corrected version the line i ← i + 1 is added to the body. Table 4.3.15 traces this version from start to finish.
| Step | Condition check | Body | i (after the iteration) | Body executions |
|---|---|---|---|---|
| Startup | — | i ← 1 | 1 | 0 |
| Iteration 1 | 1 ≤ 3 → true | 1 is printed, i ← 2 | 2 | 1 |
| Iteration 2 | 2 ≤ 3 → true | 2 is printed, i ← 3 | 3 | 2 |
| Iteration 3 | 3 ≤ 3 → true (equality) | 3 is printed, i ← 4 | 4 | 3 |
| Exit | 4 ≤ 3 → false | The loop is exited; "done" is printed | 4 | 3 |
The loop variable now advances on every iteration. On the third iteration the condition 3 ≤ 3 is still true, because ≤ includes equality. If this detail is overlooked, one might think the numbers will be printed only up to 1 and 2. When the loop finishes, the body has run 3 times and the condition has been checked 4 times: three true and one false. In a loop the condition is always checked once more than the body runs. The last check is the one that ends the loop. The Java version and its output:
public class CountLoop {
public static void main(String[] args) {
int i = 1;
while (i <= 3) {
System.out.println(i);
i = i + 1;
}
System.out.println("done");
}
}1
2
3
doneHow many iterations does the following loop run, and what does it print? k ← 1; while k < 20: print k; k ← k × 3. What would happen if the line k ← k × 3 in the body were forgotten?
- Iteration 1: 1 < 20 is true; 1 is printed, k = 3.
- Iteration 2: 3 < 20 is true; 3 is printed, k = 9.
- Iteration 3: 9 < 20 is true; 9 is printed, k = 27.
- 27 < 20 is false; the loop ends. It runs three iterations and prints 1, 3, 9; the condition is checked 4 times.
- If the multiplication line in the body were forgotten, k would stay 1 forever. Since the condition would always be true, the loop would print 1 forever.
Changing the loop variable in the wrong direction. In the loop i ← 1; while i ≤ 3: print i; i ← i − 1, the body changes i, but not in the direction that makes the condition false. i decreases as 1, 0, −1, −2 and always stays below 3. It is not enough for the body to change something; the change must someday make the condition false.
4.3.6.5Functions and arrays
As programs grow, two needs arise. The first is that the same job is done in many places in the program; the area of a rectangle may be computed in ten places. The second is storing many similar values; defining 40 separate variables for the grades of the 40 students in a class makes no sense. The function meets the first need and the array the second (Figure 4.3.27).
A function is a block of code that performs a specific task and is called by a name. It can take parameters as input and can return a result. The values given when calling the function are called arguments. An array is a structure that stores many values of the same type under a single name, by sequence number. The sequence number of an element is called its index.
A function names a task. The function square(x) is the name of the task "take the square of a number." The code that uses the function does not care how the square is computed; it just writes square(4) and gets 16. The formula lives in one place. If there is a bug in the formula, it is fixed once, and the fix is reflected everywhere the function is called.
In an array, values are selected by sequence number. In Java, C, and Python the sequence number starts at 0. In the four-element array grades, the first element is grades[0] = 85 and the last is grades[3] = 64. The last index is always length − 1. This rule may seem odd at first, but there is logic to it: the index says how many steps the element is from the start of the array; the first element is zero steps from the start.
These two constructs divide a program into small pieces that can be tested separately. A program that computes a grade average can be split into three functions that read the grades, compute the average, and find the letter grade; the grades are also kept in a single array.
4.3.6.6Tracing a function call
The following pseudocode defines the area function and calls it twice:
function area(width, height)
result ← width × height
return result
end
a ← area(3, 4)
b ← area(2, 5)
print a + bFunction calls are tracked in memory with a structure called the call stack. For every call, a new stack frame is added on top of the stack. The frame holds the function's parameters and its own variables. When the function finishes, its frame is removed from the stack. The frame at the top of the stack belongs to the function that is running at that moment. Table 4.3.16 traces the program step by step.
| Step | Event | Main program | area frame |
|---|---|---|---|
| 1 | The definition (lines 1–4) is recorded, not run; the program starts at line 5 | a = —, b = — | none |
| 2 | area(3, 4) is called; new frame, 3 → width, 4 → height | a = —, b = — | width = 3, height = 4 |
| 3 | Body: result ← 3 × 4 = 12 | a = —, b = — | width = 3, height = 4, result = 12 |
| 4 | return result: 12 is sent back to the caller | a = —, b = — | about to be removed |
| 5 | The frame is removed; the returned value is assigned to a | a = 12, b = — | none |
| 6 | area(2, 5) is called; a brand-new frame | a = 12, b = — | width = 2, height = 5 |
| 7 | Body: result ← 2 × 5 = 10 | a = 12, b = — | width = 2, height = 5, result = 10 |
| 8 | 10 is returned, the frame closes | a = 12, b = — | about to be removed |
| 9 | The returned value is assigned to b | a = 12, b = 10 | none |
| 10 | print a + b → 22 | a = 12, b = 10 | none |
Three conclusions come out of the trace. First, a function definition by itself does nothing; it runs only when called. Second, every call opens its own frame. The first call's value result = 12 is not visible in the second call's frame, because the first frame has long been removed. The variables inside a function live only as long as that call lasts. Third, the main program does not see inside the function; it only receives the returned value. A function written once was used twice, and the area formula stays in a single place (Figure 4.3.28).
In Java, functions are called methods. The header static int area(int width, int height) says that the method takes two integers and returns an integer:
public class AreaFunction {
static int area(int width, int height) {
int result = width * height;
return result;
}
public static void main(String[] args) {
int a = area(3, 4);
int b = area(2, 5);
System.out.println(a + b);
}
}22function perimeter(width, height): return 2 × (width + height) is defined. The main program runs the line c ← perimeter(3, 4) + perimeter(1, 1). How many frames are opened, and what is c?
- First
perimeter(3, 4)is called: a frame opens, width = 3, height = 4. 2 × (3 + 4) = 14 is returned and the frame closes. - Then
perimeter(1, 1)is called: a new frame, width = 1, height = 1. 2 × (1 + 1) = 4 is returned and the frame closes. - The two returned values are added: c = 14 + 4 = 18. In total two frames were opened; the two are never on the stack at the same time.
Trying to use a variable defined inside a function outside the function. The variable result in the area function exists only in the function's frame; writing print result in the main program gives a "cannot find symbol" compile error in Java. A value the function produces gets out only through return.
4.3.6.7Averaging with an array
The following pseudocode computes the average of four grades with an array and a loop:
grades ← [85, 72, 90, 64]
total ← 0
for i ← 0, 1, 2, 3
total ← total + grades[i]
avg ← total / 4
print "Average: ", avgThe variable that holds the sum is called an accumulator. The accumulator is initialized to 0 before the loop, and one more value is added on every iteration. If no initial value were given, the first value of the total would be undefined. Table 4.3.17 traces each iteration of the loop.
| Step | i | grades[i] | Operation | total |
|---|---|---|---|---|
| Startup | — | — | total ← 0 | 0 |
| Iteration 1 | 0 | 85 | 0 + 85 | 85 |
| Iteration 2 | 1 | 72 | 85 + 72 | 157 |
| Iteration 3 | 2 | 90 | 157 + 90 | 247 |
| Iteration 4 | 3 | 64 | 247 + 64 | 311 |
| After the loop | — | — | avg ← 311 / 4 | 311 (avg = 77.75) |
The loop ends after four iterations. The last index is 3, that is, length − 1. The result is printed as "Average: 77.75" (Figure 4.3.29). In the Java program the loop bound is written not as a fixed 4 but as the array's length, grades.length. That way, when a grade is added to the array, the loop adapts by itself. The division is also done with 4.0 so that the result is not rounded to an integer:
public class Average {
public static void main(String[] args) {
int[] grades = {85, 72, 90, 64};
int total = 0;
for (int i = 0; i < grades.length; i++) {
total = total + grades[i];
}
double avg = total / 4.0;
System.out.println("Average: " + avg);
}
}Average: 77.75In Python the same computation is shorter. The built-in functions sum and len hide the loop from the programmer:
grades = [85, 72, 90, 64]
total = 0
for i in range(4):
total = total + grades[i]
avg = total / 4
print("Average:", avg)
print(sum(grades) / len(grades))Average: 77.75
77.75What would happen if the loop ran one iteration too many? An array with four elements has no cell number 4. Java reports this with a runtime error:
public class OutOfBounds {
public static void main(String[] args) {
int[] grades = {85, 72, 90, 64};
System.out.println(grades[3]);
System.out.println(grades[4]);
}
}64
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at OutOfBounds.main(OutOfBounds.java:5)grades[3] is read without trouble and 64 is printed. When grades[4] is requested, the JVM stops the program. The phrase "Index 4 out of bounds for length 4" in the message means "in an array of length 4, index 4 is outside the bounds." Writing the loop bound as i <= grades.length is the most common cause of this error; the correct form is i < grades.length.
In the array temps = [18, 21, 25, 19, 22], the days above 20 are to be counted. How is the trace done with a counter and a loop? How many days are found?
count ← 0. i = 0: temps[0] = 18; 18 > 20 is false, count stays 0.- i = 1: 21 > 20 is true, count 1.
- i = 2: 25 > 20 is true, count 2.
- i = 3: 19 > 20 is false, count stays 2.
- i = 4: 22 > 20 is true, count 3. The last index is 5 − 1 = 4; the loop ends. The result is 3 days.
In this example there is a decision inside the loop. The loop visits every element, and the decision chooses which element gets counted.
4.3.6.8Libraries and APIs
Taking a square root, sorting a list, or reading a file are jobs every programmer often needs. If every programmer had to write them from scratch, it would waste time and be a source of bugs. For this reason languages come with ready-made, tested functions.
A library is a collection of ready-made functions that others have written and tested. An API (application programming interface) defines the functions a library or a service exposes to the outside, along with their inputs and return values.
An API is like a contract (Figure 4.3.30). The API of the square root function says three things: the function's name, that it takes a number, and that it returns the square root of that number. Which method is used inside the function and how floating-point details are handled do not concern the user. Even if the library's authors replace the inside with a faster method, programs that use it keep working unchanged as long as the API stays the same.
| Call | Language | Result |
|---|---|---|
Math.sqrt(16) | Java | 4.0 |
Math.max(3, 8) | Java | 8 |
len("Giresun") | Python | 7 |
The results in the table were taken from real runs. In Java, Math.sqrt always returns a double; that is why 4.0 is printed, not 4. In Java the length of a string is found not with a function but with the string's own method: "Giresun".length().
public class Libraries {
public static void main(String[] args) {
System.out.println(Math.sqrt(16));
System.out.println(Math.max(3, 8));
System.out.println("Giresun".length());
}
}4.0
8
7import math
print(math.sqrt(16))
print(max(3, 8))
print(len("Giresun"))4.0
8
7The concept of an API is not limited to libraries. A weather app calls the API that a meteorological service offers over the network: it sends the city name and gets the temperature. The people who wrote the app do not know what goes on in that service's servers; they only read the API's documentation.
Using a library function without knowing its return type. In Java, Math.sqrt(16) returns 4.0; assigning the result to an integer with int k = Math.sqrt(16); gives a compile error, because a double value is not converted to int automatically. The API documentation states what each function takes and returns; look before using it.
4.3.7Debugging
Every programmer makes mistakes; what sets an experienced programmer apart is knowing an orderly way to find the error. Finding and removing an error in a program is called debugging.
4.3.7.1Debugging techniques
Debugging is not a guessing game but an investigation that proceeds step by step. The following techniques are the tools of this investigation.
- Reproduce the bug. Does the same input trigger the error every time? Starting the search before finding an input that brings out the error on demand is wasted effort. This input is also needed to check that the error is really gone after the fix.
- Print intermediate values. Before and after the suspicious line, the values of the variables are printed to the screen. The first place where the expected and the actual value part ways is the location of the bug.
- Set a breakpoint. In the debugger, a breakpoint is placed on a line. The program stops when it reaches that line, and all the variables at that moment can be inspected.
- Step through. After the program stops, it is advanced line by line. After each line, look at which value has changed.
- Narrow the search. Half of the code is temporarily disabled and you find which half contains the bug. Then that half is split in two again. In a hundred lines of code, the bug comes down to a single line in seven splits, because 27 = 128 ≥ 100.
- Explain it aloud. Explaining the code line by line to someone, even to a toy on the desk, often reveals the bug. While explaining you say "this line does this," and suddenly you notice that the line actually does something else.
Figure 4.3.31 imitates the look of a debugger. The program has stopped at the breakpoint on line 4 and has not yet run that line. The variables panel shows the three grades. The line is avg ← g1 + g2 + g3 / 3. When the "Step" button is pressed, first g3 / 3 = 30 is computed, then 70 + 85 + 30 = 185. The average comes out as 185; the expected value is 245 / 3 ≈ 81.67. The debugger shows at a glance that the problem lies in the order of the division and the addition.
Hiding the symptom of a bug without finding its cause. Because the average comes out as 185, dividing the result by 2.27 gives about 81.5 for this input but produces a wrong result for every other input. The fix is made at the root cause of the bug: the missing parenthesis is added.
4.3.7.2Finding bugs by tracing
The following pseudocode was written to find the largest of three numbers. The variable max holds the "largest" value:
read a, b, c
max ← 0
if a > max then max ← a
if b > max then max ← b
if c > max then max ← c
print "Largest: ", maxFor the first test, 7, 12, and 5 are chosen; the expected output is 12. Table 4.3.19 traces the program.
| Line | Condition | max |
|---|---|---|
max ← 0 | — | 0 |
if a > max | 7 > 0 → true | 7 |
if b > max | 12 > 7 → true | 12 |
if c > max | 5 > 12 → false | 12 |
print | — | Output: Largest: 12 ✓ |
The output is the same as expected. But a single successful test does not prove the program correct. The second test tries a boundary case: let all the numbers be negative, −5, −2, and −9. The expected output is −2 (Table 4.3.20).
| Line | Condition | max |
|---|---|---|
max ← 0 | — | 0 |
if a > max | −5 > 0 → false | 0 |
if b > max | −2 > 0 → false | 0 |
if c > max | −9 > 0 → false | 0 |
print | — | Output: Largest: 0 ✗ |
All three comparisons are false, because no input is greater than 0; max never changes and the output is 0 (Figure 4.3.32). None of the inputs is 0. The trace points to the culprit: the initial value on line 2 comes from outside the inputs. 0 is not an initial value that is "no larger than any number"; it works only for positive numbers.
The fix is to take the initial value from one of the inputs: max ← a. Because max now starts with an input, the result is always one of the inputs. There is also no need to compare a with itself. The corrected program is traced again with Test 2: max starts at −5; −2 > −5 is true, max = −2; −9 > −2 is false. The output is −2 ✓. After a fix, the earlier tests must be repeated too, because the fix may have broken a case that worked before. Test 1 is tried again and still gives 12.
The buggy and corrected Java versions of the same program were run with the same inputs:
import java.util.Scanner;
public class LargestBuggy {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
int max = 0;
if (a > max) max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println("Largest: " + max);
}
}Outputs for the inputs 7 12 5 and −5 −2 −9:
Largest: 12Largest: 0import java.util.Scanner;
public class Largest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
int max = a;
if (b > max) max = b;
if (c > max) max = c;
System.out.println("Largest: " + max);
}
}The corrected version for the same two inputs and an input with equal values (3, 3, 1):
Largest: 12Largest: -2Largest: 3Which test inputs should be chosen for the corrected largest-number program? What does each test?
- Inputs in which the largest number is in each of the three positions: (12, 7, 5), (7, 12, 5), (7, 5, 12). A typo in one comparison line shows up only when the largest value is in that position.
- All negative: (−5, −2, −9). It catches the initial value error.
- Equal values: (3, 3, 1) and (4, 4, 4). Writing
>=instead of>would not change the result, but the case of equality is at least exercised. - An input containing zero: (0, −1, −3). The expected result is 0; the buggy version also gives 0. This test alone cannot catch the buggy version; it is a case in which the wrong initial value happens to give the right result.
4.3.7.3Common mistakes
Some mistakes are made so often that they have names. Table 4.3.21 lists them with examples and consequences.
| Mistake | Example | What happens? |
|---|---|---|
| Missing or wrong initial value | total ← total + x without initializing total | Java refuses to compile; in some languages the computation uses a random value |
| Off-by-one error (one too few / one too many) | for i ← 1 to n − 1 | The last element is skipped, or one extra iteration runs |
| Infinite loop | The loop variable is not updated in the body | The program never ends |
| Division by zero | avg ← total / n, n = 0 | Runtime error |
| Going outside the array | grades[4] in an array of 4 elements | Runtime error |
| Forgetting parentheses | avg ← a + b / 2 | Wrong result (logic error) |
| Not validating input | Accepting −3 as an age | A meaningless result, errors in later steps |
Languages behave differently on the initial-value mistake. Java does not allow a local variable that has not been given a value to be read:
public class Uninitialized {
public static void main(String[] args) {
int total;
total = total + 5;
System.out.println(total);
}
}Uninitialized.java:4: error: variable total might not have been initialized
total = total + 5;
^
1 errorIn C, the same code compiles. A local variable that has not been given a value holds whatever happens to be in memory at that moment, and the program may give a different result on every run. Java's strictness is a safeguard here: it moves the error from run time to compile time.
The off-by-one error is among the most insidious mistakes. If you write for i ← 1 to n − 1 when you want the sum from 1 to n, n is skipped. For n = 5 the total comes out as 1 + 2 + 3 + 4 = 10 instead of 15. The program runs, the result looks "plausible," and the error is easily overlooked.
Most of these errors show up with edge cases: 0, an empty list, the smallest and largest values, a negative number. A program that works on normal inputs often breaks at the boundaries. For this reason every test set should contain a few edge cases.
A program computes the average of the entered grades with avg ← total / n. Which edge cases should be tried, and which error can each reveal?
- No grades entered (n = 0): division by zero. The program is fixed to print "no grades entered" when n = 0.
- A single grade (n = 1): the average must be the grade itself. If the loop bound is off by one, the result comes out 0.
- The smallest and largest grades (0 and 100): the input check must not reject these values by mistake; for example,
grade ≥ 0should be written rather thangrade > 0. - An invalid grade (−5 or 120): the program must not accept this value.
- A fractional result (70, 85, 90): the average should come out around 81.67. If there is integer division, 81 comes out.
4.3.7.4The cost of software bugs
A bug in an assignment results in a low grade. The cost of bugs in real systems can be millions of dollars, even human lives. Three famous examples show the real-world counterparts of the kinds of errors described in this note.
Ariane 5 (1996). On its first flight, the European Space Agency's new rocket Ariane 5 veered off course about 37 seconds after liftoff and broke apart within seconds. According to the inquiry board's report, the cause was a number conversion. The navigation software was converting a 64-bit floating-point horizontal velocity value into a 16-bit signed integer. A 16-bit signed integer can hold at most 32,767. The software had been taken from the slower-climbing Ariane 4, where this limit was never exceeded. Ariane 5's horizontal velocity was much larger, the conversion raised an overflow error, and the navigation system shut down.
What happens in Java if a double with the value 40000.0 is forcibly converted to the 16-bit short type?
public class Overflow {
public static void main(String[] args) {
double speed = 40000.0;
short narrow = (short) speed;
System.out.println(narrow);
System.out.println(Short.MAX_VALUE);
}
}-25536
32767The largest value of the short type is 32,767. 40,000 exceeds this limit. Java gives no error; it keeps only the last 16 bits of the number's binary representation. Because 16 bits can hold 216 = 65,536 different values, the result is 40,000 − 65,536 = −25,536. A positive speed has silently turned into a negative number. Ariane 5's software was written in the Ada language and, instead of staying silent on overflow, it raised an error. But there was no code to catch and handle that error, and the system shut down. In both cases the root cause is the same: it was never tested whether the value could leave the range the type can hold.
Mars Climate Orbiter (1999). The probe NASA sent to Mars came too close to the planet while entering orbit and was lost. Software at the ground station produced the effect of the thrusters in English units (pound-force seconds). The other software that used this data expected metric units (newton-seconds). One pound-force second is about 4.45 newton-seconds. As a result, the effect of the thrust was computed about 4.45 times too small, and the orbit calculation drifted gradually over the journey of more than nine months. Each of the two programs worked correctly on its own; the bug was in the interface between them.
Therac-25 (1985–1987). The software of a radiotherapy machine used in cancer treatment had a timing bug. When the operator entered settings in a particular order and very quickly, the safety check was skipped. In earlier models hardware interlocks also performed this check; in the Therac-25 this job was left to software alone. In six accidents between 1985 and 1987, patients received radiation doses far above normal; at least three patients died.
All three bugs are of the kind a compiler cannot catch. One is an edge case, one a unit inconsistency, one a timing-dependent logic error. The shared lessons can be gathered in a few points. Edge cases must be tested, and units must be stated clearly in variable names and documentation. Software taken from one system must be retested under the conditions of the new system, and code should be reviewed by someone else.
Not stating the unit in the variable name. From the code you cannot tell whether a variable named speed is in km/h or m/s. Names such as speedKmh or speedMs prevent two programmers from interpreting the same number in different units. The loss of Mars Climate Orbiter shows the value of this small habit.
4.3.7.5Readable code
Code is written once and read many times. It is read by its own author weeks later, by teammates, and by others who take over maintenance. Readable code both prevents bugs and makes them easier to find. The following two pieces of pseudocode do the same job.
It works but is unreadable:
a ← read()
b ← read()
c ← a*b/2
print cThe same program, readable:
// area of a triangle = base × height / 2
base ← read()
height ← read()
area ← base × height / 2
print "Area: ", areaWhoever reads the first program has to work out the formula to understand what c is; a*b/2 could be a triangle's area, or a mistyped average computation. The second program explains itself. The differences are these:
- Meaningful names. area is written instead of c, and base instead of a. The reader understands a variable's role from its name.
- Consistent indentation and spacing. The spaces around operations and the regular indentation of nested blocks show the boundaries of the structure at a glance.
- Named constants instead of magic numbers. A number embedded in the code whose meaning is not explained is called a magic number. Instead of
price * 0.20, defineVAT_RATE ← 0.20and writeprice * VAT_RATE. When the rate changes, a single line is corrected. - Moving repetition into a function. If the same formula is written in three places, one fix must be made three times, and one of them will surely be forgotten.
- Comments. A comment says not what the code does but why it does it. The comment
// add 1 to xrepeats the code and adds nothing. The comment// the array starts at 0, add 1 for the ordinal number, however, explains an intention.
What is the Java version of the readable triangle area program? What are the outputs for base 6, height 5 and base 7, height 3?
import java.util.Scanner;
public class TriangleArea {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// area of a triangle = base × height / 2
double base = in.nextDouble();
double height = in.nextDouble();
double area = base * height / 2;
System.out.println("Area: " + area);
}
}Area: 15.0Area: 10.56 × 5 / 2 = 15 and 7 × 3 / 2 = 10.5. Because the variables are double, the second result comes out right with its fractional part. If int had been used, the integer division 21 / 2 would have given 10. The use of a named constant is written in a similar way:
public class VatDemo {
static final double VAT_RATE = 0.20;
public static void main(String[] args) {
double price = 250.0;
double vat = price * VAT_RATE;
System.out.println("VAT: " + vat);
System.out.println("Total: " + (price + vat));
}
}VAT: 50.0
Total: 300.0For a product costing 250 TL, the VAT is 250 × 0.20 = 50 TL and the total is 300 TL. If the rate changes, only the VAT_RATE line is changed.
Thinking short names make code faster or smaller. The compiler does not carry names into machine code; c and triangleArea run at the same speed. The only effect of short names is to make the reader's job harder. Short, well-established uses such as the loop counter i are the exception.
4.3.8Summary
- A programming language is a formal language that expresses an algorithm in a form a computer can execute. Syntax determines what may be written, and semantics what the written text does. A program with correct syntax can do the wrong job.
- Source code is the text people read; machine language is the binary instructions the processor runs; assembly is the symbolic notation of machine instructions. One high-level line often corresponds to several machine instructions.
- Source code is run in three ways. In compiled languages (C) the program is translated to machine code beforehand. In interpreted languages (Python) commands are evaluated at run time. In hybrid languages (Java) the source code is compiled to bytecode and the bytecode is executed on a virtual machine (the JVM). A JIT compiler translates frequently run code into machine code at run time. The compiled/interpreted distinction is a property of the implementation, not of the language.
- There are three kinds of errors. A compile error is found during translation, and the program never runs. A runtime error stops the program during execution. A logic error gives no error message, produces a wrong result, and is found only by testing.
- A compiler works in five phases: lexical analysis (tokens), syntax analysis (syntax tree), semantic analysis (names and types), intermediate code and optimization (e.g. constant folding), and code generation. The first three phases look for errors. The linker combines object files and libraries, and the loader brings the program into memory and starts it.
- Languages are classified by level (low: machine language, assembly; high: C, Java, Python), by kind (general-purpose, domain-specific, scripting, markup), and by paradigm (imperative, object-oriented, functional). Level is not a measure of quality but of abstraction. The choice of language is determined by the problem area, the platform, libraries, performance, security, and team experience.
- In static typing (Java), type errors are found at compile time; in dynamic typing (Python), when the line in question runs.
- The path from problem to program: define the problem (input, output, constraints), solve examples by hand, build the algorithm, convert it to code, and test. If testing finds a gap, return to an earlier stage.
- The software development process is an iterative process made up of requirements, design, coding, testing, deployment, and maintenance. The waterfall model passes through the stages once, in order. The agile approach proceeds in short cycles. Prototyping makes vague requirements visible. The IDE, compiler, debugger, version control, testing tools, and package manager are the tools of this process.
- Variables, decisions, loops, functions, and arrays are the basic programming constructs. Operator precedence is as in mathematics. For a loop to end, the body must affect the condition. Every function call opens its own frame on the call stack. Array indices start at 0, and the last index is length − 1.
- Bugs are found by testing with edge cases (0, an empty list, a negative number, the smallest and largest values) and by tracing the program step by step with a trace table. Readable code (meaningful names, named constants, functions, comments that explain "why") both prevents bugs and makes them easier to find.
4.3.9Key terms
The key terms of this chapter are listed below.
- programming language
- syntax
- semantics
- source code
- machine language
- machine code
- assembly language
- translator
- compiler
- compilation
- interpreter
- interpretation
- compiled / interpreted
- bytecode
- intermediate code
- virtual machine
- Java Virtual Machine (JVM)
- just-in-time (JIT) compiler
- compile error
- syntax error
- runtime error
- logic error
- lexical analysis
- token
- parsing
- syntax tree
- semantic analysis
- code optimization
- constant folding
- object file
- linker
- linking error
- loader
- executable file
- class loader
- high-level / low-level language
- domain-specific language
- scripting language
- markup language
- programming paradigm
- imperative programming
- object-oriented programming
- functional programming
- static typing
- dynamic typing
- waterfall model
- agile
- prototyping
- integrated development environment (IDE)
- debugger
- breakpoint
- package manager
- version control
- commit
- branch
- merge
- merge conflict
- data type
- operator precedence
- infinite loop
- parameter
- argument
- call stack
- array
- index
- library
- application programming interface (API)
- off-by-one error
- magic number
4.3.10Test Yourself
What kind of error is each of the following Java errors? If it is a compile error, in which phase of the compiler is it caught? (a)
System.out.println("Hello);(b) Using an undeclared variabletotal. (c) A loop that runs with the conditioni <= nover an array of n elements. (d) Dividing the total by n − 1 when computing an average.Answer
(a) A compile error; because the unclosed string cannot be turned into a token, it is caught in the lexical analysis phase (javac: "unclosed string literal"). (b) A compile error; whether a name has been declared is checked in the semantic analysis phase ("cannot find symbol"). (c) A runtime error; in the last iteration i = n and
array[n]is outside the array, so Java throwsArrayIndexOutOfBoundsException. (d) A logic error; the program runs with every input but finds the average larger than it is.A three-line Python file reads:
print("A"),print(1 / 0),print("B"(the parenthesis on the last line is unclosed). What appears on the screen when the file is run? What would a simple line-by-line interpreter have shown?Answer
Python parses the whole file before it starts running. It finds the unclosed parenthesis on line 3 and gives only the message
SyntaxError: '(' was never closed. "A" is not printed, and the division by zero is never reached. A simple line-by-line interpreter would print "A" first, stop at the division by zero on the second line, and never see the syntax error on the third line.Into how many tokens is the line
total = total + 1;split in lexical analysis? What are the types of the tokens?Answer
Six tokens:
total(identifier),=(operator),total(identifier),+(operator),1(constant),;(separator). Whitespace is discarded. Because the same name appears twice, it counts as two separate tokens.What does the following pseudocode print? How many times does the body run, and how many times is the condition checked?
s ← 0;i ← 1;while i ≤ 4: s ← s + i × i; i ← i + 2;print s.Answer
Iteration 1: 1 ≤ 4 is true; s = 0 + 1 × 1 = 1, i = 3. Iteration 2: 3 ≤ 4 is true; s = 1 + 3 × 3 = 10, i = 5. Check: 5 ≤ 4 is false, and the loop ends. 10 is printed. The body runs 2 times and the condition is checked 3 times. Because multiplication is done before addition, no parentheses are needed in
s + i × i.function f(x): return 2 × x + 1is defined. What doesprint f(f(2))print? How many frames are opened, and are the two on the stack at the same time?Answer
The inner call runs first: a frame is opened for f(2), x = 2, 2 × 2 + 1 = 5 is returned, and the frame closes. Then a new frame is opened for the outer call f(5): 2 × 5 + 1 = 11. 11 is printed. Two frames are opened but they are not on the stack at the same time: the outer call starts after its argument has been computed and the inner frame has closed.
In Java, what is s after the line
int s = 17 % 5 * 2 + 9 / 2;? Write out the order of computation.Answer
%,*, and/are at the same precedence level and are done before addition, from left to right. 17 % 5 = 2, 2 × 2 = 4. Then 9 / 2 is 4, because it is the quotient of two integers (not 4.5). Finally 4 + 4 = 8. s = 8.A Python function returns
"a" + 5if x is greater than 10 and"small"otherwise. The program callsmessage(3)and thenmessage(20). When does the error show up? What would happen if the same logic were written in Java?Answer
Python parses the file without trouble, because the syntax is correct.
message(3)returns "small" and it is printed. At the callmessage(20)the faulty line runs for the first time and raises aTypeError. In dynamic typing a type error is seen only when the line runs; if x never exceeded 10, the error would never be seen. In Java, in a method whose return type isString,"a" + 5is string concatenation and is valid: it returns "a5". If the return type wereint, the compiler would report the type mismatch before the program ever ran.A program to find the smallest element of an array starts with
min ← 0and compares each element withif d[i] < min then min ← d[i]. What is the output for d = [3, 8, 1, 6]? What is the bug, and how is it fixed?Answer
None of the four comparisons is true: none of 3, 8, 1, and 6 is less than 0. min never changes and the output is 0; the correct result is 1. The bug is in the initial value: 0 is a value from outside the inputs and acts like the smallest value for positive numbers. The fix is
min ← d[0]. Trace: min = 3; 8 < 3 is false; 1 < 3 is true, min = 1; 6 < 1 is false. The output is 1.
4.3.11Further reading
- A. B. Downey, C. Mayfield, Think Java (2nd ed., O'Reilly, 2019): an introduction to programming with Java; its first chapters cover compilation, interpretation, kinds of errors, and debugging at the level of this note. It can be read free of charge on the Green Tea Press website.
- R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016): teaches programming in Java through science and engineering examples; it has plenty of examples for variables, loops, functions, and arrays.
- R. W. Sebesta, Concepts of Programming Languages (12th ed., Pearson, 2019): compares in detail the history of languages, the description of syntax and semantics, type systems, and paradigms.
- A. V. Aho, M. S. Lam, R. Sethi, J. D. Ullman, Compilers: Principles, Techniques, and Tools (2nd ed., Addison-Wesley, 2006): the standard source on the phases of a compiler; for those who want to go deeper into lexical analysis, parsing, and code optimization.
4.3.12References
- R. W. Sebesta, Concepts of Programming Languages, 12th ed., Pearson, 2019.
- A. V. Aho, M. S. Lam, R. Sethi, J. D. Ullman, Compilers: Principles, Techniques, and Tools, 2nd ed., Addison-Wesley.
- R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016.
- A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online version).
- Oracle, The Java Tutorials: Getting Started.
Related pages: Chapter 4.3 slides · Study questions · Java Compile and Run simulator · Glossary · © Sercan Külcü. All rights reserved.