Object-Oriented Programming with Java · Lecture Notes

Chapter 2.1: Programming

However precisely an algorithm is written on paper, a computer can run it only once it is expressed in a programming language. A programming language is the bridge between the solution a person has in mind and the operations a machine performs, and these notes describe how that bridge is built. The first sections classify languages by level of abstraction, application area, execution model, and paradigm, and explain how Java compiles source code to bytecode and runs it on a virtual machine. Next come the three layers of every language: syntax, static semantics, and semantics. These layers also separate compile-time errors, run-time errors, and logic errors. The following sections show how expressions are evaluated by operator precedence, how integer division works, what static and dynamic typing mean, how operations across types behave, and how string concatenation proceeds. The last section turns an algorithm into a Java program, distinguishes expressions from statements, and shows how statement order determines the result.

Learning outcomes

Programming languages
Define a programming language and classify languages by level of abstraction, application area, execution model, and paradigm.
How Java runs
Explain how source code is compiled to bytecode by javac and executed by the JVM.
Syntax and semantics
Distinguish syntax, static semantics, and semantics; recognize compile-time, run-time, and logic errors.
Expressions
Find the value of an expression using operator precedence, left-to-right evaluation, and integer division.
Variables and types
Declare variables and trace an assignment in two steps; explain static and dynamic typing and operations across types.
From algorithm to program
Tell an expression from a statement; translate an algorithm into a Java program and show why statement order matters.

2.1.1Programming languages

People talk to each other in natural languages. English, Turkish, and German are rich languages: the same thought can be put many ways, and the listener fills in whatever is left out from context. A computer does no such filling in. Every instruction it receives must be read in exactly one way and mean exactly one thing. Programming languages were born from that need. This section defines a programming language and classifies languages by four criteria: level of abstraction, application area, execution model, and paradigm. Paradigms get a section of their own.

2.1.1.1What is a programming language?

Definition 2.1.1

A programming language is an artificial language designed to express computations that a machine can carry out. Text written in such a language is a program, and a program in the form in which it is written is called source code.

The word “artificial” matters. Natural languages develop on their own over centuries, and their rules are written down afterwards by observation. Programming languages are designed up front. A document fixes precisely which words may be used, in what order they may be arranged, and what each arrangement means. For Java that document is The Java Language Specification.

A programming language serves two purposes. The first is to write programs that control the behavior of a machine, which requires algorithms to be expressed clearly and exactly. The second is easier to overlook: a program is a means of communication between programmers. Someone else will read the code years later, change it, or hunt for a bug in it. A good program does not merely run correctly; it is also easy to read.

Computers, phones, and embedded devices get their functions from programs. The washing steps of a washing machine, the decisions of a car’s brake control system, and the response to every touch on a phone screen are all instructions written in a programming language. In that sense a programming language is the written form of algorithms and logical processes.

Problemdescribed in wordsdesignAlgorithmprecise stepscodeProgramcode in, e.g., JavarunMachineruns instructions
Figure 2.1.1: From problem to machine. A description in everyday language becomes an algorithm, the algorithm becomes a program, and the program runs on the machine.

Figure 2.1.1 shows the four stops along this path. Each step has its own difficulty. Going from problem to algorithm removes ambiguity and breaks the solution into precise steps. Going from algorithm to program writes those steps according to the rules of a language. Going from program to machine is handled by helper programs called compilers or interpreters. Most of these notes concern the second step: how to write an algorithm correctly in Java, and what the code you have written actually means.

There are many languages: C, C++, Java, Python, Prolog, Haskell, Scala, and hundreds more. None is best for every job, so the choice depends on the needs of the project. Speed, reliability, development time, the hardware to be used, and the experience of the team all play a part. The next subsections give classifications that help with this choice.

2.1.1.2Levels of abstraction

A processor understands only its own instruction set. These instructions are encoded as binary numbers, and each does something very small: it moves a value from one register to another, adds two registers, or reads a word from memory. The form the processor executes directly is called machine language or machine code. Machine language is specific to a processor family; the machine code of an Intel processor does not run on an ARM processor.

Definition 2.1.2

A low-level language is close to the hardware: each line written in it corresponds to one or a few processor instructions. Machine language and assembly language belong to this group. A high-level language hides the details of the hardware, and the programmer thinks in terms of variables, expressions, loops, and methods. Java, Python, and C# are high-level languages.

Assembly language gives readable abbreviations to machine instructions. Names such as ADD, MOV, and LOAD replace the binary codes. Even so, each line still corresponds to a single machine instruction. A simple operation such as a = b + c takes roughly three lines of assembly: load b into a register, add c, and store the result at the memory address of a. In Java the same job is a single line, and the programmer does not care which register is used.

As the level of abstraction rises, programs become shorter and more readable, and they are easier to move to other hardware. In exchange, the programmer gives up some control over the hardware. In electrical and electronics engineering both ends have their place. A microcontroller’s interrupt routine, or a driver with a very tight timing constraint, is sometimes written in assembly or C. An application that processes measurement data, has a user interface, or communicates over a network is usually written in Java or Python.

Table 2.1.1: Comparison of levels of abstraction.
LevelExampleWhat does one line correspond to?Portability
Machine languagebinary instruction codesa single processor instructiononly that processor family
AssemblyADD, MOVa single processor instruction (with a readable name)only that processor family
High levelJava, Python, C#many processor instructionsanywhere there is a compiler or virtual machine

C sits somewhere in the middle of this classification. It is a high-level language, but it allows memory to be accessed by address and low-level code to be written. That is why it is so common in embedded systems. Java, by contrast, keeps the programmer entirely away from memory addresses and leaves memory management to a component called the garbage collector.

2.1.1.3General-purpose and domain-specific languages

The second way to classify languages is by application area.

Definition 2.1.3

A general-purpose language offers a broad core set of commands that supports a wide variety of applications. A domain-specific language focuses on a particular kind of application and makes the operations of that kind easy.

Java, C, C++, and Python are general-purpose languages. The same language can be used to write a desktop program, a web server, a mobile app, or an embedded system. Two familiar domain-specific languages are MATLAB and SQL. MATLAB is designed for numerical computing: matrix and vector operations are built into the language and optimized to run fast. SQL (Structured Query Language) is for requesting data from a database and updating it.

The same task shows the difference best. Multiplying two n × n matrices is a single line in MATLAB:

C = A * B;   % one line

In Java the same job takes three nested loops written by hand:

for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
        for (int k = 0; k < n; k++)
            C[i][j] += A[i][k] * B[k][j];

In the Java code the innermost line builds the sum Cij = Σk Aik · Bkj step by step. The two outer loops walk over every cell of the result matrix, and the innermost loop adds up the products for that cell. The notation C[i][j] += … means “add to C[i][j]”; it assumes the array C starts out filled with zeros, which holds in Java because the elements of a newly created double array are already 0.0.

The costs of the two versions differ as well. Three nested loops of n iterations each perform n3 multiplications and additions in total. The A * B in MATLAB ends up doing a similar number of operations, but it hands them to a ready-made library that uses the cache well and often runs in parallel. A domain-specific language is therefore both shorter and, in its own area, often faster. The price is flexibility: writing a web server in MATLAB is much harder than writing one in Java.

Common mistake

Writing C = A * B; in Java out of MATLAB habit. In Java the * operator is defined only for numbers; it does not know how to multiply two arrays. The compiler rejects the line with the message bad operand types for binary operator '*'. In Java, matrix multiplication is done either with loops or with a library method.

2.1.1.4Compiled and interpreted languages

The third classification looks at how source code is executed. A processor does not understand source code directly; the code must first be translated into machine language. There are two basic ways to do this.

Definition 2.1.4

A compiler is a program that translates the whole source code into another language, usually machine code, before the program is run. An interpreter reads the source code and executes its commands one after another, on the spot; it does not produce a complete translation in advance. By these two routes languages are called compiled or interpreted.

Source codeCompilertranslates onceMachine codeexecutable fileRun Source codeInterpreterread a line, run itOutput
Figure 2.1.2: Execution models. Top: a compiled language (C, C++, Go, Rust): the compiler translates the source code to machine code in one pass, and the resulting executable file is run afterwards. Bottom: an interpreted language (Python, JavaScript): the interpreter reads the source code line by line and executes it directly.

Figure 2.1.2 puts the two routes side by side. In a compiled language the translation is done once and the result is written to a file; a Windows .exe file is such an output. The program is not translated again each time it runs, and the machine code goes straight to the processor. Because the compiler sees the whole program at once, it can optimize the code: it discards unnecessary operations and keeps frequently used values in registers. Compiled programs are therefore generally fast.

An interpreted language has no separate translated file. The interpreter keeps running alongside the program, decoding and carrying out each command when its turn comes. This approach gives flexibility: code can be tried as soon as it is written, and new commands can even be entered while the program runs. The price is speed. If the same loop runs a thousand times, the interpreter decodes the same line a thousand times.

Table 2.1.2: Comparison of compiled and interpreted languages.
CompiledInterpreted
How?All of the source code is translated into object code or machine code by the compiler before the program runs.The interpreter reads the source code and executes the commands one after another on the spot.
SpeedFast, optimized executionGenerally slower
ErrorsMany are found during compilationMost show up only when the line is executed
DistributionA separate build is needed for each operating system and processorThe same source code runs anywhere there is an interpreter

The third row of the table may be the most important difference for a programmer. The compiler reads the whole program before it runs. A misspelled word, a missing parenthesis, or an incompatible operation is caught in that reading, and the program never runs at all. In an interpreted language a faulty line goes unnoticed until the flow of the program reaches it. A Python program can run without trouble for an hour and then stop because of a typo in an if branch that is rarely taken.

2.1.1.5Java’s path: bytecode and the JVM

Java combines the two approaches. The source code is compiled first, but not directly to the machine code of a particular processor: it is compiled to an intermediate code called bytecode. The Java Virtual Machine (JVM) then executes this intermediate code.

Definition 2.1.5

Bytecode consists of platform-independent instructions produced by the Java compiler javac and stored in .class files. The JVM is the virtual machine that interprets bytecode and translates its frequently executed parts to machine code at run time with a JIT compiler (just-in-time compiler).

A Java program is run with two commands: the first compiles, the second executes.

> javac Paradigm.java      (creates Paradigm.class)
> java Paradigm
Imperative: 15
Functional: 15

The command javac Paradigm.java reads the source file. If there are no errors, it creates Paradigm.class in the same folder. The command java Paradigm starts the JVM and has it load that class. Note that the second command has no file extension: the JVM is given a class name, not a file name.

You can see what bytecode looks like with the javap -c tool that ships with the JDK. Here is a small method that adds two integers:

static int add(int a, int b) {
    return a + b;
}

javac translates this method into the following four bytecode instructions:

static int add(int, int);
  Code:
     0: iload_0
     1: iload_1
     2: iadd
     3: ireturn

The instructions operate on a stack. iload_0 pushes the first parameter (a) and iload_1 the second (b). iadd takes the two integers on top of the stack, adds them, and pushes the result back. ireturn returns the value on top of the stack as the method’s result. The leading i in each instruction shows that it works with int. These instructions belong to no real processor; they are an abstract instruction set defined for the JVM.

This intermediate layer has a great benefit. The same .class file runs unchanged on Windows, Linux, or macOS, on an Intel or an ARM processor. A separate JVM has been written for each platform, while the program is compiled only once. The slogan used when Java was introduced, “write once, run anywhere,” describes this property.

The JIT compiler solves the speed problem. The JVM first runs the program by interpreting it, and counts which methods are called often. A method that runs frequently is compiled at run time into the real machine code of that machine, and later calls run directly on the processor without interpretation. As a result, long-running Java programs reach speeds close to those of compiled languages. For short programs, the JVM’s startup time is noticeable.

Java’s compilation step also keeps the most important advantage of compiled languages. javac reads the whole program, checks the types, and never produces a .class file for a faulty program. A misspelled variable name or a string assigned to a number is caught before the program runs. Other languages, such as Kotlin and Scala, also compile to JVM bytecode; they share the same virtual machine and Java’s libraries.

Common mistake

Trying to run the program as java Paradigm.class, or with a file whose name differs from the class name. The java command expects a class name; if you write the .class extension, the JVM looks for a class called Paradigm.class and cannot find it. Also, the source file of a public class must have the same name as the class: public class Paradigm compiles only in a file named Paradigm.java.

2.1.2Programming paradigms

Two programmers can solve the same problem in very different ways, even in the same language, and languages themselves are designed to make one way of solving problems easier than another. The way of thinking a language favors is described by its paradigm. This section introduces four basic paradigms and illustrates each with a short program.

2.1.2.1The idea of a paradigm

Definition 2.1.6

A programming paradigm is a fundamental approach to solving a problem. A paradigm determines what a program consists of (commands, functions, rules, or objects) and how the computation proceeds.

Four paradigms are mentioned often in this course. Table 2.1.3 summarizes them.

Table 2.1.3: Four basic programming paradigms.
ParadigmCore ideaExample languages
ImperativeThe programmer tells the machine, step by step, how to change its state.FORTRAN, BASIC, Pascal, C
FunctionalComputation is the evaluation of mathematical functions; changing state is avoided.Lisp, Scheme, Haskell
LogicThe logic of the computation is described with facts and rules; the flow of control is not spelled out.Prolog
Object-orientedRelated data and methods are gathered under an object; commands are grouped together with the state they work on.C++, Java, C#, Python

The word “state” in the table is the key to telling the paradigms apart. State is the values of a program’s variables at a given moment. In an imperative program these values change at every step, and the result is the sum of those changes. In a functional program values are computed once and never changed; the result comes from composing functions. In a logic program the programmer writes neither steps nor functions, only what is true. In an object-oriented program state does not disappear; it is placed inside objects.

Languages that support more than one paradigm are called multi-paradigm languages. Java is fundamentally object-oriented and imperative. Since Java 8 it also includes functional elements such as lambda expressions and streams. Python and C# are multi-paradigm as well. A paradigm is therefore often a property not of a language but of a program, or of a part of a program.

2.1.2.2Imperative and functional: the same problem

The problem is simple: find the sum of the numbers from 1 to 5. The Java program below computes it in two ways.

import java.util.stream.IntStream;

public class Paradigm {
    public static void main(String[] args) {
        // Imperative: change state step by step
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum = sum + i;
        }
        System.out.println("Imperative: " + sum);

        // Functional (Java 8+): say what you want
        int result = IntStream.rangeClosed(1, 5).sum();
        System.out.println("Functional: " + result);
    }
}

When the program runs, both ways give the same result:

Imperative: 15
Functional: 15

The imperative part spells out how the sum is found. A variable named sum starts at 0. The for loop counts i from 1 to 5 and on each pass updates sum with the statement sum = sum + i. The result is whatever value remains in the variable after five updates. Here the programmer thinks in the machine’s place: which variable changes, in what order, and how?

The functional part states what is wanted. IntStream.rangeClosed(1, 5) produces a stream of the numbers 1, 2, 3, 4, and 5; the word closed says the upper bound is included. .sum() adds up all the numbers in that stream. No variable is updated step by step in the code; result is assigned only once, with its final value. The order in which the additions happen is left to the library.

The first line of the program, import java.util.stream.IntStream;, tells the compiler where the IntStream class lives. Without it the compiler would not recognize the name IntStream and would report cannot find symbol. Classes such as System and String are in the java.lang package, so they need no import.

2.1.2.3Code trace: the imperative sum

The best way to see how state changes in the imperative approach is to trace the code line by line. Table 2.1.4 gives, for each pass of the loop, the value of the condition and the new value of sum.

Table 2.1.4: Trace of the imperative sum. Each row shows a condition check followed by the body’s execution.
ii <= 5Bodysum
——start0
1true0 + 11
2true1 + 23
3true3 + 36
4true6 + 410
5true10 + 515
6falseloop ends15
values of i12345sum0 values of i12345sum31 + 2 = 3 values of i12345sum15 values of i12345rangeClosed(1, 5).sum() → 15
Figure 2.1.3: Four moments from the trace of the sum program. (a) The state variable sum starts at 0. (b) i = 2: 1 + 2 = 3; the first pass is marked in green. (c) When i becomes 6, 6 <= 5 is false and the loop ends; the sum accumulated over five passes is 15. (d) The functional route: rangeClosed(1, 5) produces the five numbers together and sum() adds them all; no variable is updated step by step.

Three things stand out in the trace. First, the condition is checked six times but the body runs only five times; the last check is the one that ends the loop. Second, when the loop ends i is 6, not 5. Because i is declared in the loop header, it cannot be used after the loop anyway, but the detail matters for understanding off-by-one errors. Third, every intermediate value of sum is the input of the next pass, so a mistake in one pass is carried into all the later ones.

The two routes cost the same. Both perform five additions; for n numbers, n additions are needed. The difference is in how the code is written, not in the amount of work. The last panel of Figure 2.1.3 sums up the difference: the two approaches give the same result, and what differs is whether the code says how to do it or what is wanted.

Example 2.1.1

Write the sum of the numbers from 3 to 6 in both ways.

Imperative: int t = 0; for (int i = 3; i <= 6; i++) t = t + i;. The passes make t equal to 3, 7, 12, and 18 in turn; when i is 7 the condition is false.

Functional: IntStream.rangeClosed(3, 6).sum(). The stream produces 3, 4, 5, 6, and their sum is 18.

Both routes give 18. Had range(3, 6) been written instead of rangeClosed(3, 6), the upper bound would be excluded and the result would be 3 + 4 + 5 = 12.

Common mistake

Forgetting to give the sum variable an initial value. If you write int sum; and then sum = sum + i; in the loop, Java stops compilation with variable sum might not have been initialized. Local variables have no default value. In other languages such a variable may start with a random value and a wrong sum is produced silently; Java catches this error at compile time.

2.1.2.4Logic programming: Prolog

The best-known example of the logic paradigm is Prolog. A Prolog program consists not of steps but of facts and rules. The programmer writes what is true; when a question is asked, Prolog searches for the answer itself.

% facts
parent(ali, ayse).
parent(ayse, can).
% rule
grandparent(X, Z) :- parent(X, Y),
                     parent(Y, Z).
% query
?- grandparent(ali, can).
true.

The first two lines declare two facts: Ali is a parent of Ayşe, and Ayşe is a parent of Can. In Prolog, names that begin with a lowercase letter are constants and those that begin with an uppercase letter are variables. The rule line reads “X is a grandparent of Z if X is a parent of some Y and Y is a parent of Z.” The symbol :- means “if,” and the comma means “and.”

The query ?- grandparent(ali, can). asks “Is Ali a grandparent of Can?” Prolog applies the rule, substituting ali for X and can for Z. It then looks for a Y that satisfies the fact parent(ali, Y) and finds ayse. Finally it checks whether the fact parent(ayse, can) exists. It does, so the answer is true.

None of this search order is written in the program. The programmer built no loop and did not say which fact to try first. In the logic paradigm, control flow is left to the language’s own search method. The same program also answers other questions: the query ?- grandparent(ali, X). means “Whose grandparent is Ali?” and Prolog finds X = can. In an imperative language these two questions would need two separate pieces of code.

2.1.2.5Object-oriented programming: Rectangle

The object-oriented paradigm is the main subject of this course. The basic idea is to gather related data and the operations that work on that data into a single unit. This unit is called an object, and the template for objects is a class.

Definition 2.1.7

Object-oriented programming (OOP) builds a program from objects that combine state (data) and behavior (methods). The variables that hold an object’s data are called fields, and the operations that define its behavior are called methods.

The class below models a rectangle.

public class Rectangle {
    double width, height;          // data (state)

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    double area() {          // behavior
        return width * height;
    }

    public static void main(String[] args) {
        Rectangle d = new Rectangle(3, 4);
        System.out.println("Area: " + d.area());
    }
}
Area: 12.0

The class has four parts:

  • double width, height; declares two fields. Each Rectangle object carries its own width and height; these two values are the object’s state.
  • Rectangle(double width, double height) is a constructor. A constructor has the same name as the class and no return type. It is called once when an object is created and gives the fields their initial values.
  • double area() is a method. It computes the area from the object’s own fields and returns a double value.
  • The main method is the entry point of the program. It creates an object, calls the object’s area() method, and prints the result.

The line this.width = width; inside the constructor looks odd at first. There are two different width names here. The one on the right is the constructor’s parameter and carries the value passed in the call. The this.width on the left is the object’s field. The keyword this means “the object currently being worked on.” When a parameter has the same name as a field, the parameter shadows the field, and you must write this. to reach the field.

In the area() method, by contrast, this is not written: return width * height;. Since the method has no parameter or local variable named width, the name goes straight to the field. Writing return this.width * this.height; would mean the same thing.

Common mistake

Forgetting this in the constructor: width = width;. This line compiles, but it assigns the parameter to itself and the field does not change. The object’s width and height fields stay at the default 0.0 and the program prints Area: 0.0. The compiler reports no error here because the line is valid as far as the language is concerned. This is a logic error.

2.1.2.6Code trace: a Rectangle object

When tracing an object-oriented program, two regions of memory are considered together. The stack holds the frames of method calls and the local variables. The heap is where objects created with new live. The local variable d is on the stack; the Rectangle object it refers to is on the heap.

StackHeapmaind— StackHeapmaind—Rectangle(…)this = •width = 3.0height = 4.0Rectanglewidth = 0.0height = 0.0 StackHeapmaind•Rectanglewidth = 3.0height = 4.0 StackHeapmaind•area()this = •Rectanglewidth = 3.0height = 4.0
Figure 2.1.4: Four moments from the trace of the Rectangle program. (a) main starts; the stack holds the main frame, and d does not yet refer to an object. (b) new allocates the object on the heap and the fields are the default 0.0; in the constructor’s frame this refers to the object and the parameters are 3.0 and 4.0. (c) The constructor has finished, the fields are 3.0 and 4.0, and d now refers to the object. (d) In the call d.area(), this and d refer to the same object.

Figure 2.1.4 gives the flow of the program step by step. The details are as follows:

  1. main starts running. A main frame is opened on the stack and space is set aside for the variable d, but there is no object yet.
  2. The expression new Rectangle(3, 4) is evaluated. new allocates space for the object on the heap and gives the fields the default value 0.0. Then the constructor is called. The 3 and 4 in the call are integers while the parameters are double, so 3 and 4 are automatically widened to 3.0 and 4.0.
  3. this.width = width; runs: the object’s width field becomes 3.0.
  4. this.height = height; runs: the height field becomes 4.0. The constructor ends and its frame is removed from the stack.
  5. The value of the new expression is the object’s reference, that is, a value that points to its place on the heap. This reference is assigned to d.
  6. d.area() is called. In the new frame, this refers to the same object as d. width * height = 3.0 × 4.0 = 12.0 is computed and returned.
  7. The returned 12.0 is concatenated with the string "Area: " and Area: 12.0 is printed.

The output shows 12.0, not 12, because of the type. area() returns a double. When Java converts a double to a string it writes at least one decimal digit, even if the value is a whole number.

This small program carries the essence of the object-oriented paradigm. Data (width, height) and behavior (area) sit in the same object. The main method does not know how the area is computed; it simply asks the object for its area. Even if the method of computation changed, for example if the dimensions were kept in millimeters instead of centimeters, the call in main would stay the same.

Example 2.1.2

Add these two lines to main: Rectangle r = new Rectangle(2, 5); and System.out.println(r.area() + r.width);.

A second object is created on the heap; its fields are 2.0 and 5.0. The first object is not affected, because each object has its own fields. r.area() returns 10.0 and r.width is 2.0. The two double values are added and 12.0 is printed.

If the line were "Area: " + r.area() + r.width, the result would be different. Because the left operand is a string, both + operators concatenate, and Area: 10.02.0 is printed.

2.1.3Syntax and semantics

Programming languages and natural languages share a good deal. Both have primitive elements, both have rules for how those elements may be combined, and a correctly formed text has a meaning. Three layers of studying a language rest on this observation: syntax, static semantics, and semantics. The distinction is not merely theoretical. The layer of an error in a program determines who finds it, and when: the compiler, the JVM, or the person testing the program.

2.1.3.1Primitives and syntax

In English the primitive elements are words and punctuation marks. In Java they are numbers, strings, simple operators (+ - * /), and keywords. int, class, if, and return are examples of keywords; the language reserves these words for itself.

Definition 2.1.8

Syntax is the set of formatting rules that determine which sequences of characters and symbols are well formed in a language. A text that breaks these rules is invalid even if every word in it is correct on its own.

Each word in “cat dog child” is English, but there is no sentence: no subject, object, or predicate has been formed. The same holds in Java. int x = 5; is a valid line: first the type, then the name, then the assignment sign, then the value, and finally the semicolon. If the same pieces are arranged in another order, the line is invalid:

int = x 5;

The compiler rejects this line. The full message from JDK 21 is:

Bad.java:3: error: not a statement
        int = x 5;
        ^
Bad.java:3: error: ';' expected
        int = x 5;
           ^
Bad.java:3: error: not a statement
        int = x 5;
              ^
Bad.java:3: error: ';' expected
        int = x 5;
               ^
4 errors

A single misordering on a single line has caused four error messages. The reason is that the compiler does not stop after the error; it tries to make sense of the rest of the line. Expecting a name after int, it sees = and says “this is not a statement.” Then it expects a ; and does not find one. It also tries to interpret the remaining pieces x and 5 separately and produces two more messages. The later messages are side effects of the first error. That is why, when several errors are listed, you start fixing with the first one; once it is fixed, the others often disappear.

Syntax also affects how understandable a language is. In a language with precise rules, there is no argument about how a line should be read. Syntax errors are therefore the easiest errors to find: the rules are explicitly defined and the compiler checks every line against them.

2.1.3.2Static semantics

Not every text with correct syntax is meaningful. The English sentence “I are big” fits the pattern <noun> <verb> <noun> in form. But “I” is singular and “are” is plural, so the sentence is invalid in the language. This kind of mismatch lies not in the order of the sentence but in how well its parts fit together.

Definition 2.1.9

Static semantics are the rules that check, before the program runs, whether a syntactically correct expression is meaningful. In Java the most important of these rules is type compatibility.

In Java, <value> <operator> <value> is a valid pattern. 2.3 / 4 fits it and is meaningful. The line below fits the same pattern, but dividing a number by a string has no meaning:

double result = 2.3 / "abc";
error: bad operand types for binary operator '/'
  first type:  double
  second type: String

The message says that the / operator cannot be used with these two types, and it gives the type of each operand: the first is double, the second is String. Another error of the same kind is assigning a value to a variable whose type does not match:

int x = "five";
error: incompatible types:
  String cannot be converted to int

There is nothing wrong with the syntax of these two lines. The error is found in the compiler’s type-checking step. Java is a statically typed language: the compiler knows the type of every variable and every expression and checks the operand types of every operator. That is why errors of this kind are caught before the program ever runs.

Source codeBad.javaSyntaxint = x 5;Static semanticsint x = "five";Run (semantics)(a + b) / 2
Figure 2.1.5: The checks that source code passes through. The code first goes through the syntax check (int = x 5; is stopped here), then the static-semantics check (int x = "five"; is stopped here); both happen at compile time. Semantic errors (such as an average computed with (a + b) / 2) appear only while the program runs.

Figure 2.1.5 shows the three layers as a pipeline. Each layer takes the code that got through the one before it. A line with a syntax error never reaches the type check. Code that passes the type check compiles and can be run. The errors in the last box are of a kind the compiler cannot see.

How strong static-semantics checking is varies from language to language. In languages where this checking is weak, errors that slip through make the behavior of the program unpredictable. In C, writing outside the bounds of an array is not caught at compile time, and the program can silently corrupt another part of memory. Java catches some of these errors at compile time and the rest at run time with an exception; it leaves none of them silent.

2.1.3.3Semantics

Definition 2.1.10

Semantics determines what a syntactically correct expression means, that is, what it does when it runs.

In natural languages a sentence can have more than one meaning. “They saw the man with the telescope.” can be read in two ways: they used a telescope to see the man, or they saw the man who had the telescope. The listener works out the right meaning from context. Programming languages have no such ambiguity. Every valid expression has exactly one meaning, and that meaning is written in the language specification.

That single meaning, however, may not be what the programmer expects. The code below tries to compute the average of 7 and 8 in three different ways:

int a = 7, b = 8;
int avg = (a + b) / 2;
System.out.println(avg);            // not 7.5
System.out.println(a + b / 2);      // precedence
System.out.println((a + b) / 2.0);  // correct
7
11
7.5

The average of 7 and 8 is 7.5. Only the third line prints that value. The first two lines compile, run, and print a number, but the number is wrong. The compiler sees no error in these lines because, as far as the language is concerned, there is none. Each line does exactly what is written, according to Java’s rules.

  • (a + b) / 2: both operands are int, so Java performs integer division. The fractional part of 15 / 2 is discarded and the result is 7.
  • a + b / 2: there are no parentheses, and / has higher precedence than +. First b / 2 = 4 is computed, then 7 + 4 = 11.
  • (a + b) / 2.0: 2.0 is a double constant. 15 is also widened to double and real division is performed: 7.5.

2.1.3.4Code trace: integer division

How an expression is evaluated is shown clearly by its expression tree. In the tree every internal node is an operator and every leaf is a value or a variable. An operator can be applied only after the values of its child nodes have been found, so evaluation proceeds from the leaves toward the root.

/+152a7b8 /7+152a7b8 +11a7/4b82 /7.5+152.0a7b8
Figure 2.1.6: Expression trees of the average program. (a) (a + b) / 2: the parentheses come first, a + b = 15. (b) 15 / 2: both operands are int, so integer division gives 7. (c) a + b / 2: without parentheses the division sinks to the bottom; first b / 2 = 4, then 7 + 4 = 11. (d) (a + b) / 2.0: because 2.0 is a double, the result is 7.5.

Trees (a) and (c) in Figure 2.1.6 consist of the same four pieces (a, b, +, /) and the same constant 2. Only their shapes differ. The parentheses move the + node down, to the place where it is done first. Without parentheses, the precedence rule puts / at the bottom. This is why two expressions written with the same characters give different results.

Table 2.1.5: Line-by-line trace of the average program.
LineComputationVariablesOutput
1—a = 7, b = 8
2(7 + 8) / 2 = 15 / 2 = 7avg = 7
3—7
47 + 8 / 2 = 7 + 4 = 1111
5(7 + 8) / 2.0 = 15.0 / 2.0 = 7.57.5

The second line of the program shows the most common trap in these notes. The variable avg is declared as int. Even if the right-hand side produced 7.5, Java would not allow that value to be assigned to an int. Making the variable a double does not solve the problem either: the right-hand side still produces 7 by integer division, and the assignment merely turns 7 into 7.0.

Common mistake

Thinking that storing the result in a double variable makes the division fractional. The line double avg = (a + b) / 2; gives 7.0, not 7.5. Java first evaluates the right-hand side with its own types: the quotient of two int values is an int. Only after that computation is finished is the assignment performed, and the lost fraction does not come back. The fix is to make one of the operands a double: (a + b) / 2.0.

2.1.4Kinds of errors and error messages

Writing programs includes making mistakes and finding them. Even experienced programmers do not write error-free code on the first try. The difference is that they quickly recognize the kind of an error and know where to look for it. The distinction among syntax, static semantics, and semantics pays off directly here.

2.1.4.1Four kinds of errors

Table 2.1.6: Kinds of errors, when they are noticed, and how they show up in Java.
Kind of errorWhen is it noticed?Java exampleSymptom
Syntaxat compile time (compiler)System.out.println("Hello")';' expected
Static semanticsat compile time (type check)int x = "five";incompatible types
Run-timewhile the program runsa / b (when b is zero)crash: ArithmeticException
Logicnot by the compiler; only by testing(a + b) / 2 for an averagewrong result, infinite loop

The first two kinds are together called compile-time errors. Both are found before the program runs, and no .class file is produced while one is present. Syntax errors are like spelling mistakes: they violate clearly defined rules, and the compiler finds them easily. Static-semantics errors are looked for with language-specific checks; in Java the types are at the center of this checking.

Definition 2.1.11

A run-time error arises while a compiled program is running and, in Java, causes an exception. A logic error is when the program runs and produces a wrong result; neither the compiler nor the JVM notices it.

The last row of the table describes the most dangerous case. Even a program that is flawless in syntax and static semantics may not produce the expected result. It can crash, fall into an infinite loop, or give a wrong result without any warning. The last of these is the hardest to find, because nothing signals that something has gone wrong.

2.1.4.2Reading a compile-time error message

A compiler’s error message can look frightening, but it has a regular structure. In the program below a semicolon is missing:

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello")
    }
}
Hello.java:3: error: ';' expected
        System.out.println("Hello")
                                     ^
1 error

The message has four parts:

  • Hello.java:3: the file and line number where the error was found.
  • error: ';' expected: what the compiler was expecting. Here a semicolon was expected.
  • A copy of the line with a ^ mark under it: the position of the error within the line. The mark points just past the closing parenthesis, where the ; should have been.
  • 1 error: the total number of errors.

When there is an error, no .class file is produced and the program does not run at all. If an old .class file is left over from an earlier compilation, the java command may run that old version by mistake. This is often why a change to the code seems to have no effect: the compilation failed, but the message went unnoticed.

When a semicolon is missing, javac points to the error at the end of the line where the ; is missing. In the fragment below, the ; at the end of the first line has been forgotten:

int x = 5
int y = 6;
System.out.println(x + y);
Semi.java:3: error: ';' expected
        int x = 5
                 ^
1 error

The mark is placed not on the second line but right after the 5. When the compiler sees the next token after 5 (int), it realizes the statement should have ended and reports the omission at the end of the previous piece. Line 3 of the file is the first line of the fragment; above the fragment are the class and main headers.

Example 2.1.3

A program declares int total = 0; and on line 7 writes System.out.println(Total);. The compiler reports Calc.java:7: error: cannot find symbol, with symbol: variable Total beneath it.

Reading the message: the error is on line 7, and the compiler could not find a variable named Total. The declared name is total. Java distinguishes uppercase from lowercase, so these are two different names. This is a compile-time (static semantics) error. When Total is changed to total, the program compiles.

2.1.4.3Run-time errors and exceptions

The program below compiles without trouble. The error appears only when it runs:

public class Divide {
    public static void main(String[] args) {
        int a = 10, b = 0;
        System.out.println(a / b);
    }
}
Exception in thread "main"
java.lang.ArithmeticException: / by zero
	at Divide.main(Divide.java:4)

The compiler sees nothing wrong with a / b: the quotient of two int values is a valid expression. That b is 0 at that moment is known only while the program runs. Integers cannot be divided by zero, so the JVM throws an exception. The parts of the message are:

  • Exception in thread "main": the exception occurred in the main thread.
  • java.lang.ArithmeticException: the type of the exception, that is, the full name of its class.
  • / by zero: the description of the exception; an integer division by zero was attempted.
  • at Divide.main(Divide.java:4): the method, file, and line where the exception occurred.

In the real output the first two parts are printed on one line; here they are split to fit the page. If the exception is not caught by a try-catch block, the program ends at this line and the following lines never run.

The behavior of division by zero depends on the type. 10 / 0 throws an exception. 10.0 / 0 does not throw; it produces the value Infinity, and 0.0 / 0 gives NaN (not a number). Floating-point numbers have these special values; integers do not. A division by zero with double therefore does not crash the program, but silently turns the result into a meaningless value.

Another common run-time error is going outside the bounds of an array. int[] a = new int[3]; creates an array of three elements; the valid indices are 0, 1, and 2. a[3] = 1; compiles, but at run time it throws ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3. The value of an index is often the result of a computation, and the compiler cannot know it in advance.

2.1.4.4Logic errors and testing

With a logic error the program compiles, runs, and gives a result; only the result is wrong. Computing the average as (a + b) / 2, writing 2 * pi * r for the area of a circle (that is the circumference), and setting the bound of a loop one too low or one too high are all of this kind. As far as the language is concerned, none of these lines is flawed.

The way to find logic errors is testing: run the program on inputs whose result is known in advance and compare the output with the expected value. The average of 7 and 8 is known to be 7.5; if the program prints 7, there is a bug. A few well-chosen tests also narrow down where the bug is. For 6 and 8 the program gives the right result (7), and for 7 and 8 the wrong one; this difference suggests that fractional results are being lost.

The exception mechanism does not catch logic errors. An exception is thrown when an invalid operation is performed; with a logic error every operation performed is valid. The distinction matters: that a program runs without throwing an exception does not show that it runs correctly.

Example 2.1.4

Suppose each of the four lines below is in a separate program. Identify the kind of error.

(a) String s = 5; A static-semantics error. The compiler says incompatible types: int cannot be converted to String. The form of the line is correct; the types do not match.

(b) System.out.println("Hello"; A syntax error. The closing parenthesis is missing; the compiler says ')' or ',' expected.

(c) int k = 0; System.out.println(10 % k); A run-time error. Like division, the remainder operation cannot be taken with a zero divisor; ArithmeticException: / by zero is thrown.

(d) double perimeter = pi * r * r; A logic error. The code compiles and runs, but it computes the area instead of the perimeter. The correct form is 2 * pi * r.

2.1.5Expressions and operator precedence

Every part of a program that does a computation is an expression. To find the value of an expression correctly, two things must be known: the order in which the operations are carried out, and the type each operation produces. This section covers the first, the precedence rules; types come into those rules here and there.

2.1.5.1Expressions, operators, operands

Definition 2.1.12

An expression is a construct that produces a value when evaluated: 3 + 4, x > 0, pi * r * r. The operation symbols in an expression are called operators, and the values an operator works on are called operands.

In the expression 3 + 4, + is the operator, 3 and 4 are the operands, and the value of the expression is 7. Operands can themselves be expressions. In (a + b) / 2, the left operand of the / operator is the expression (a + b). Expressions thus nest inside one another and form a tree.

There are five basic arithmetic operators in Java: addition +, subtraction -, multiplication *, division /, and remainder %. The remainder operator gives the remainder of a division: 7 % 3 = 1, because 7 = 2 · 3 + 1. In addition, the comparison operators (<, >, <=, >=, ==, !=) compare two values and produce a boolean value, that is, true or false.

2.1.5.2Precedence and the left-to-right rule

Definition 2.1.13

Operator precedence is the rule that determines the order in which operators are applied in an expression. Arithmetic operators of the same precedence are applied from left to right.

Java’s arithmetic precedence matches the rules of school mathematics. Table 2.1.7 lists the operators used in these notes from highest precedence to lowest.

Table 2.1.7: Precedence of the operators used in these notes (decreasing from top to bottom).
LevelOperatorsDirection
1parentheses ( )inside out
2* / %left to right
3+ - (addition, subtraction, string concatenation)left to right
4< > <= >=left to right
5== !=left to right
6= (assignment)right to left

Two details in the table are easy to miss. First, *, /, and % are on the same level. None comes before the others; whichever is further left is done first. The expression 12 / 3 * 2 gives (12 / 3) · 2 = 8, not 12 / 6 = 2. Second, assignment has the lowest precedence and works right to left. So x = y = 7; first assigns 7 to y and then assigns the value of that assignment (7) to x.

Performing operations of equal precedence from left to right directly affects the result for subtraction. The expression 10 - 4 - 3 is computed as (10 − 4) − 3 = 3. Starting from the right would give 10 − (4 − 3) = 9. For addition and multiplication the order does not change the result, but once integer division is involved it does: 7 / 2 * 2 = 3 · 2 = 6, whereas 7 * 2 / 2 = 14 / 2 = 7.

Example 2.1.5

Find the value of the expression 10 - 2 * 3 + 8 / 4 % 3.

The operators of highest precedence are *, /, and %. From left to right: 2 * 3 = 6. Then 8 / 4 = 2, and then 2 % 3 = 2. The expression becomes 10 - 6 + 2.

- and + are on the same level, left to right: 10 − 6 = 4, 4 + 2 = 6. The result is 6, and its type is int.

2.1.5.3Evaluating an expression step by step

A computer does not evaluate an expression in one go; it simplifies it step by step according to the precedence rules. At each step it performs the leftmost of the operations with the highest precedence and puts its result in its place. The following expression, taken from the Fahrenheit-to-Celsius formula, shows this well: (72 - 32) / 9 * 5. In mathematics its value is 40 · 5 / 9 ≈ 22.22.

Table 2.1.8: Step-by-step evaluation of the expressions (72 - 32) / 9 * 5 and (72.0 - 32) / 9 * 5.
StepExpressionOperation performed
1(72 - 32) / 9 * 5parentheses first: 72 − 32 = 40
240 / 9 * 5/ and * are on the same level, left to right: first 40 / 9
34 * 5both operands are int: integer division gives 4, not 4.44… (the remainder 4 is discarded)
420the result is 20; the expected value was 22.22…
5(72.0 - 32) / 9 * 5double − int: 32 is widened to 32.0; the result is 40.0
640.0 / 9 * 5real division: 4.444444444444445
74.444444444444445 * 5double × int → double
822.22222222222222the correct result
×/5−972321.2.3.
Figure 2.1.7: The tree of the expression (72 - 32) / 9 * 5. The operation at the bottom is done first; the numbers give the order of operations: 1. subtraction, 2. division, 3. multiplication.

Figure 2.1.7 shows the structure of the expression. The root is the multiplication, because it is done last. The left operand of the multiplication is the division, and the left operand of the division is the subtraction. The left-to-right rule shows up in the tree like this: since / and * have the same precedence, the one on the left (/) sinks to the bottom and is done first.

The first four steps of Table 2.1.8 show that a result can come out wrong even when the precedence rules are applied correctly. The error is not in the precedence but in the type. In the third step two int values are divided and the fraction is lost. That loss is magnified by the multiplication that follows: the lost 0.44 is multiplied by five, and the result is 2.22 too small. This is a semantic (logic) error; the compiler does not warn about it.

To fix it, it is enough to make a single constant a double. When 72.0 is written, the result of the subtraction becomes double, and this type spreads through the rest of the expression. If one operand of an operation is double, the other is widened to double as well and the result is double. If a fractional result is needed, at least one operand must be double, and this widening must happen before the division.

The last digit of 22.22222222222222 in the final step may also draw attention. In mathematics 200 / 9 = 22.222… goes on forever. A double keeps about 15–17 significant digits; when Java prints the value, it chooses the shortest digit string that identifies it uniquely. Floating-point numbers are therefore always approximations.

Example 2.1.6

Write the same computation with the order of operations changed: (72 - 32) * 5 / 9.

Parentheses: 40. Left to right, multiplication first: 40 · 5 = 200. Then division: 200 / 9 = 22 (integer division; the remainder 2 is discarded). The result is 22.

The loss is smaller: because the integer division is left for last, only the final fraction (0.22…) is discarded. Doing the multiplication before the division reduces the error when working with integers, but does not remove it. For the exact result a double is still needed: 200 / 9.0 = 22.22222222222222.

2.1.5.4Integer division and remainder

Definition 2.1.14

Integer division discards the fractional part when one integer is divided by another. In Java, if both operands of the / operator are of an integer type (such as int or long), the result is an integer too. The result is truncated toward zero: 7 / 2 = 3, -7 / 2 = −3.

The phrase “truncated toward zero” matters for negative numbers. −7 / 2 = −3.5. When the fraction is discarded, −3 remains; the result moves toward zero. Some languages (for example Python’s // operator) round down and give −4. Java always truncates toward zero.

The remainder operator % is consistent with division. For every a and every nonzero b, the following identity holds:

(a / b) * b + a % b == a

It follows from this identity that the sign of the remainder is the same as the sign of the dividend. -7 % 2 = −1, because (−3) · 2 + (−1) = −7. -17 % 5 = −2. By contrast, 7 % -2 = 1; the sign of the divisor does not affect the remainder. Whether a number is even is tested with n % 2 == 0. Because the remainder of a negative odd number is −1, an odd-number test must be written n % 2 != 0, not n % 2 == 1.

Table 2.1.9: Examples of integer division and remainder (verified by running them with JDK 21).
ExpressionResultTypeExplanation
7 % 31int7 = 2 · 3 + 1
17 / 53intthe fraction of 3.4 is discarded
17 % 52int17 = 3 · 5 + 2
-7 / 2-3inttruncated toward zero
-7 % 2-1intthe remainder takes the sign of the dividend
1 / 3 * 30int1 / 3 = 0, then 0 · 3
1.0 / 3 * 31.0doublereal division
17 / 5.03.4doubleone operand is double

Integer division is not always a mistake. Many algorithms use it on purpose. Splitting seconds into minutes and seconds is a typical example: for 135 seconds, 135 / 60 = 2 minutes and 135 % 60 = 15 seconds. Separating the digits of a number works the same way: n % 10 gives the last digit and n / 10 drops it. The problem arises when integer division happens unnoticed where a fractional result was expected.

Example 2.1.7

A student’s three exam scores are 70, 85, and 90. Compute the average in three ways:

int t1 = 70, t2 = 85, t3 = 90;
System.out.println((t1 + t2 + t3) / 3);     // 81
System.out.println((t1 + t2 + t3) / 3.0);   // 81.66666666666667
double avg = (t1 + t2 + t3) / 3;
System.out.println(avg);                     // 81.0

The total is 245. The first line finds 245 / 3 by integer division: 81. In the second line, 3.0 is a double, so real division is performed and 81.66666666666667 is printed. The third line is the most misleading: even though the variable is double, the right-hand side is first computed as 81, and the assignment turns it into 81.0.

2.1.5.5Exponentiation

Java has no exponentiation operator. The operation written 23 in mathematics is done with the method Math.pow(2, 3), and the result is a double: 8.0. Math.pow(2, 10) = 1024.0 and Math.pow(2, 0.5) = 1.4142135623730951. For small integer powers, multiplication is also used: x * x is x2.

Two habits from other languages cause trouble here. Python’s ** operator does not exist in Java; if 2 ** 3 is written, the compiler says illegal start of expression. The more insidious one is the ^ sign. In Java ^ is a valid operator, but it is not exponentiation; it is the bitwise exclusive or (XOR):

System.out.println(2 ^ 3);           // 1: XOR
System.out.println(Math.pow(2, 3));  // 8.0

The binary representation of 2 is 010 and that of 3 is 011. XOR produces 1 in the bits where the two numbers differ: 001, that is, 1. The code compiles and runs; only the result is wrong. Because it gives no compile-time error, trying to exponentiate with ^ is a logic error.

2.1.6Variables, assignment, and typing

The values a program computes must be stored somewhere. That place is a variable. The type of a variable determines what kind of value it can hold and what operations can be performed on that value.

2.1.6.1Variables and assignment

Definition 2.1.15

A variable is a memory location bound to a name, whose value can change. In Java a variable is declared with its type and name before it is used: int count;. Assignment writes the value of the expression on the right into the variable on the left, using the = sign.

Assignment takes place in two steps, and the order of the two steps matters:

  1. The expression on the right is computed with the variables’ current values.
  2. The value found is written into the variable on the left; the variable’s old value is erased.

This order makes sense of the line x = x + 1, which looks meaningless in mathematics, where it is an equation with no solution. In Java it is a command: “add 1 to the current value of x and write the result into x.” If x is 5, first 5 + 1 = 6 is computed, then 6 is written.

Example 2.1.8

What are a and b after these four lines run? int a = 4; int b = a * 3; a = b - a; b = b / a;

1. a = 4. 2. The right-hand side is 4 · 3 = 12, so b = 12. 3. The right-hand side is computed with the old value of a: 12 − 4 = 8; then a becomes 8. 4. 12 / 8 = 1 (integer division; 0.5 is discarded); b = 1.

Result: a = 8, b = 1. In the third line a appears on both the right and the left. While the a on the right is being read, its value is still 4; the new value is written only after the computation is finished.

Variable names are called identifiers, and they must follow a few rules. A name begins with a letter, an underscore (_), or a dollar sign ($); the following characters may also be digits. A name cannot contain spaces and cannot be a keyword. total2, _counter, $price, and averageGrade are valid. 2total is invalid because it starts with a digit, student count because it contains a space, and int because it is a keyword. By Java convention, variable names start with a lowercase letter and later words are joined with an initial capital: averageGrade, studentCount.

Java distinguishes uppercase from lowercase. Count and count are two different names:

int Count = 4;
System.out.println(count);
Case.java:4: error: cannot find symbol
        System.out.println(count);
                           ^
  symbol:   variable count
  location: class Case
1 error

The message says that the compiler could not find a variable named count. The symbol line gives the name being looked up, and the location line gives the class in which the lookup was made. The same message appears when the variable was never declared or when its name is misspelled.

A local variable cannot be read before it is given a value:

int s;
System.out.println(s);
Uninit.java:4: error: variable s might not have been initialized
        System.out.println(s);
                           ^
1 error

The compiler examines every path that reaches s and finds no assignment on any of them. This check prevents a random memory value from being used silently. The fields of an object (such as width and height of Rectangle), by contrast, automatically receive a default value: 0 for numbers and false for boolean. Local variables have no such default.

2.1.6.2Assignment versus comparison

In Java = is assignment and == is comparison. Because the equals sign in mathematics is used in both senses, the two operators are often confused. Writing = inside a condition by mistake is a typical error:

int x = 100;
if (x = 100) {
    System.out.println("hundred");
}
Check.java:4: error: incompatible types: int cannot be converted to boolean
        if (x = 100) {
              ^
1 error

A boolean value is expected inside the parentheses of an if statement. x = 100 is an assignment, and its value is the value assigned, that is, the int 100. Java does not convert an int to a boolean, so the line does not compile. The correct form is if (x == 100). In C, integers can be used as conditions, so the same mistake compiles and the condition is always true; Java’s type checking catches this error at compile time.

The values produced by comparison operators can be stored in boolean variables: boolean passed = score >= 50;. In this line the comparison score >= 50 is made first (in the precedence table >= is higher than =), and then its result is assigned to passed. Such a variable can be used directly in an if statement: if (passed).

2.1.6.3Static and dynamic typing

Every programming language is concerned with the types of values; the difference between languages lies in when the types are checked.

Definition 2.1.16

In statically typed languages (Java, C, C#) the type of a variable is stated explicitly, does not change, and type compatibility is checked at compile time. In dynamically typed languages (Python, JavaScript) the type of a variable is not declared in advance; it is determined when a value is assigned and may change at run time. These two approaches are called static typing and dynamic typing.

The difference shows when the same idea is written in two languages. In Python a variable can be assigned a number first and then a string:

x = 5          # x is an int now
x = "five"      # now a str: no problem
print(x + 1)   # at run time:
# TypeError: can only concatenate
#   str (not "int") to str

The first two lines run without trouble. The error appears only when the third line is executed and a number is added to a string. If that line were at the end of the program or in a rarely taken branch, the error might go unnoticed for weeks. In Java the same idea does not compile:

int x = 5;
x = "five";     // does not compile:
// error: incompatible types:
//   String cannot be converted to int

x is declared as int, and that type does not change. The assignment on the second line is rejected at compile time, and the program never runs.

Table 2.1.10: Comparison of dynamic and static typing.
Dynamically typed (Python, JavaScript)Statically typed (Java, C, C#)
Type declarationNot declared in advance; determined when a value is assignedStated explicitly and does not change
Can the type change?Yes, at run timeNo
Incompatible operationError at run time (TypeError)Error at compile time
BenefitFlexibility, short codeSafety; the compiler can generate fast code

Static typing also brings speed. Because the compiler knows that both variables in a + b are int, it generates an integer-addition instruction directly. In a dynamically typed language, the current types of the operands must be looked at on every addition: two numbers, two strings, or an incompatible pair?

Since Java 10, local variables can also be declared with var. This does not make Java dynamically typed:

var count = 3;        // type: int
var ratio = count / 2;  // type: int, value 1
var name = "Ali";       // type: String
count = "three";       // does not compile: String cannot be converted to int

With var no type is written, but the compiler infers the type from the right-hand side and fixes it at compile time. The type of count is int; a string cannot be assigned to it later. var only shortens the notation; type checking continues exactly as before. For this reason a variable declared with var must be given an initial value: var x; does not compile, because the compiler has no value from which to infer the type.

Common mistake

Thinking that var lets a variable take a value of any type. In the line var ratio = count / 2;, if count is 3, the type of ratio is int and its value is 1. var does not choose a fractional type; it takes whatever the right-hand side produces. If a fractional result is wanted, either write double ratio = count / 2.0; or arrange the right-hand side so that it produces a double.

2.1.7Strings and types

A program does not work with numbers alone. Every message shown to the user, every name read in, and every result written to the screen is a string. When numbers and strings meet in the same expression, Java’s rules are precise but surprising at first sight. This section covers those rules.

Definition 2.1.17

A string is a piece of text made up of characters. In Java strings are objects of the String class and are written in double quotes in source code: "Hello". A single character in single quotes ('a') is not a string but a value of type char.

2.1.7.1Different types cannot be compared

Comparing different data types directly leads to an error. An integer and a string cannot be compared; although 5 and "5" look the same to a human eye, one is a number and the other is a sequence of characters.

int num = 5;
String text = "5";
boolean b = num == text;
error: bad operand types for binary operator '=='
  first type:  int
  second type: String

Languages define rules and type conversion routes for comparing types. A comparison is meaningful only after both values have been brought to the same type. This can go two ways: the string is converted to a number, or the number is converted to a string.

int num = 5;
String text = "5";
System.out.println(Integer.parseInt(text) == num);
System.out.println(text.equals(String.valueOf(num)));
System.out.println(text.equals(num));
true
true
false
  • Integer.parseInt(text) converts the string "5" to the int 5. The two int values can now be compared with ==: true.
  • String.valueOf(num) converts the number 5 to the string "5". The two strings are compared with the equals method: true.
  • text.equals(num) compiles, but always returns false. equals accepts an object of any type as its parameter; here num is automatically wrapped in an Integer object. A String is never equal to an Integer.

The third line is the most dangerous, because the compiler does not warn. The program runs and gives a wrong answer; this is a logic error. parseInt also needs care: if the string is not an integer, for example "5a" or "5.0", it throws NumberFormatException at run time.

Comparing strings has one more rule: strings are compared with equals, not with ==. The operator == checks whether two references point to the same object; equals checks whether the characters of the two strings are the same. Two separate objects can hold the same text, and then == gives false while equals gives true. Because identical string literals in source code are stored as a single object in Java, == sometimes gives the right answer by accident. Do not rely on that coincidence.

2.1.7.2Operations across types

The same operator behaves differently on different types. The clearest example is +: on numbers it is addition, and on strings it is concatenation.

Definition 2.1.18

String concatenation joins strings end to end with +. If one operand of + is a string, the other is converted to a string too, and the result is a string. A widening conversion is the automatic conversion of a smaller numeric type to a larger one: int → double.

Table 2.1.11: The + operation on different types (verified by running them with JDK 21).
ExpressionJava resultTypeExplanation
3.0 + 4.07.0doubletwo floating-point numbers
3 + 47inttwo integers
3 + 4.07.0doublethe int is automatically widened to double
"3" + "4""34"Stringconcatenation
3 + "4""34"Stringif one side is a string, the other is converted to a string; not an error
3 + truedoes not compile—bad operand types for binary operator '+'
'a' + 198inta char is a numeric code ('a' = 97)

Each row of the table shows a rule. The sum of two int values is an int. When an int and a double are added, the int is first widened to double; no information is lost in widening, because every int value can be represented exactly in a double. The reverse direction is not automatic. The line int n = 4.5; does not compile, and the compiler says possible lossy conversion from double to int: converting a double to an int can lose the fraction, and Java expects the programmer to ask for that loss explicitly.

The line 3 + "4" shows the different choices languages make. Java does not count it as an error; it converts 3 to "3" and concatenates. In Python, 3 + "4" throws a TypeError; Python does not convert a number to a string on its own. JavaScript concatenates, like Java. None of them is wrong; each language has its own rule, and a programmer must know the rule of the language in use.

The line 3 + true is another choice Java makes: a boolean is not a number. In C, true counts as 1 and this sum gives 4; Java does not compile the line. The last row, 'a' + 1, looks surprising but follows the rule. The char type stores a character as its Unicode code number; the code of 'a' is 97. In an arithmetic operation the char is widened to int, and 97 + 1 = 98. To see the result as a character, an explicit cast is needed: the expression (char) ('a' + 1) gives 'b'.

An operation across types leads to unexpected results or errors if the rules of the language are not known. In Java these rules are exact, and the compiler applies them to every expression in the same way. For a programmer who knows the rules, Java’s behavior is always predictable.

2.1.7.3Concatenation goes left to right

The + operator works from left to right and at each step looks only at the two operands of that step. When an expression contains both numbers and strings, the result depends on where the string is:

Table 2.1.12: Expressions mixing numbers and strings.
ExpressionStepsOutput
"Total: " + 2 + 3"Total: 2" + 3Total: 23
"Total: " + (2 + 3)parentheses first: 5; "Total: " + 5Total: 5
2 + 3 + " total"2 + 3 = 5; 5 + " total"5 total
1 + 2 + "3" + 4 + 53; "33"; "334"; "3345"3345
"" + 'A' + 'B'"A"; "AB"AB
'A' + 'B'65 + 66131

The first row is the source of a common mistake. The programmer wants to print “Total: 5”, but Java starts from the left: "Total: " + 2 is a string. Adding 3 to this string is again concatenation, and “Total: 23” comes out. Parentheses are needed so that the numbers are added first. In the third row the string comes last. The two int values on the left are added to give 5; concatenation happens only in the final step.

The fourth row shows the general form of the rule. Numbers are added until the first string is seen; after the first string, every + is concatenation. The last two rows apply the same rule to char. In the expression 'A' + 'B' there is no string; the two characters are added as numbers, and 65 + 66 = 131. Putting an empty string ("") at the start turns the whole expression into concatenation from the beginning.

2.1.7.4The decimal separator in input

Another aspect of conversion between types is input read from the user. Everything that comes from the keyboard is text first; the Scanner class converts this text to the requested type. The nextDouble() method uses the computer’s locale when reading a floating-point number. In the Turkish locale the decimal separator is a comma.

Scanner input = new Scanner(System.in);   // locale: Turkish
double height = input.nextDouble();
// input "1,75" -> 1.75
// input "1.75" -> java.util.InputMismatchException

On a computer with a Turkish regional setting, if the user types 1,75, the value is read as 1.75. If the user types 1.75, Scanner does not recognize it as a floating-point number and throws InputMismatchException; the program stops. Constants in the source code (such as 65.2) and the output of println are not affected by the locale; they always use a period. So the same program asks for a comma in the input and prints a period in the output.

There are two ways to solve the problem. The first is to match the example in the prompt shown to the user to the locale: “Height (e.g. 1,75)”. The second is to fix the locale of the Scanner: after the line input.useLocale(Locale.US); the input is read with a period on every computer. This detail is a common reason why the same program works on one computer and crashes on another.

2.1.8From algorithm to program

The previous sections took up the building blocks of a program one at a time: values, types, expressions, variables. This section puts them together. A program is a sequence of instructions built from these blocks, and the order of the instructions matters at least as much as the instructions themselves.

2.1.8.1A program is a sequence of instructions

A computer processes instructions one at a time, in order. When one instruction finishes, the next one begins, and each instruction continues from the state the previous one left behind. That is why it is important to get the order of operations right. A classic example is exchanging the values of two variables, which is called a swap.

int a = 3, b = 5;
a = b;
b = a;
System.out.println(a + " " + b);

int c = 3, d = 5;
int temp = c;
c = d;
d = temp;
System.out.println(c + " " + d);

The program prints two lines: 5 5 and 5 3. The first swap fails and the second succeeds. Table 2.1.13 traces the two fragments line by line.

Table 2.1.13: Trace of the swap program.
LineStatementVariablesOutput
1int a = 3, b = 5;a = 3, b = 5
2a = b;a = 5, b = 5 (the old 3 is gone)
3b = a;a = 5, b = 5
4println5 5
6int c = 3, d = 5;c = 3, d = 5
7int temp = c;c = 3, d = 5, temp = 3
8c = d;c = 5, d = 5, temp = 3
9d = temp;c = 5, d = 3, temp = 3
10println5 3
a5b5 a5b5 c3d5temp3 c5d3temp3
Figure 2.1.8: Four moments from the swap trace. (a) a = b: 5 is written into a and the old value 3 is lost. (b) b = a: the current value of a (5) is written into b; the swap has failed. (c) The correct method: the value of c is first saved in temp. (d) The saved old value of c (3) is written into d; the swap succeeds.

The flaw in the first fragment is that assignment erases the old value. When a = b; runs, the value 3 of a is lost and has been saved nowhere. The following line b = a; copies the current value of a, which is 5. Panels (a) and (b) of Figure 2.1.8 show this loss. Reordering the lines does not fix the result: if b = a; is written first, this time the value of b is lost and the output is 3 3.

The correct method is to save the value that is about to be overwritten in a third, temporary variable beforehand. The line temp = c puts the 3 in safekeeping. After that c can be overwritten safely. The last line moves the saved value into d. A swap takes three assignments, and their order cannot be changed. The cost is constant: however many values there are, one swap needs three assignments and one extra variable.

Example 2.1.9

Integers can also be swapped without a temporary variable. For a = 4 and b = 9, trace these three lines: a = a + b; b = a - b; a = a - b;

1. a = 4 + 9 = 13, b = 9. 2. b = 13 − 9 = 4. 3. a = 13 − 4 = 9.

In the end a = 9 and b = 4. The method works, but it has two drawbacks. It is hard to read, and if the sum a + b exceeds the range of int, overflow occurs. The method with a temporary variable works for every type and shows its intent clearly.

2.1.8.2Expressions, statements, and programs

The parts of a program are of two kinds: those that produce a value and those that produce an effect.

Definition 2.1.19

An expression computes a value and returns the result: the value of the expression 3 + 4 is 7. A statement produces an effect: pi = 3.14159; assigns a value to a variable, and System.out.println(pi); writes to the screen. In Java statements usually end with ;. A program consists of statements that run in order.

Expressions can nest and can appear inside statements. double area = pi * r * r; is a statement; it contains the expression pi * r * r, which in turn contains the expression pi * r. The reverse does not hold: a statement cannot appear inside an expression. println writes to the screen but returns no value; its return type is void. Using it inside a computation therefore makes no sense:

double d = 3 + System.out.println(pi);
error: 'void' type not allowed here

Conversely, an expression that produces a value but has no effect cannot stand alone as a statement:

3 + 4;      // produces a value, no effect
error: not a statement

An expression does not become a statement just by putting ; after it. Java allows this for only four kinds of expression: assignment (x = 5;), increment and decrement (i++;), method call (println(x);), and object creation (new Rectangle(1, 2);). What they have in common is that they produce an effect. 3 + 4;, x * 2;, or x > 3; is computed and the result is immediately thrown away; this is wasted work, and the compiler treats it as a typing mistake.

There is a subtle point here. In Java an assignment also produces a value: the value assigned. That is why the following line compiles:

int y = (x = 4) + 1; → x = 4, y = 5

The assignment in parentheses is done first and its value is 4; 1 is added to it. That an assignment produces a value also makes chained assignments such as x = y = 7; possible. Even so, burying an assignment in the middle of an expression makes the code harder to read and is not preferred. Having a single effect on each line of a program makes both tracing and debugging easier.

Common mistake

Trying to capture in a variable the value that println prints: int s = System.out.println(5);. println writes to the screen but returns no value; the compiler reports incompatible types: void cannot be converted to int. If the result of a computation is both to be used and to be printed, assign it to a variable first and then print it.

2.1.8.3From Fahrenheit to Celsius

The order of writing a program is fixed: first the algorithm, then the code. The algorithm breaks the problem into precise steps; the code writes those steps in the rules of the language. Let us build, in that order, a program that converts a temperature given in Fahrenheit to Celsius. The conversion formula is C = (F − 32) · 5 / 9.

The algorithm has three steps:

1. Read the Fahrenheit value f.
2. Compute c = (f − 32) · 5 / 9.
3. Print c.

Each step has a counterpart in Java. Scanner is used for reading, an assignment statement for the computation, and println for printing:

import java.util.Scanner;

public class Fahrenheit {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Fahrenheit: ");
        double f = input.nextDouble();
        double c = (f - 32) * 5 / 9;
        System.out.println("Celsius: " + c);
    }
}

When the user enters 100, the screen shows:

Fahrenheit: 100
Celsius: 37.77777777777778

The code runs line by line as follows. The line import java.util.Scanner; makes the Scanner class available. new Scanner(System.in) creates an object that reads from the keyboard. Unlike println, print does not move to the next line, so the 100 the user types appears on the same line. input.nextDouble() reads a number and assigns it to f. In the computation line, first f - 32 = 68.0 is found; because f is double, this result is double as well. Then 68.0 · 5 = 340.0 and 340.0 / 9 = 37.77777777777778 are computed.

The way the formula is written matters here too. If the same formula is written as 5 / 9 * (f - 32), the result is 0.0. The precedence rules have not changed: 5 / 9 is on the left and is done first. Since both operands are int, integer division gives 0, and 0 · 68.0 = 0.0. The compiler does not see this as an error; the program prints 0 °C for 100 °F. There are two ways to fix it: make the division floating-point (5.0 / 9 * (f - 32)) or move the multiplication first ((f - 32) * 5 / 9). The second works correctly as long as f is double; because f - 32 produces a double, the division that follows is real division too.

Table 2.1.14: Different ways of writing the Fahrenheit-to-Celsius formula, for F = 100.
Formf is doublef is int
(f - 32) * 5 / 937.7777777777777837 (340 / 9, fraction discarded)
5 / 9 * (f - 32)0.00
5.0 / 9 * (f - 32)37.7777777777777837.77777777777778

The last column of the table shows how the type changes the result. Even if f is int, the 5.0 brings a double into the expression, so the result comes out right. The importance of the order of writing shows even in this small example: the algorithm is correct, and a small difference in notation during translation to Java spoils the result. The way to find such errors is to try an input whose result is known. It is known that 212 °F is 100 °C and 32 °F is 0 °C; if the program converts these two values correctly, the formula is most likely written correctly.

2.1.9Popular programming languages

Programming languages offer different advantages for different tasks, and programmers choose the language that best fits the needs of a project. How much each language is used is tracked every year by surveys and indices. Stack Overflow’s developer survey, the TIOBE index, and the IEEE Spectrum ranking are well known. Each uses a different measure: what survey respondents report, search-engine results, or job postings. The rankings therefore differ a little from one another, but the same languages are always near the top.

Table 2.1.15: Some of the languages that stood out in 2023 and the areas in which they stand out.
LanguageArea of strength
Pythondata analysis, artificial intelligence, web development
Javalarge-scale enterprise applications, Android
JavaScriptweb browsers, web development
C#Windows applications, game development
C++games, systems programming, performance-oriented software
Rustsafe and fast systems programming
Swiftapplication development on Apple platforms
KotlinAndroid application development (runs on the JVM)
Go (Golang)simple and effective; network and cloud applications

The table can be read together with the classifications in the earlier sections. C, C++, Rust, and Go compile directly to machine code and stand out where performance matters. Java, Kotlin, and C# compile to an intermediate code and run on a virtual machine, balancing portability against speed. Python and JavaScript are usually interpreted and are preferred where fast development is needed. That Kotlin runs on the same JVM as Java lets the two languages be used together in one project.

From an engineering point of view there is no single “best language.” C may suit the software of a microcontroller, MATLAB or Python a signal-processing prototype, and Java a desktop measurement application. The concepts learned in one language (types, expressions, precedence, assignment, and statement order) carry over largely to the others. Learning a new language is often a matter of learning how these concepts are written in it and its small differences in rules.

2.1.10Common mistakes

The mistakes of people new to programming come largely from the same few sources. The eight mistakes below summarize rules treated in detail in these notes. In each case the reaction of the compiler or the JVM was obtained with JDK 21.

Table 2.1.16: Common mistakes, their symptoms, and their fixes.
MistakeExampleSymptomFix
Forgetting a semicolonSystem.out.println("Hello")';' expected; ^ points to the end of the line; at the end of the statement
Confusing = with ==if (x = 100)int cannot be converted to booleanif (x == 100)
Integer divisionthe average of 7 and 8 with (a + b) / 27 (expected 7.5); the compiler does not warn(a + b) / 2.0
** or ^ for powers2 ** 3; 2 ^ 3illegal start of expression; ^ compiles but is XOR (1)Math.pow(2, 3)
Order of string and number"Total: " + 2 + 3Total: 23"Total: " + (2 + 3)
Uppercase versus lowercasedeclaring Count and using countcannot find symbolwrite the name as it was declared
Using a variable before assigning itint s; System.out.println(s);variable s might not have been initializedan initial value in the declaration: int s = 0;
Decimal separatorentering 7.5 into nextDouble() in the Turkish localeInputMismatchExceptionenter 7,5 or use useLocale(Locale.US)

The mistakes in the table fall into three groups. The semicolon, uppercase/lowercase, initial-value, and =/== mistakes are compile-time errors; the compiler catches them and its message points to the place. The decimal-separator mistake is a run-time error; the program compiles but crashes on a particular input. Integer division, powers with ^, and concatenation order are logic errors. These last are the most dangerous, because the program produces a wrong result without any sign. The only way to find them is to try inputs whose results are known.

A general habit helps with compile-time errors: read the message carefully and start fixing from the first error. As in the int = x 5; example, a single mistake can lead to a series of messages. Once the first error is fixed, the others often disappear on their own. If nothing looks wrong on the line the message points to, look at the previous line too; an unclosed parenthesis or quotation mark in particular can carry the error several lines further on.

2.1.11Summary

  • A programming language is an artificial language designed to express computations that a machine can carry out. A program is both an instruction to the machine and a means of communication between programmers.
  • Languages are classified by four criteria: level of abstraction (low or high level), application area (general-purpose or domain-specific), execution model (compiled or interpreted), and paradigm.
  • In Java, javac compiles source code to bytecode (.class); the JVM interprets the bytecode and translates frequently executed parts to machine code with the JIT compiler. The same .class file runs on every platform that has a JVM.
  • The four basic paradigms are imperative, functional, logic, and object-oriented. Java is fundamentally object-oriented and imperative; since Java 8 it also includes functional elements.
  • Syntax is the formatting rules. Static semantics are the meaning rules for syntactically correct code that are checked at compile time (type compatibility). Semantics is what the code does; it is single and exact, but may not be what the programmer expects.
  • There are four kinds of errors: syntax and static-semantics errors are found at compile time, run-time errors surface while the program runs as exceptions, and logic errors are found only by testing.
  • Expressions are evaluated with parentheses first, then * / %, then + -, left to right on the same level. The quotient of two integers is an integer and is truncated toward zero. Java has no exponentiation operator; use Math.pow.
  • Assignment has two steps: the right-hand side is computed with the current values, and then written into the variable on the left. = is assignment and == is comparison.
  • Java is statically typed: types are checked at compile time and do not change. Even var fixes the type at compile time. An operation on an int and a double is a double operation. If one operand is a string, + is concatenation and goes from left to right.
  • Strings are compared with equals. Different types are first converted to the same type: Integer.parseInt, String.valueOf.
  • A program consists of statements that run in order. An expression produces a value and a statement produces an effect. The order of statements determines the result; a swap is done with a third, temporary variable.
  • A program is first designed as an algorithm and then translated into code. In the translation, details of type and precedence can change the result.

2.1.12Key terms

  • programming language
  • source code
  • assembly language
  • compiler
  • interpreter
  • bytecode
  • Java Virtual Machine (JVM)
  • just-in-time (JIT) compiler
  • programming paradigm
  • object-oriented programming
  • field
  • constructor
  • reference
  • syntax
  • static semantics
  • semantics
  • run-time error
  • logic error
  • exception
  • expression
  • operand
  • operator precedence
  • integer division
  • variable
  • assignment
  • identifier
  • static / dynamic typing
  • widening conversion
  • type conversion
  • string
  • string concatenation
  • statement

2.1.13Test Yourself

  1. What are the values and types of the expressions 17 / 5 * 5 + 17 % 5 and 17 / 5.0?

    Answer

    The first: 17 / 5 = 3 (integer division), 3 · 5 = 15, 17 % 5 = 2, total 17, of type int. This result is no coincidence: (a / b) * b + a % b always equals a. The second: because 5.0 is double, real division is performed; 3.4, of type double.

  2. What does System.out.println(2 * 3 + "x" + 2 * 3); print?

    Answer

    6x6. The * operator has higher precedence than +; both multiplications are done before the concatenations, and the expression becomes 6 + "x" + 6. Left to right: 6 + "x" = "6x", then "6x" + 6 = "6x6". The multiplications work correctly even without parentheses; the problem arises only when addition with + is what is wanted.

  3. Suppose each line is in a separate program. What is the kind of error (syntax, static semantics, run-time, logic)? (a) boolean b = 1; (b) int n = 5; int y = 10 / (n - 5); (c) double perimeter = 2 * pi + r; for the perimeter of a circle

    Answer

    (a) Static semantics: incompatible types: int cannot be converted to boolean. In Java a boolean is not a number. (b) Run-time: the code compiles, but because n - 5 = 0, ArithmeticException: / by zero is thrown. (c) Logic: the code compiles and runs, but the formula is wrong; the correct one is 2 * pi * r.

  4. After these lines run, what are x and y? int x = 6; int y = x / 4; x = x * y + x % 4; y = x - y;

    Answer

    y = 6 / 4 = 1 (integer division). The right-hand side of the third line is computed with the old x (6): 6 · 1 + 6 % 4 = 6 + 2 = 8; x = 8. The last line: 8 − 1 = 7. The result is x = 8, y = 7.

  5. With a = 1, b = 2, c = 3, the values are to be rotated to the right: a ← c, b ← a, c ← b. In what order is this written with a temporary variable? What is the result?

    Answer

    First save the value that is to be overwritten first. The order int t = c; c = b; b = a; a = t; is correct: t = 3, c = 2, b = 1, a = 3. The result is 3 1 2. Each assignment overwrites a variable whose value has already been copied elsewhere; no value is lost.

  6. What does IntStream.range(2, 6).sum() give? How is the imperative equivalent of the same computation written?

    Answer

    range excludes the upper bound: the numbers 2, 3, 4, 5 are added and 14 is found. The imperative equivalent: int t = 0; for (int i = 2; i < 6; i++) t = t + i;. The loop condition uses <, not <=; with rangeClosed(2, 6) the 6 would be included and the result would be 20.

  7. With int c = 37;, what do the expressions c * 9 / 5 + 32, 9 / 5 * c + 32, and c * 9 / 5.0 + 32 give?

    Answer

    The first: 37 · 9 = 333, 333 / 5 = 66 (fraction discarded), 66 + 32 = 98. The second: 9 / 5 = 1 (integer division), 1 · 37 + 32 = 69; a large error. The third: 333 / 5.0 = 66.6, 66.6 + 32 = 98.6 (double), which is the correct value.

  8. Let x be an int variable. Which of the following compile as a statement on their own? x++;, x + 1;, Math.pow(x, 2);, x == 3;

    Answer

    x++; compiles: it increments x, so it produces an effect. Math.pow(x, 2); compiles too: method calls can be statements, and the returned value is discarded. x + 1; and x == 3; do not compile, and both give the message not a statement; they only produce a value and have no effect.

2.1.14Further reading

  • Oracle, The Java Tutorials, “Language Basics”: explains variables, operators, the precedence table, expressions, and statements with short examples. It is the official, free starting point for Java.
  • A. B. Downey and C. Mayfield, Think Java (2nd ed., 2019), Chapters 1–2: covers programming languages, compilation and interpretation, kinds of errors, and reading error messages. The presentation is aimed at the beginning reader.
  • J. V. Guttag, Introduction to Computation and Programming Using Python (3rd ed., 2021), Chapter 2: the source of the distinction among syntax, static semantics, and semantics. Because it gives the distinction with Python examples, it also lends itself to comparison with dynamic typing.
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 15: defines the order of evaluation of expressions, integer division, and string concatenation with exact rules. The last word on the value of an expression is in this document.

2.1.15References

  1. P. Deitel and H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2017 (Chapters 1–2).
  2. A. B. Downey and C. Mayfield, Think Java: How to Think Like a Computer Scientist, 2nd ed., O’Reilly, 2019 (Chapters 1–2).
  3. J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Oracle, 2023 (Chapter 3: Lexical Structure; Chapter 15: Expressions).
  4. J. Guttag, Introduction to Computation and Programming Using Python, 3rd ed., MIT Press, 2021 (Chapter 2: syntax, static semantics, and semantics).
  5. C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson, 2022 (Chapters 2–3).
  6. Oracle, The Java Tutorials: “Language Basics” (variables, operators, expressions, statements, and blocks).
  7. K. Sierra and B. Bates, Head First Java, 3rd ed., O’Reilly, 2022.

Related pages: Chapter 2.1 slides · Study questions · Glossary · © Sercan Külcü. All rights reserved.