Object-Oriented Programming with Java · Lecture Notes

Chapter 2.2: Syntax Rules

A Java program is handed to the compiler as text. The compiler reads this text character by character and checks whether it follows the rules of the language. If a single semicolon is missing, or a letter is lowercase where it should be uppercase, the program will not run. These notes describe the writing rules of Java and the machinery behind them. The first section follows a .java file as it becomes bytecode through javac and then a running program through the java command. It explains how the JVM works on its stack and why the same .class file runs on every operating system. Next come variables, the eight primitive types, and the limits of those types. Identifiers, keywords, and naming conventions determine how names are chosen. The section on assignment, literals, and type conversion shows how numbers change when they move from one type to another. The last sections cover operators, operator precedence, short-circuit evaluation, the conditional operator, and the syntax of control statements. In every section the code from the slides is explained line by line, and the compiler’s real error messages are shown.

Learning outcomes

Compiling and running
Describe how a .java file becomes bytecode with javac and a running program with java; relate the levels of abstraction; trace bytecode on the JVM stack; explain how the JVM provides platform independence.
Variables and types
Know the eight primitive types with their sizes and ranges; declare variables and assign values; notice overflow and floating-point precision problems.
Rules and naming
Tell a valid identifier from an invalid one, recognize keywords, and follow the camelCase, PascalCase, and UPPER_CASE conventions.
Expressions and flow
Evaluate expressions by operator precedence, perform type conversion; choose a value by a condition with ?:; recognize the syntax of the if, switch, for, while, do-while, break, and continue statements.

2.2.1Compiling and running

A program written in Java goes through several stages before a result appears on the screen. The programmer writes the code in a text file. The compiler checks this text and translates it into an intermediate code. The Java Virtual Machine takes the intermediate code and executes it on the computer’s processor. This section takes the stages in order. Reading error messages correctly, and knowing what happens behind the “Run” button, become possible only once this chain is familiar.

2.2.1.1The source file

Definition 2.2.1

Source code is the human-readable program text that a programmer writes according to the rules of a programming language. Java source code lives in plain text files, and these files have the extension .java.

Plain text is a file made up of characters only. It carries no information about typeface, color, bold type, or page layout. A document saved by a word processor such as Word stores this formatting information next to the text, and the compiler does not understand that extra information. Java code is therefore written in a text editor such as Notepad, Notepad++, or VS Code, or in a development environment.

Plain text is convenient for three reasons:

  • It is readable. A person who opens the file sees the code directly. The code is easy to understand, can be sent by e-mail, and can be kept in a version control system.
  • It is portable. The same .java file opens on every operating system and in every development environment.
  • It is easy to edit. Any text editor is enough to fix a bug or update the code.

Java also imposes a rule on file names. If a file contains a public class, the file’s name must be exactly the same as the class name. Code that begins with public class HelloWorld is saved in a file named HelloWorld.java. Uppercase and lowercase matter in this match too. If the same code is saved as helloworld.java, the compiler gives this message:

helloworld.java:1: error: class HelloWorld is public, should be declared in a file named HelloWorld.java
public class HelloWorld {
       ^
1 error

Although the Windows file system does not distinguish uppercase from lowercase, javac does. The message says exactly what is wrong: the class HelloWorld is public and must be declared in a file named HelloWorld.java.

2.2.1.2Programming tools

Several tools are used together to write a Java program. Table 2.2.1 summarizes these tools and their roles.

Table 2.2.1: Tools used to develop programs in Java.
ToolWhat is it for?Examples
Text editorWriting source code as plain textNotepad++, VS Code
JDK (Java Development Kit)The compiler, the launcher, and other development toolsjavac, java, javap, jshell
IDE (integrated development environment)Editing, compiling, running, and debugging in one window; errors are underlined as you typeEclipse, IntelliJ IDEA, NetBeans, VS Code with Java extensions
JShell (Java 9 and later)Trying out one-line Java expressions without writing a classjshell> 7 / 2 → 3

The JDK (Java Development Kit) is the package that contains everything needed to develop programs in Java. It includes the compiler javac, the java command that starts a program, javap, which shows the inside of a .class file, and the interactive experimentation environment jshell. An IDE (integrated development environment) combines these tools with an editor. When you press the “Run” button in an IDE, javac and java still run in the background.

JShell is very handy for small experiments. Someone who wonders why 7 / 2 gives 3 and not 3.5 can type the expression into JShell without writing a class and a main method, and see the result at once. It is also worth using javac and java from the command line at least once at the start. The steps an IDE hides then become visible, and when an error appears you can tell at which stage it appeared.

2.2.1.3The first program: HelloWorld

The program below is one of the shortest complete programs that can be written in Java. It prints a single line to the screen.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Short as it is, every part of the program follows a rule:

  • public class HelloWorld defines a class. Every Java program contains at least one class. The body of the class is the part between the { on this line and the } on the last line. Because the class is public, the file must be named HelloWorld.java.
  • public static void main(String[] args) is the entry point of the program. When the JVM starts the program, it begins running from this method. The header must be written exactly this way. If Main or main(String args) is written, the program compiles, but the JVM cannot find the entry point and refuses to run it.
  • System.out.println(...) writes the value in parentheses to the console and moves to the next line. Text is written in double quotes: "Hello, World!".
  • The semicolon at the end of the line shows that the statement is over. Every statement ends with ;. Blocks closed by braces need no ; after them, which is why there is no semicolon after the closing brace of the class or of the method.

The body of the program consists of two nested blocks. The outer block is the body of the class and the inner block is the body of the main method. Indentation, that is, the spaces at the beginning of the lines, makes this nesting visible to the eye. The compiler does not look at indentation; it only counts braces.

2.2.1.4Basic syntax rules

Definition 2.2.2

Syntax is the set of writing rules of a language: it determines which words, symbols, and orderings are valid. Java code that breaks the syntax rules does not compile.

In English, the phrase “Book the read I” has an unusual order but can be understood. The compiler is not so tolerant. It does not correct a line that breaks the rules by guessing; it reports an error and stops. The basic writing rules of Java are:

  • Every statement ends with ;.
  • Blocks are opened with { and closed with }. Every block that is opened must be closed.
  • Java is case-sensitive: num and Num are two different names; system cannot be written in place of System.
  • Spaces, tabs, and line breaks are unimportant to the compiler. A statement can be split over several lines. Indentation is used for readability.
  • Comments are written in two forms: // runs to the end of the line, and /* … */ can span several lines. The compiler ignores comments.

The program below shows all of these rules together.

/* Multi-line comment:
   the compiler ignores it. */
public class Rules {
    // Single-line comment
    public static void main(String[] args) {
        int num = 5;  // ends with ;
        int Num = 7;  // num ≠ Num
        System.out.println(num
                + Num);   // a line can be split
    }
}

The program gives this output:

12

The first two lines form a multi-line comment and add nothing to the compiled code. num and Num are two separate variables because of the difference in case: one holds 5 and the other 7. The println call is split over two lines. For the compiler this split is unimportant, because a statement ends only when a ; is seen. The 12 in the output is the sum of the two variables. That two variables can sit side by side shows how important a single letter in a name can be. In real programs, such similar names cause confusion and should be avoided; the aim here is only to show the rule.

Common mistake

Mixing up uppercase and lowercase. The three lines below are typical mistakes caused by habits of writing everything in lowercase. The compiler gives a separate message for each:

Case.java:3: error: package system does not exist
        system.out.println("a");
              ^
Case.java:4: error: cannot find symbol
        string s = "b";
        ^
  symbol:   class string
  location: class Case
Case.java:5: error: cannot find symbol
        Int n = 3;
        ^
  symbol:   class Int
  location: class Case
3 errors

When system.out is written, the compiler takes system to be a package name and cannot find that package. string and Int look like class names that are not defined. The correct forms are System, String, and int. String starts with an uppercase letter because it is a class, and int with a lowercase letter because it is a keyword.

2.2.1.5Levels of abstraction

A processor understands only commands encoded as binary numbers. A person thinks more like “add a and b and store the result in sum.” On the way from person to processor there are three levels, and each level hides the details of the one below it.

  • A high-level language is close to the problem domain. Java, C, and Python are at this level. The code is short, readable, and understandable, and the programmer works more productively.
  • Assembly language writes processor instructions with short names such as MOV and ADD. Each line often corresponds to a single machine instruction. It is a lower level of abstraction.
  • The hardware representation consists only of bits. Instructions and data go directly to the hardware in this form.
High-level language (Java)sum = a + b;compilerAssembly language (x86)mov eax, ebx · add eax, ecxassemblerHardware representation (machine code)10001001 11011000 00000001 11001000
Figure 2.2.1: Three levels of the same addition. The single line in Java corresponds to two instructions in assembly language and to two machine instructions of two bytes each in hardware.

Figure 2.2.1 shows the counterparts of the line sum = a + b at the three levels. The example assumes that the variables a, b, and sum live in the registers ebx, ecx, and eax respectively. In assembly language, the value of a is first copied into eax (mov eax, ebx), and then b is added on top of it (add eax, ecx). The machine code is the real encoding for x86 processors: the first instruction is the hexadecimal bytes 89 D8 and the second is 01 C8. As abstraction increases, the code gets shorter and more readable. The translation to the lower level is done by a compiler or an assembler.

Java adds an intermediate layer to this picture. The Java compiler does not translate source code directly to x86 machine code. It first translates it to a code called bytecode, which belongs to no real processor. This intermediate code allows the same compiled program to run on different processors.

2.2.1.6Compilation

Definition 2.2.3

Compilation is the translation of source code, as a whole, into another language. The program that does this is called a compiler. The Java compiler javac translates source code not into the machine language of a processor but into bytecode, which the Java Virtual Machine understands, and writes the result to a file with the extension .class.

A computer cannot run .java text directly. The text has to be compiled first. The path from source code to the output on the screen is completed in four steps:

  1. The programmer writes the source code as plain text and saves it as HelloWorld.java.
  2. The command javac HelloWorld.java runs the compiler. The compiler checks the syntax and the types. If there are no errors, the file HelloWorld.class is created in the same folder.
  3. The command java HelloWorld runs the launcher. The launcher starts the JVM and loads the class. The JVM interprets the bytecode and translates the frequently executed parts into machine code with the JIT compiler.
  4. The operating system and the processor carry out the actual instructions; Hello, World! appears on the screen.
HelloWorld.javasource code (plain text)javaccompilerHelloWorld.classbytecodeJVM (java)interpreter + JITOperating systemand processor1. write2. compile3. run4. outputcompile time: once, on the developer's machinerun time: on every run
Figure 2.2.2: The compile-and-run pipeline. The .java file becomes a .class file with javac, and the .class file becomes a running program with the JVM.

In Figure 2.2.2 there are two separate commands and two separate periods of time. Compile time is the time during which javac runs; during it the program does not run yet, it is only checked and translated. Run time begins with the java command. It matters at which time an error appears. A compile-time error means the program never runs at all. A run-time error appears while the program is running; division by zero is an example.

The greatest benefit of the compilation stage is that errors are caught before the program runs. The compiler finds a missing semicolon, an unclosed parenthesis, a misspelled name, and incompatible types. If there is an error, no .class file is produced. The file name:line information in the message shows where the error is. If the semicolon on line 3 of the HelloWorld program is forgotten, the line becomes:

System.out.println("Hello, World!")

For this line the compiler gives this message:

HelloWorld.java:3: error: ';' expected
        System.out.println("Hello, World!")
                                           ^
1 error

The first line of the message gives the file (HelloWorld.java), the line number (3), and the kind of error (';' expected, that is, a semicolon was expected). The second line repeats the faulty code. The ^ mark on the third line shows where the compiler expected the semicolon: immediately to the right of the closing parenthesis. The last line reports the total number of errors. The compilation stage also contributes to the speed of the program. The compiler does jobs such as type checking once, so they need not be repeated while the program runs. The JVM’s optimizations at run time come on top of this.

Common mistake

Not looking before the line that the message points to. When a semicolon is missing, the compiler usually notices it only when it reads the next token, so the message sometimes points one line down. If a puzzling ';' expected message appears on a line, first look at the end of the previous line.

2.2.1.7Compiling and running from the command line

There are three basic steps in working with Java. In the compile step the .java file is turned into a .class file: javac HelloWorld.java. In the run step the java command is given the class name without an extension: java HelloWorld. The third step is the output: the program prints Hello, World! on the screen. A command-line session looks like this:

> javac HelloWorld.java
> dir /b
HelloWorld.class
HelloWorld.java
> java HelloWorld
Hello, World!

If javac printed nothing, the compilation succeeded. The dir /b command that follows (ls on Linux and macOS) lists the files in the folder. The list shows the newly created HelloWorld.class next to the source file. The last command runs the program.

HelloWorld.javasource codejavacHelloWorld.classbytecodejavaJVMrunsHello, World!output
Figure 2.2.3: Two commands, two files: javac turns the source file into a .class file; java starts the JVM and the program produces output.
Common mistake

Writing the extension when running: java HelloWorld.class. The JVM expects a class name, not a file name. This command looks for a class named HelloWorld.class and stops with the message “Could not find or load main class.” The correct form is without the extension: java HelloWorld.

Java 11 added a shortcut for single-file programs. The command java HelloWorld.java compiles the file in memory and runs it at once. No .class file is written to disk this way. The shortcut is practical for small experiments, but programs made of several files use the two-step route.

2.2.1.8Bytecode

Definition 2.2.4

Bytecode consists of the instructions, independent of processor and operating system, that javac produces and the Java Virtual Machine executes. .class files do not contain machine code that a processor can understand directly; they contain bytecode. Bytecode is the “machine language” of the JVM.

The name comes from the structure of the instructions: the opcode of each instruction is a single byte. Any extra information the instruction needs, such as a constant or the number of an entry in a table, sits in the bytes after the opcode. A one-byte opcode means at most 256 different instructions, and that is enough for the JVM.

Bytecode is not tied to a processor or an operating system. The same .class file runs on Windows, on Linux, and on macOS. An analogy describes the relationship well: bytecode is like a musical score that reads the same in every country, and the JVM on each computer is the musician who plays that score on its own instrument. The score does not change; the instrument and the musician do.

A .class file is a binary file and looks like meaningless characters in a text editor. The command javap -c ClassName in the JDK lists the bytecode instructions in this file in readable form. Consider this two-line code: int x = 5; System.out.println(x);. When the code is placed inside a main method and compiled with JDK 21, javap -c gives this listing:

0: iconst_5
1: istore_1
2: getstatic     #7    // System.out
5: iload_1
6: invokevirtual #13   // println(int)
9: return

The number at the beginning of each line is the instruction’s byte position within the method. The positions go 0, 1, 2, 5, 6, 9. iconst_5 and istore_1 are one-byte instructions. getstatic and invokevirtual carry a two-byte table number after the opcode, so each takes three bytes.

The JVM is a stack machine. Real processors keep values in registers. The JVM’s instructions push values onto an operand stack and take them from it. A stack is like plates piled on top of one another: the one put on last is taken first. The instructions do the following in order:

  1. iconst_5: the constant 5 is pushed onto the operand stack. Its counterpart in the source is the right-hand side of int x = 5;.
  2. istore_1: the value on top of the stack is taken and written to local variable number 1, that is, x. The stack is empty again.
  3. getstatic #7: a reference to the System.out object is pushed onto the stack. #7 is entry number 7 in the class file’s constant pool.
  4. iload_1: the value of x (5) is copied onto the stack. Its counterpart in the source is the line System.out.println(x);.
  5. invokevirtual #13: the method println(int) is called. The method takes two values from the stack: the object it is to work on (System.out) and the number to print (5). 5 is written to the screen.
  6. return: main ends, and the program terminates.
operand stack5local variables0: args = array1: x = — operand stacklocal variables0: args = array1: x = 5 operand stackout5local variables0: args = array1: x = 5
Figure 2.2.4: The operand stack and the local variables while bytecode runs. (a) After iconst_5 the stack holds 5 and x is still empty. (b) After istore_1 the stack is empty and x = 5. (c) After iload_1 the stack holds the System.out reference and 5; println will take these two.

Figure 2.2.4 shows three moments. The difference between (b) and (c) matters: iload_1 copies the value from the local variable onto the stack. x stays where it is and its value does not change. Reading a variable does not consume it; this holds at the bytecode level too.

2.2.1.9An addition on the JVM stack

The stack-machine idea is clearer in an addition. Consider these three lines:

int a = 5;
int b = 7;
int sum = a + b;
System.out.println(sum);

The compiled form of these lines is twelve instructions. The comments give the source-code counterpart of each instruction:

iconst_5        // push 5
istore_1        // a = 5
bipush 7        // push 7
istore_2        // b = 7
iload_1         // load a
iload_2         // load b
iadd            // add
istore_3        // sum = 12
getstatic       // System.out
iload_3         // load sum
invokevirtual   // println(int)
return

The JVM uses no register to add. It pushes the two numbers onto the stack, the iadd instruction pops the top two values and adds them, and it pushes the result back onto the stack. Table 2.2.2 gives the operand stack and the local variable table after each instruction. Slot 0 of the local variable table holds main’s parameter args; the table shows it as “…”. a, b, and sum take slots 1, 2, and 3 respectively.

Table 2.2.2: The state of the JVM after each instruction in the example int sum = a + b;. The top of the stack is on the right.
InstructionOperand stack1: a2: b3: sumExplanation
iconst_55the constant 5 is pushed
istore_1empty5a = 5
bipush 775the constant 7, which fits in one byte, is pushed
istore_2empty57b = 7
iload_1557a is copied
iload_25, 757b is copied
iadd1257two values come off, the sum goes on
istore_3empty5712sum = 12
getstaticout5712the System.out reference
iload_3out, 125712the argument of println
invokevirtualempty571212 is written to the screen
returnempty5712main ends
operand stacklocal variables570 args…1 a52 b73 sum operand stacklocal variables120 args…1 a52 b73 sum operand stacklocal variables0 args…1 a52 b73 sum12
Figure 2.2.5: Three moments of the addition. (a) After iload_2 the stack holds 5 and 7. (b) iadd pops both and pushes 12. (c) istore_3 writes 12 into the slot of sum and the stack becomes empty.

Three observations follow from the table. First, iconst_5 is used for 5, but bipush 7 for 7. In the JVM each small constant from −1 to 5 has its own one-byte instruction. Since 7 is not in this range, bipush, meaning “push a byte,” is written, followed by a byte carrying the value 7. Second, the stack is emptied at the end of every statement. The stack stays full only for the short time during which an expression is being computed. Third, the iload instructions do not consume the variables; a and b remain 5 and 7 after the addition.

The letter i in the instruction names indicates the type int. There are separate instructions such as ladd for long and dadd for double. The JVM knows which type it is working with in every operation. This is one reason types are checked at compile time: the compiler decides which instruction to generate by looking at the type. The same bytecode runs in this order on the JVM of every operating system.

2.2.1.10The Java Virtual Machine and the JIT compiler

Definition 2.2.5

The Java Virtual Machine (JVM) is the software that runs Java applications. It interprets bytecode and executes it in a way suited to the processor it is on. It translates frequently executed pieces of bytecode into machine code at run time with the JIT (just-in-time) compiler.

The name “virtual machine” comes from the fact that the JVM behaves like a computer with its own instruction set. This computer does not exist as hardware; it runs as a program on top of the real computer. The internal structure of the JVM has four main parts:

  • The class loader finds the needed .class files and brings them into memory.
  • The verifier checks that the loaded bytecode follows the rules. For example, it makes sure that an instruction does not try to take a value that is not on the stack. A corrupted or malicious file therefore cannot crash the JVM.
  • The interpreter reads the bytecode instructions one by one and does the work corresponding to each.
  • The JIT compiler notices code fragments that run many times and translates them directly into machine code. In later runs this machine code is used instead of interpretation.
MyClass.classbytecodeJVMclass loaderverifierinterpreterJIT compileroperating system+ processor
Figure 2.2.6: The internal structure of the JVM: class loader, verifier, interpreter, and JIT compiler. The work produced goes to the operating system.

Interpretation is flexible but slow: every instruction is decoded again each time it is run. Machine code is fast, but producing it takes time. The JIT strikes a balance between the two. Code that runs once is interpreted; a loop body that runs thousands of times is compiled. A Java program therefore speeds up over time. This effect is noticeable in long-running server programs.

The java command that starts the program is called the Java launcher tool in the JDK documentation. The launcher starts the JVM, loads the class whose name is given, and calls the main method of that class. When main ends, the JVM shuts down too.

2.2.1.11Platform independence and the Java platform

Definition 2.2.6

A platform is the hardware or software environment in which a program runs: the combination of a processor and an operating system. Platform independence means that the same compiled program runs, without being recompiled, on every platform that has a JVM.

Platform independence is one of the fundamental features of Java and is known by the slogan “Write Once, Run Anywhere.” The program is compiled once, and the same bytecode runs on different operating systems. What makes this possible is that JVMs have been written separately for many operating systems and processors. A JVM written for Windows translates bytecode into x86 machine code. The JVM on a Mac with an ARM processor translates the same bytecode into ARM machine code. The difference is in the JVM, not in the bytecode.

Program.classone bytecodeJVM for WindowsWindows · x86-64JVM for LinuxLinux · ARM / x86JVM for macOSmacOS · Apple M
Figure 2.2.7: Platform independence. The same .class file runs on JVMs written for Windows, Linux, and macOS.

In languages such as C the situation is different. A C compiler produces machine code directly, and this code is tied to the platform it was compiled on. A C program compiled on Windows does not run on Linux; a separate build is needed for every platform. In Java this burden passes to those who write the JVMs. The programmer distributes a single .class file, and it is enough for the user’s computer to have a JVM.

The Java platform has two main components:

  • The JVM runs applications and provides portability across different hardware.
  • The API (Application Programming Interface) consists of ready-made class libraries. It provides many functions out of the box, such as graphical interfaces, databases, network communication, and file operations, and speeds up development. System, String, Math, and Scanner are classes in these libraries.
JDK: development kitjavac · javap · jshell · jar …Runtime (JRE)API (libraries)java.lang · java.util · java.io …JVMruns bytecode
Figure 2.2.8: The layers of the Java platform. The JDK contains the runtime environment, and the runtime environment contains the API libraries and the JVM.

Figure 2.2.8 shows that the layers are nested. The runtime environment (JRE, Java Runtime Environment) contains what is needed to run a Java program, namely the JVM and the API libraries. The JDK adds the compiler and the other development tools on top of these. To develop programs, the JDK is installed. Since Java 11, Oracle has not distributed the JRE as a separate package; the JDK contains everything.

2.2.2Variables and data types

A program takes in data, processes it, and produces a result. At every moment of this process the data has to be held somewhere. Variables do this job. Java wants to know in advance what kind of data each variable holds; this information is called the type. This section covers variables, Java’s eight primitive types, and the limits of each type.

2.2.2.1Basic programming elements

Every program, in whatever language it is written, is built from a few basic elements. Variables store data. Every variable has a type. Values are computed with expressions: num > 0 and sum + 1 are expressions. Control flow determines in what order and how the program runs. Control flow has two basic forms:

  • Branching runs different parts of the program depending on a condition. if-else is an example.
  • Loops repeat an operation. for and while are examples.

The following fragment brings together a variable, a condition, and output:

int num = 5;
if (num > 0) {
    System.out.println("Positive.");
} else {
    System.out.println("Zero or negative.");
}
Positive.

Because num is 5, the expression num > 0 is true and the first block runs. The else block is skipped. If num were 0 or negative, the first block would be skipped and the second would run. Here the value of the expression num > 0 is not a number but a piece of true-or-false information. Java uses a separate type for this information: boolean.

2.2.2.2Variables and declarations

Definition 2.2.7

A variable is a location in memory that stores a value and has a name and a type. Introducing a variable before it is used is called a declaration. In a declaration the type is written first, then the name, and the declaration ends with ;.

A variable can be pictured as a box with a name written on it. The label on the box carries two pieces of information: its name and what kind of thing may be put in it. Only an integer goes into a box labeled int, and only a floating-point number into a box labeled double. The value inside the box can change while the program runs; its name and type do not.

id1042intinterestRate0.45doubleanswer'E'char
Figure 2.2.9: Variables are like labeled boxes: id (int) holds 1042, interestRate (double) holds 0.45, and answer (char) holds 'Y'.

In Java every variable must be declared before it is used. Several variables of the same type can be declared on one line, separated by commas:

int id, checkCount, stockCount;
double amount, interestRate;
char answer;

The first line declares three int variables, the second two double variables, and the third one char variable. A declaration has three forms: type name;, type name1, name2, name3;, and type name = initialValue;. The last also gives the variable its first value together with the declaration.

Names should be chosen to be descriptive and meaningful. The name x says nothing about what the variable holds. checkCount, on the other hand, makes it clear at once that it holds the number of checks in an account. The person who rereads the code a few months later is often the person who wrote it. Meaningful names make that person’s job easier.

2.2.2.3Declaration, assignment, update

A variable’s life proceeds through three events: it is declared, it receives a value, and that value is updated. The code below contains all three events:

int age;
age = 25;
double height = 1.78;
age = age + 1;
char letter = 'K';
System.out.println(age + " " + height + " " + letter);

The program prints 26 1.78 K. Table 2.2.3 shows the boxes in memory after each line.

Table 2.2.3: Trace of declaration, assignment, and update. “?” marks a box with no value assigned, and an empty cell marks a variable not yet declared.
LineCodeageheightletterExplanation
1int age;?a box is set aside, empty
2age = 25;25assignment: 25 is put in the box
3double height = 1.78;251.78declaration and initial value on one line
4age = age + 1;261.78first 25 + 1 = 26 is computed
5char letter = 'K';261.78'K'a character is written in single quotes
6println(…)261.78'K'output: 26 1.78 K
age?int age25int age26intheight1.78double
Figure 2.2.10: Three moments in the life of a variable. (a) int age; sets the box aside, empty. (b) age = 25; puts 25 in the box. (c) After age = age + 1; the box holds 26; the old value is gone.

After line 1 there is a box called age but no value in it. In this state age cannot be read; code that tries to read it does not compile. Line 4 is an update. The right-hand side is computed first: the 25 in the box is read and 1 is added. The result, 26, is written into the same box and the old value is lost. In the expression age + " " + height + " " + letter on line 6, the + sign does not add numbers. Because one of the operands is text, it appends the values to the text. This operation is called string concatenation.

2.2.2.4The eight primitive types

Definition 2.2.8

A data type determines which values a variable can take, how much memory it occupies, and which operations can be performed on it. Java’s eight basic types built into the language are called primitive types: byte, short, int, long, float, double, char, and boolean.

The eight types fall into four groups:

  • Integer: byte, short, int, long.
  • Floating-point: float, double.
  • Character: char.
  • Logical: boolean.
byte1 byteshort2 bytesint4 byteslong8 bytesfloat4 bytesdouble8 byteschar2 bytesbooleantrue / false (size depends on the JVM)
Figure 2.2.11: The memory occupied by the primitive types: byte 1, short 2, int 4, long 8, float 4, double 8, char 2 bytes. The size of boolean is determined by the JVM.

Each type has its own size in memory and a range of values that follows from it. As the number of bits grows, a type can hold larger numbers but takes more memory. In C the size of int can vary with the compiler and the processor. In Java, sizes are fixed by the definition of the language: int is 32 bits on every platform. This fixedness is part of platform independence too.

In everyday use, int is the default choice for integers and double for floating-point numbers. byte and short are mostly used in special cases, such as saving memory in large arrays or reading bytes from a file. float is rarely preferred outside graphics and some embedded systems.

2.2.2.5Integer types

Table 2.2.4: Integer types, their memory sizes, and their ranges.
TypeMemorySmallest valueLargest valueExample
byte1 byte (8 bits)−128127byte b = 100;
short2 bytes (16 bits)−32,76832,767short s = 32000;
int4 bytes (32 bits)−2,147,483,6482,147,483,647int n = 1_000_000;
long8 bytes (64 bits)−9,223,372,036,854,775,8089,223,372,036,854,775,807long l = 3000000000L;
byte8 bitsshort16 bitsint32 bitslong64 bits
Figure 2.2.12: The bit widths of the integer types: byte 8, short 16, int 32, long 64 bits.

All four types are signed: they take both positive and negative values. The range of an n-bit type is from −2n−1 to 2n−1 − 1. For byte, n = 8, and the range lies between −27 = −128 and 27 − 1 = 127. The positive side is one short because zero also takes a place in the positive half: 8 bits give 256 different values; 128 of them are negative, one is zero, and 127 are positive.

There is no need to memorize the limits. Java provides constants for every type: Byte.MIN_VALUE, Byte.MAX_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, and so on. Still, it is useful to know that the upper limit of int is about 2.1 billion. The world’s population, a month measured in milliseconds, or a country’s budget exceeds this limit.

An integer written directly in code, such as 42, is taken to be an int. To write a number beyond the int range as a long, add L to the end: 3000000000L. A lowercase l is valid too, but it looks so much like the digit 1 that the uppercase letter is preferred. If the L is forgotten, the compiler gives the message integer number too large: before the number is assigned to the long variable, it is read as an int and does not fit.

2.2.2.6Floating-point types

Numbers with fractional parts are stored in a computer in floating-point form. This form is the binary-base counterpart of scientific notation. A number consists of a sign, an exponent, and a fraction: in the number 6.02 × 1023, 6.02 is the fraction and 23 is the exponent. The fraction holds the significant digits and the exponent determines where the point goes. The point “floats” according to the magnitude of the number; hence the name.

Table 2.2.5: Floating-point types. “Smallest positive” is the smallest positive value other than zero.
TypeMemorySmallest positiveLargest (±)Significant digits
float4 bytes (32 bits)≈ 1.4 × 10−45≈ 3.4028235 × 1038≈ 7
double8 bytes (64 bits)≈ 4.9 × 10−324≈ 1.7976931348623157 × 10308≈ 15–16
float±exponent 8fraction (significand) 23double±exponent 11fraction (significand) 52
Figure 2.2.13: The bits of a floating-point number. float: 1 sign bit, 8 exponent bits, 23 fraction bits. double: 1 sign bit, 11 exponent bits, 52 fraction bits.

Figure 2.2.13 shows the difference between the two types. The fraction part of double is 52 bits, which corresponds to about 15–16 decimal digits. The 23-bit fraction of float holds about 7 digits. double is double precision: compared with float it has both a wider range and more digits. The negative limits in the table are the largest values with a minus sign.

A floating-point number written in code, such as 3.14, is taken to be a double. For a float, add f at the end: 3.14f. The difference in digits shows even in a small computation:

System.out.println(1.1f * 3);   // 3.3000002
System.out.println(1.1 * 3);    // 3.3000000000000003

Neither result is exactly 3.3. The error in the float shows in the seventh digit, and the error in the double in the sixteenth. The source of the error is the number itself: 1.1 cannot be written as a finite fraction in binary, so it is stored rounded to the nearest representable value.

2.2.2.7char and boolean

char holds a single character. It occupies 2 bytes (16 bits) in memory and is unsigned: its range is 0 to 65,535. Each value is a Unicode character code. Unicode is an international standard that gives a number to the characters of the world’s writing systems. char literals are written in single quotes: 'A', 'ş', '7'. The difference between single and double quotes matters: 'A' is a char, while "A" is a String of one character.

Knowing the code of a character makes it possible to compute with characters. Three codes are used often: 'A' = 65, 'a' = 97, '0' = 48. The codes of the letters and digits of the English alphabet are the same as those in the ASCII table and are consecutive: 'B' = 66, 'C' = 67, '1' = 49. The code of the character '7' is not 7 but 55. The digit character and the numeric value of the digit are different things.

boolean holds a logical value. It has only two values: true and false. The information it carries is one bit; how many bytes it takes in memory is determined by the JVM. Unlike in C, a boolean in Java is not a number. boolean done = 0; does not compile, and if (1) cannot be written. boolean values are used in conditions and for the results of comparisons:

boolean passed = score >= 50;

In this line the result of the comparison score >= 50, that is, true or false, is written into the variable passed. If score is 72, passed becomes true.

char letter = 'A';
boolean valid = true;
System.out.println(letter);
System.out.println(valid);
System.out.println(!valid);
A
true
false

When println is given a char, it writes the character itself: A. It does not write its code, 65. boolean values are written as the words true and false. The ! sign on the third line is the logical NOT operation and turns true into false.

2.2.2.8Seeing the limits with a program

Instead of memorizing the tables, you can print the limits with a program. Every primitive type has a wrapper class: Byte for byte, Integer for int, Double for double, and Character for char. These classes provide the limits of the type through the constants MIN_VALUE and MAX_VALUE.

System.out.println("byte  : " + Byte.MIN_VALUE + " .. " + Byte.MAX_VALUE);
System.out.println("short : " + Short.MIN_VALUE + " .. " + Short.MAX_VALUE);
System.out.println("int   : " + Integer.MIN_VALUE + " .. " + Integer.MAX_VALUE);
System.out.println("long  : " + Long.MIN_VALUE + " .. " + Long.MAX_VALUE);
System.out.println("float : " + Float.MIN_VALUE + " .. " + Float.MAX_VALUE);
System.out.println("double: " + Double.MIN_VALUE + " .. " + Double.MAX_VALUE);
System.out.println("char  : " + (int) Character.MIN_VALUE + " .. "
                              + (int) Character.MAX_VALUE);
byte  : -128 .. 127
short : -32768 .. 32767
int   : -2147483648 .. 2147483647
long  : -9223372036854775808 .. 9223372036854775807
float : 1.4E-45 .. 3.4028235E38
double: 4.9E-324 .. 1.7976931348623157E308
char  : 0 .. 65535

4.9E-324 in the output is scientific notation and means 4.9 × 10−324. The letter E is read as “times ten to the power.” In the float and double lines, the value on the left is not the smallest negative number but the smallest number greater than zero. This differs from the integer types and is often confused. The (int) cast is used on the char line. Without the cast, println would try to write these two values as characters. Code 0 is an invisible control character, and 65,535 is not a printable character either.

2.2.2.9Overflow

Definition 2.2.9

Overflow occurs when the result of an operation does not fit in the range of values of its type. In Java, integer overflow raises no error: the value wraps around to the other end of the range.

Overflow is easy to picture with a clock. If the hand is at 12 and moves one hour forward, it goes to 1, not 13. Integer types behave the same way: adding 1 to the largest value returns to the smallest. What matters is that this happens silently. The program gives neither a compile-time error nor a run-time error; it carries on with the wrong result.

int max = Integer.MAX_VALUE;
System.out.println(max);
System.out.println(max + 1);   // overflow!
byte n1 = 80;
byte n2 = 50;
byte sum = (byte) (n1 + n2);
System.out.println(sum);        // not 130
long fixed = (long) max + 1;
System.out.println(fixed);
2147483647
-2147483648
-126
2147483648

The lines run as follows:

  • max holds the largest value of int, 2,147,483,647, and this value is printed on the first line.
  • max + 1 is an addition between two int values, and its result is an int too. The result does not fit and wraps around to the smallest value: -2147483648.
  • n1 + n2 gives 80 + 50 = 130. 130 exceeds 127, the limit of byte. The (byte) cast takes the last 8 bits of the result, and the value becomes 130 − 256 = −126.
  • In the expression (long) max + 1 the cast is done before the addition. The operation proceeds in long; the 64-bit range holds 2,147,483,648 comfortably.
125126127−128−127−126+1byte: adding 1 to the maximum “wraps” to the minimum
Figure 2.2.14: Overflow. When 1 is added to 127 in type byte, the value becomes −128; the number line closes up like a circle.

The fix is to use a wider type. But where the cast goes matters. The line long wrong = max + 1; still gives −2147483648. The right-hand side is computed between two int values and overflows first; only the overflowed result is assigned to the long variable. The conversion must be done before the operation: (long) max + 1 or max + 1L.

Example 2.2.1

What comes out if the square of one million is computed with int? With int million = 1_000_000;, the true value of million * million is 1012, which is far beyond the limit of about 2.1 billion for int. The result Java gives is -727379968. This value is the signed reading of the last 32 bits of the binary representation of 1012. When the same computation is written (long) million * million, the correct result, 1000000000000, is obtained. Here the negative result gives the overflow away. Not every overflow is this obvious; the result may be positive but wrong.

Let us follow step by step how overflow arises at the bit level, using a byte counter:

byte b = 125;
for (int i = 1; i <= 4; i++) {
    b++;
    System.out.println(b);
}

b starts at 125 and the loop runs four times. Table 2.2.6 gives the value and the binary representation in each pass.

Table 2.2.6: Trace of the byte counter. The leftmost bit is the sign bit and has weight −128.
ii <= 4After b++BinaryOutput
——125 (start)01111101
1true12601111110126
2true12701111111127
3true−12810000000-128
4true−12710000001-127
5false——loop ends
b (byte)= 1270-12816413211618141211−1280127 b (byte)= -1281-12806403201608040201−1280127
Figure 2.2.15: The moment of overflow. (a) b = 127, binary 01111111: the largest value of byte. (b) Adding 1 gives 10000000 in binary addition; the sign bit becomes 1 and the value wraps to −128.

The cause of overflow is binary addition itself. The binary representation of 127 is 01111111. When 1 is added, all the 1s turn to zero and the carry moves into the leftmost bit: 10000000. This bit is the sign bit, and its weight is −128, not +128. Since the other bits are zero, the value is −128. This representation is called two’s complement. It was chosen because the processor can use the same addition circuit for both positive and negative numbers. The program prints 126, 127, −128, −127 and gives no warning.

The b++ line in the table needs a note too. If b = b + 1; had been written, the code would not compile, because b + 1 is an int expression and can be assigned to a byte only with an explicit cast. The ++ and compound assignment operators perform the conversion themselves. Overflow is also a consequence of this hidden conversion.

2.2.2.10Primitive types and reference types

Definition 2.2.10

A variable of a primitive type stores the value itself. A variable of a reference type points to an object: the variable holds not the object itself but its location in memory, that is, a reference to the object.

stack: local variablesint age20double avg3.25String name•heap: objectsString object"Ayşe"a primitive variable holds the value · a reference variable holds the object's address
Figure 2.2.16: Primitive and reference types. int and double variables hold the value directly; a String variable refers with an arrow to an object in heap memory.

There are eight primitive types, and their names begin with a lowercase letter. All the remaining types are reference types. String (a sequence of characters), arrays, classes, interfaces, and enums are in this group. The names of reference types begin with an uppercase letter. Objects are usually created with new. String is a common exception to this rule: a string literal such as "Ali" creates an object even without new.

A reference that points to no object has the value null. null must not be confused with the empty string. The empty string "" is a real object and has length zero: "".length() gives 0. null means “there is no object here.” If a method is called on a null reference, the program stops with NullPointerException. For a local String variable three situations are distinct. Code that prints a variable to which no value has been assigned does not compile. A variable assigned null prints null. A variable assigned "" prints an empty line.

The difference between the two groups of types shows in assignment too. After the lines int a = 5; int b = a;, b holds a separate copy of 5; when b changes, a is not affected. Two reference variables, however, can point to the same object. This distinction is one of the fundamental topics of object-oriented programming.

2.2.3Identifiers and keywords

Each of the variables, methods, and classes in a program has a name. The programmer is free to choose these names, but the limits of that freedom are clear. Some characters cannot be used in names, and some words are reserved for the language. There are also writing habits that the Java community follows. This section takes up the three levels in turn: the compiler’s mandatory rules, reserved words, and conventions.

2.2.3.1Identifier rules

Definition 2.2.11

An identifier is the name given to variables, classes, methods, and other program elements.

Identifiers follow these rules:

  • They may contain only letters, digits (0–9), the underscore _, and the dollar sign $. Characters such as spaces, -, @, and . cannot appear.
  • The first character must be a letter, _, or $. An identifier cannot start with a digit.
  • Keywords and the literals true, false, and null cannot be identifiers.
  • There is no length limit.
  • Uppercase and lowercase are distinct: personName and personname are different variables. A name written differently from its declaration gives a cannot find symbol error.

There is a reason for the ban on starting with a digit. When the compiler sees a digit, it starts reading a number. Meeting 2count, the compiler first reads the number 2 and then treats the count that follows as a separate word. For the same reason first-last is read as “first minus last,” because - is the subtraction operator.

Java accepts as letters not only English letters but all Unicode letters. A variable named öğrenci (“student” in Turkish) compiles and runs. Even so, it is recommended to use only ASCII letters in names. When files are opened with a different character encoding, accented letters can be corrupted, and the code may stop compiling on other systems. That is why names are written studentNo and counter, not with accented letters. Valid examples: userName, totalScore, student_name, data1, _counter.

2.2.3.2Valid and invalid names

Table 2.2.7: Examples of identifiers. ✓ valid, ✗ invalid.
NameStatusWhy?
studentNo✓starts with a letter
num_2✓letters, digits, and _
$price✓$ is allowed, but not recommended
2count✗starts with a digit
salary calc✗contains a space
first-last✗- is the subtraction operator
@name✗@ is not allowed
class✗a keyword
Class✓capital C: not a keyword

The $ sign is valid but is used in class names the compiler itself generates. That is why programmers are advised not to use it. Class compiles, because Java is case-sensitive and all keywords are lowercase. But Class is the name of an existing class in the Java API and would surprise the reader.

An invalid name does not always produce a clear message. A name that starts with a digit confuses the compiler; the message points at the statement, not at the name:

int 2count = 20;
Ident.java:3: error: not a statement
        int 2count = 20;
        ^
Ident.java:3: error: ';' expected
        int 2count = 20;
           ^
2 errors

After the word int the compiler expects a name. On seeing 2, it realizes there is no name here and treats int on its own as a meaningless statement (not a statement). It then tries to read the 2count part as the beginning of a new statement and expects a semicolon. Neither message says what the real problem is, namely that the name starts with a digit. When messages look confusing, the first place to look is whether the names on the line follow the rules.

2.2.3.3Keywords

Definition 2.2.12

A keyword (also reserved word) is a word that has a specific job in the language and is therefore reserved. Keywords cannot be used as variable, class, or method names. All of them are written in lowercase.

Java 21 has 51 keywords. Table 2.2.8 groups them by function.

Table 2.2.8: The 51 keywords of Java 21, by functional group.
GroupKeywordsCount
Typesboolean byte char short int long float double void9
Control flowif else switch case default for while do break continue return11
Classes and objectsclass interface enum extends implements new this super instanceof package import11
Modifierspublic protected private static final abstract native synchronized volatile transient strictfp11
Exceptionstry catch finally throw throws assert6
Reserved, unusedconst goto _3

Three words are often mistaken for keywords: true, false, and null. These are not keywords but literals. Even so, they cannot be used as names either. Another group is the contextual keywords. Words such as var (since Java 10), yield (since Java 14), and record (since Java 16) carry a special meaning only in certain places. Because they were added to the language later, they may have been used as variable names in old programs. To keep that code from breaking, they were not made full keywords. String, System, and main do not belong to any group; they are the names of classes and methods in the API. The line int String = 3; therefore compiles, but it should never be written, because it would surprise the reader.

When a keyword is used as a name, the compiler expects the construct that the word starts. new starts an object-creation expression; a class name and parentheses must follow it:

int new = 5;
Keyword.java:3: error: not a statement
        int new = 5;
        ^
... (4 errors in total)

A single faulty word produces four messages. After new, the compiler expects a class name (<identifier> expected) and then ( or [. None of the messages says “new is a keyword.” As with identifier errors, a sequence of messages that looks meaningless often indicates that there is a problem with the name itself.

2.2.3.4Groups of keywords

Most keywords come into their full meaning only when the related constructs are written. At the start it is enough to know briefly what each does. The type keywords are the names of the primitive types; void is added to them. void is not a type but a marker saying that a method returns no value: public static void main.

Table 2.2.9: Control-flow keywords.
WordPurpose
if / elseChecks the condition; if true the if block runs, otherwise the else block.
switchPerforms different operations for different values of a variable.
caseRepresents one case (value) inside a switch.
defaultThe operation to perform inside a switch when no case matches.
forRepeats an operation with a counter as long as the condition holds.
whileRepeats the operation as long as the condition holds.
doThe do-while loop: the body runs at least once, and the condition is checked at the end.
breakLeaves the loop or the switch block at once.
continueSkips the rest of this pass of the loop and moves to the next one.
returnEnds the method; returns a result if needed.
Table 2.2.10: Keywords for classes and objects.
WordPurpose
classDefines a class. Classes are templates for objects and the basic building blocks of Java programs.
interfaceDefines an interface: a contract that specifies the methods a class must provide.
enumA type made of fixed values: enum Color { RED, GREEN }.
extendsInheritance: a class taking over the fields and methods of another class.
implementsA class implementing an interface, that is, providing the interface’s methods.
newCreates an object: sets aside memory and gives initial values.
thisA reference to the object itself; tells a field apart from a local variable of the same name.
superAccesses the methods, fields, and constructor of the superclass.
instanceofChecks whether an object is of a given class or interface type.
package / importpackage sets the package (namespace) of the class; import makes classes in other packages available.
Table 2.2.11: Modifiers.
WordPurpose
publicAccessible from everywhere, from all classes.
protectedAccessible from the same package and from subclasses.
privateAccessible only from inside the same class.
staticThe member belongs to the class, not to an object; it is shared among all objects.
finalVariable: its value cannot change. Method: cannot be overridden in a subclass. Class: cannot be inherited.
abstractAn abstract class (cannot be instantiated) or a method without a body; a subclass must write the body of the method.
nativeA method whose body is written outside Java, in platform-specific code (C/C++); it is linked with JNI.
synchronizedIn a multithreaded program, lets only one thread at a time enter a block.
volatileMakes sure a variable is always read with its current value in every thread.
transientThis field is ignored when an object is serialized (saved).
strictfpMakes floating-point operations give the same result on every platform. Since Java 17 this is the default anyway; the word no longer has any effect.

The words in the exception group concern errors that occur while the program runs. try surrounds code that may fail. catch catches and handles the exception raised in that block. The finally block runs at the very end whether or not an exception occurred; closing a file that was opened is written in this block. throw throws an exception object and interrupts the normal flow. throws lists in a method header the exception types the method may throw. assert checks that a condition is true. This check is off by default and is turned on with java -ea.

The last group is interesting. const and goto are reserved words that have no function. They were reserved so that programmers coming from C and C++ would not use them by mistake. A lone underscore _ has not been allowed as a name since Java 9. When int _ = 3; is written in Java 21, the compiler reports that this use is a preview feature and is turned off. With Java 22, _ definitively acquired the meaning “unused variable.”

2.2.3.5Naming conventions

Besides the compiler’s mandatory rules, there are writing habits followed by the Java community. These are called naming conventions.

Table 2.2.12: Java naming conventions.
What?ConventionExamples
Classes and interfacesPascalCase, starts with an uppercase letterString, Student, HelloWorld
Variables, fields, methodscamelCase, starts with a lowercase letterfirstName, classAverage, calculate()
Primitive typeslowercase (they are keywords)int, float, boolean
Named constantsUPPER_CASE, words separated by _PI, DAYS_PER_WEEK, MAX_COUNT
Packagesall lowercasesyntax, tr.edu.giresun

In camelCase the first word is lowercase and the following words begin with an uppercase letter. The capital letters are likened to a camel’s humps, hence the name. In PascalCase, every word, including the first, begins with an uppercase letter. This distinction gives the reader information at once: Student is a class, student is a variable, and STUDENT_COUNT is a constant.

class StudentRecord { }    // class
String fullName;       // variable
boolean isMarried;           // yes/no
final int MAX_COUNT = 100; // constant

These are not compiler rules but conventions. If they are not followed, the code still compiles. class student_record or int TotalScore runs without error. But it becomes harder for another Java programmer to read such code. Conventions are the common language of teamwork. The Java API itself follows these rules: String is a class, length() is a method, and Integer.MAX_VALUE is a constant.

2.2.4Assignment, literals, and conversion

After variables are declared they receive values, and those values change. This section explains how a value is put into a variable, how values written directly in code are read, and how a value moves from one type to another. Type conversion is one of the topics that causes the most errors in beginning Java programs.

2.2.4.1Assignment statements

Definition 2.2.13

Assignment gives a value to a variable. It is written with the assignment operator =: variable = expression;. First the expression on the right is computed, and then the result is written into the variable on the left.

The expression on the right can be a constant value, another variable, or an operation:

int num, result;
int num1 = 4, num2 = 6;
String name;

num = 10;             // literal
result = num1 + num2; // sum: 10
name = "Ahmet";        // text
num = num * 2;       // 10 → 20

The first three lines are declarations. num1 and num2 receive values together with their declarations; num, result, and name are still empty. Then come four assignments, each with a different right-hand side. The first is a constant (10), and the second is the sum of two variables (4 + 6 = 10). The third is a piece of text ("Ahmet"), and the fourth is an operation that uses the variable’s own value. After the last line num is 20.

num = num * 2;10 * 2 = 20① evaluate the right side20② store on the left
Figure 2.2.17: num = num * 2: first the right-hand side 10 * 2 = 20 is computed, then the result is written into the num box.

The = sign is not the equality of mathematics. In mathematics x = x + 1 is a contradictory equation; no number can equal one more than itself. In Java, x = x + 1 means “let the new value of x be one more than its old value.” Reading “gets” instead of “equals” prevents this misunderstanding: “x gets x + 1.”

Only a variable can appear on the left side of an assignment. The line 5 = num; does not compile:

Left.java:4: error: unexpected type
        5 = num;
        ^
  required: variable
  found:    value
1 error

The message says that a variable was expected on the left (required: variable) but a value was found (found: value). Types must also be compatible in an assignment. A number cannot be assigned to a String variable, nor text to an int variable. The lines int x = 3; String s = x; give the message incompatible types: int cannot be converted to String.

An assignment is also an expression and produces a value: the value assigned. That is why a = b = 0; can be written. Assignment groups from right to left; first b = 0 is done, and the value of that expression, 0, is assigned to a. Both variables are zeroed.

2.2.4.2Compound assignment

Definition 2.2.14

Compound assignment operators combine an operation and an assignment: +=, -=, *=, /=, %=. The notation x op= y does the same job as x = x op y.

int x = 5;
int y = 10;
x = x + y;
x -= y;
x *= 2;
x /= 4;
x %= 3;
System.out.println("x = " + x + ", y = " + y);

The program prints x = 2, y = 10. Table 2.2.13 gives the values after each line.

Table 2.2.13: Trace of compound assignment.
LineWritten outComputationxy
int x = 5;——5
int y = 10;——510
x = x + y;—5 + 101510
x -= y;x = x - y15 − 10510
x *= 2;x = x * 25 × 21010
x /= 4;x = x / 410 / 4 (integer division)210
x %= 3;x = x % 3the remainder of 2 divided by 3210
x15inty10int x10inty10int x2inty10int
Figure 2.2.18: Three moments of compound assignment. (a) After x = x + y, x = 15. (b) After x *= 2, x = 10. (c) After x /= 4, x = 2; y stays 10 throughout.

Two steps need attention. In the line x /= 4, 10 / 4 is computed between two integers and the result is 2, not 2.5; the fractional part is discarded. In the line x %= 3, since 2 is smaller than 3, the quotient is 0 and the remainder is 2. y never changes because it is never on the left side of a line.

Compound assignment has two subtleties. First, the right-hand side is computed as a whole, and then the operation is performed. The expression k *= 2 + 3 means k = k * (2 + 3), not k = k * 2 + 3; if k is 7, the result is 35. Second, a compound assignment converts the result to the type of the variable on the left by itself. byte b = 10; b += 5; compiles and b becomes 15. But b = b + 5; does not compile, because b + 5 is an int. This convenience has a price: int m = 10; m /= 0.3; compiles without error and m becomes 33. 10 / 0.3 = 33.33… is computed, and then the fraction is silently discarded.

2.2.4.3Initial and default values

A variable can be declared without a value. An initial value can also be given together with the declaration: int age = 25;. This is called initialization. When the value is given depends on two different rules, according to where the variable is declared.

Local variables, that is, variables declared inside a method, receive no default value. A local variable that is read before a value has been assigned prevents the program from compiling:

int count;
System.out.println(count);
Init.java:4: error: variable count
  might not have been initialized

The compiler examines every possible path through the program and sees that the point where count is read can be reached without a value. This check prevents a random memory content from being used silently. In C the same mistake compiles, and the program may print a different, meaningless number each time it runs.

Class fields, by contrast, automatically receive a default value. Table 2.2.14 gives these values.

Table 2.2.14: Default values of class fields.
Field typeDefault
int, long, byte, short0
double, float0.0
char'\u0000' (code 0)
booleanfalse
String and other referencesnull

When the unassigned int, long, double, float, char (its code), boolean, and String fields of a class are printed in turn, the output is 0 0 0.0 0.0 0 false null. Still, it is a good habit not to rely on default values and to give the value explicitly. An explicitly written int count = 0; tells the reader that the zero is a deliberate choice.

2.2.4.4Literals

Definition 2.2.15

A literal is a value written directly in source code: 2, 3.7, 'y', "Ali", true, and so on.

Every literal has a type, and the type can be told from the way it is written:

  • Integer: may begin with + or - but cannot contain a comma: +42, -17. For readability, underscores can be placed between the digits (added in Java 7): 1_000_000. Hexadecimal numbers begin with 0x and binary numbers with 0b: 0x1F, 0b1010.
  • Floating-point: the decimal separator is the period. Scientific notation is written with e: 2.5e3 = 2.5 × 103, 7.68e-2 = 7.68 × 10−2.
  • Character: in single quotes: 'y'. Special characters are written with a backslash: '\n' newline, '\t' tab, '\'' single quote, '\\' backslash.
  • Text: in double quotes: "Hello". Logical: true, false.
System.out.println(2.5e3);
System.out.println(7.68e-2);
System.out.println(1_000_000);
System.out.println(0x1F);
System.out.println(0b1010);
System.out.println(3000000000L);
System.out.println("Ali\tVeli\n\"Java\"");
2500.0
0.0768
1000000
31
10
3000000000
Ali	Veli
"Java"

The output shows several things. 2.5e3 is a double and is printed as 2500.0; even though its value is whole, the trailing .0 reveals its type. The underscores are only for readability in source code and do not appear in the output. 0x1F is 1 × 16 + 15 = 31 in hexadecimal and 0b1010 is 8 + 2 = 10 in binary; println writes both in decimal. In the text on the last line, \t produces a tab and \n a line break; \" puts a double quote inside the text. A single println therefore writes two lines.

Common mistake

Carrying the decimal comma of Turkish into code. double rate = 0,45; does not compile; in Java the decimal separator is the period: 0.45. Similarly, a period cannot be used as a thousands separator: 1.000.000 is meaningless. A thousand is written 1000 or 1_000. Another trap is a leading zero: 010 is read in base eight and its value is 8, not 10.

2.2.4.5The precision of floating-point numbers

Floating-point numbers are stored with a limited number of bits in base two. In base ten, 1/3 = 0.333… goes on forever and cannot be written exactly with a finite number of digits. A similar situation exists in base two: 1/10 = 0.000110011…2 repeats forever. The innocent-looking 0.1 in base ten is therefore stored approximately in a computer. The exact value of 0.1 in a double is a number like 0.1000000000000000055511151231257827….

System.out.println(1.0 / 3.0);
System.out.println(1.0/3 + 1.0/3 + 1.0/3);
System.out.println(0.1 + 0.2);
System.out.println(0.1 + 0.2 == 0.3);
double t = 0.0;
for (int i = 0; i < 10; i++) t += 0.1;
System.out.println(t);
double diff = (0.1 + 0.2) - 0.3;
System.out.println(Math.abs(diff) < 1e-9);
0.3333333333333333
1.0
0.30000000000000004
false
0.9999999999999999
true

The results read line by line as follows:

  • 1.0 / 3.0 is an approximate value and is printed with 16 digits.
  • The sum of three 1.0/3 values comes out exactly 1.0. Here the rounding errors happened to cancel each other. This is luck, not a rule.
  • The result of 0.1 + 0.2 is 0.30000000000000004. The small errors of the two numbers add up, and the result differs from the stored value of the constant 0.3. That is why 0.1 + 0.2 == 0.3 gives false.
  • Adding 0.1 ten times does not give exactly 1: 0.9999999999999999. Small errors accumulate with each addition.
  • On the last line the absolute value of the difference of the two numbers is compared with a very small bound, 10−9. The difference is about 5.55 × 10−17; because it is smaller than the bound, the result is true.

This behavior is not specific to Java. All modern processors store floating-point numbers according to the IEEE 754 standard, and C, Python, and JavaScript give the same results. Two rules follow. First, floating-point numbers are not compared with ==; instead one checks whether the difference is very small: Math.abs(a - b) < 1e-9. Second, double is not used in money calculations that must be correct to the last cent. There is the BigDecimal class for this; the sum of new BigDecimal("0.1") and new BigDecimal("0.2") is exactly 0.3. Another way is to keep amounts in cents as long integers.

Common mistake

Building a loop with a floating-point counter. The loop for (double t = 0; t != 1.0; t += 0.1) never ends. t never reaches exactly 1.0; after 0.9999999999999999 it jumps to 1.0999999999999999, and t != 1.0 stays true forever. The loop counter must be an integer; if a floating-point value is needed, it is computed from the counter: double t = i * 0.1;.

2.2.4.6Named constants

Definition 2.2.16

A named constant is a variable declared with final whose value cannot be changed once it has been given. The class-level pattern is: public static final Type CONSTANT_NAME = value;.

Numbers embedded in code with no stated meaning are called magic numbers. That the 7 in the line days = 4 * 7; is the number of days in a week can be guessed only from context. When the same line is written days = 4 * DAYS_PER_WEEK;, the meaning shows by itself. If the value changes, it is also updated in a single place. Constant names are written in uppercase, with words separated by underscores.

public class Constants {
    public static final double PI = 3.14159;
    public static final int DAYS_PER_WEEK = 7;

    public static void main(String[] args) {
        double r = 2.0;
        double area = PI * r * r;
        System.out.println("Area: " + area);
        int days = 4 * DAYS_PER_WEEK;
        System.out.println(days + " days");
    }
}
Area: 12.56636
28 days

PI and DAYS_PER_WEEK are declared at class level, outside main. Being static lets them be used inside main without creating an object. The area comes out as 3.14159 × 2 × 2 = 12.56636. Java itself offers a more precise value: Math.PI. With the same radius, Math.PI * r * r gives 12.566370614359172.

Trying to change the constant, or assigning a double result to a float, does not compile:

PI = 3.14;
float area = PI * r * r;
error: cannot assign a value to
  static final variable PI
error: incompatible types: possible
  lossy conversion from double to float

The first message shows the final keyword doing its job. When someone tries to change a value that must not change, the error is caught at compile time. The second message is a type-conversion problem. PI * r * r is a double expression and float is a narrower type. The compiler rejects the assignment with a “possible lossy conversion” message.

2.2.4.7Assignment compatibility

A value cannot always be assigned to a variable of another type. Java’s rule is simple: if the value fits without loss, the assignment is done automatically; if loss is possible, the programmer must ask for it explicitly.

byteshortintlongfloatdoublecharimplicit (automatic) widening →other direction: explicit cast required
Figure 2.2.19: Assignment compatibility. In the chain byte, short, int, long, float, double, assignment to the right is automatic; a char can be assigned to an int. The reverse direction needs a cast.
Definition 2.2.17

A widening conversion moves a value to a type with a wider range and is done automatically. A narrowing conversion moves to a type with a narrower range; because a value may be lost, it requires an explicit cast.

Figure 2.2.19 shows the chain: byte → short → int → long → float → double. A value can be assigned directly to a variable of a type further to the right in the chain. An int value goes to long, and a long value to double, without trouble. char enters the chain at int: a char value can be assigned to an int and to the types to its right; the reverse does not compile.

char ch = 'A';
int n;
n = ch;   // OK: 65
ch = n;   // error
Compat.java:5: error: incompatible types:
  possible lossy conversion from int to char
        ch = n;
             ^

In the line n = ch; the code of 'A', 65, is written into the int variable. The assignment in the other direction is rejected. Even if it is known that n is 65 at that moment, the compiler looks at the type, not the value. An int variable may also hold a value that does not fit in a char, such as −5 or 100,000.

The chain has a subtlety. long is 64 bits and float is 32 bits; yet long → float is automatically allowed. The reason is that the range of float is much wider than that of long. But float is precise to only about 7 digits. In a very large number, the last digits are rounded. When the value long big = 123456789123L; is assigned to a float and read back, 123456790528 is obtained. The same applies to int → float: when 16,777,217 is assigned to a float, it becomes 16,777,216. Widening is safe in terms of range, but not always in terms of precision.

2.2.4.8Implicit and explicit conversion

Definition 2.2.18

Type conversion is turning a value into another type. A conversion Java does by itself is called an implicit conversion; one the programmer asks for by writing the target type in parentheses is called an explicit conversion (a cast): (int) d.

Java converts from a smaller type to a larger type by itself. For a conversion from a larger type to a smaller one, the target type is written in parentheses. With this mark the programmer tells the compiler that the possible loss is accepted. The loss appears in two ways:

  • When going from a floating-point number to an integer, the fractional part is discarded; the number is not rounded. (int) 3.99 gives 3 and (int) -3.99 gives −3. The fraction is truncated toward zero.
  • An integer that does not fit overflows. (byte) 130 takes the last 8 bits of the value and gives −126.
double dbl = 5;     // implicit: 5.0
System.out.println(dbl);
double d = 5.0;
int num = (int) d;   // explicit: 5
System.out.println(num);
System.out.println((int) 3.99);
System.out.println((int) -3.99);
System.out.println(Math.round(3.99));
System.out.println((byte) 130);
5.0
5
3
-3
4
-126

In the line double dbl = 5; the int constant 5 is implicitly converted to 5.0; that is why println writes 5.0. (int) d is an explicit conversion and turns 5.0 into 5. There is no loss in this value, but because the compiler looks at the type, not the value, the cast is still required. (int) 3.99 and (int) -3.99 show that the fraction is discarded. If rounding is wanted, Math.round is used: Math.round(3.99) gives 4. (byte) 130 shows that overflow also occurs with an explicit cast. The cast does not prevent the error; it only silences the compiler’s objection.

Common mistake

Forgetting the return type of Math.round. Math.round(double) returns a long, not an int. int n = Math.round(3.99); therefore does not compile, with the message possible lossy conversion from long to int; write int n = (int) Math.round(3.99);. Another detail is the rounding of negative halves: Math.round(2.5) gives 3, but Math.round(-2.5) gives −2. The method adds 0.5 to the number and rounds down.

2.2.4.9Integer division and where the cast goes

Definition 2.2.19

Integer division means that the quotient of two integers is also computed as an integer: the fractional part is discarded. Numeric promotion is the conversion of the operands of an operation to a common type: if one operand is double, the other is promoted to double as well.

Java decides the type of an operation by looking at the types of its operands. The type of the variable the result will be assigned to does not affect this decision. Table 2.2.15 compares six expressions written with the same numbers 7 and 2.

Table 2.2.15: Integer division and where the cast goes.
ExpressionResultWhy?
7 / 23two int values → integer division, the fraction is discarded
7 / 2.03.52.0 is double → the operation is done in double
(double) 7 / 23.5first 7 → 7.0, then the division
(double) (7 / 2)3.0first integer division (3), then 3 → 3.0: a cast that comes too late
(int) 3.993the fractional part is discarded
Math.round(3.99)4rounds to the nearest integer (returns long)

The difference between the third and fourth rows comes from the precedence of the cast. (double) is a unary operator and is applied before the division. In the expression (double) 7 / 2, the cast applies only to 7; the division is done as 7.0 / 2. In (double) (7 / 2), on the other hand, the parentheses are computed first. Integer division gives 3, and the cast comes after the fraction is long gone.

The promotion rule has one more consequence. byte and short values are first promoted to int when they enter an operation. The result of byte + byte is therefore an int:

Sum.java:4: error: incompatible types: possible lossy conversion from int to byte
        byte c = a + b;
                   ^
1 error

a and b are small numbers, and even their sum of 30 would fit in a byte. Still, the compiler knows that the sum of two byte values can be as large as 254 and might not fit. The fix is to write byte c = (byte) (a + b); or to keep the result in an int variable.

To follow where the cast goes step by step, consider this code:

int a = 9, b = 4;
double d1 = a / b;
double d2 = (double) a / b;
double d3 = (double) (a / b);
int k = (int) 9.75;
long r = Math.round(9.75);
byte y = (byte) 200;
System.out.println(d1 + " " + d2 + " " + d3);
System.out.println(k + " " + r + " " + y);

The program prints two lines: 2.0 2.25 2.0 and 9 10 -56. Table 2.2.16 shows how each variable is computed.

Table 2.2.16: Trace of type conversion (a = 9, b = 4).
VariableExpressionIntermediate stepsValue
d1a / b9 / 4 = 2 (integer division) → 2.0 on assignment2.0
d2(double) a / b9 → 9.0; b is promoted to 4.0; 9.0 / 4.02.25
d3(double) (a / b)9 / 4 = 2 → 2.02.0
k(int) 9.75the fraction is discarded9
rMath.round(9.75)the nearest integer (long)10
y(byte) 200200 = 11001000; sign bit 1 → 200 − 256−56
a / b9 / 4int ÷ intinteger division2intd12.0double (double) a9.0doubleb is promoted4.0doubled22.25double 20011001000int (last 8 bits)(byte)-56byte
Figure 2.2.20: Where the cast goes. (a) d1: first the integer division gives 2, then 2 → 2.0. (b) d2: first 9 → 9.0, the division is done in double, and 2.25 results. (c) y: the last 8 bits of 200 are 11001000, which read as signed is −56.

The d1 line shows the most common mistake. That the target is double does not rescue the division. Java computes the right-hand side first, and at that point it does not look at where the result will be assigned. Two int values are divided, 2 is obtained, and only on assignment is it turned into 2.0. In the y line, 200 in binary is 11001000. When these 8 bits are read as a byte, the leftmost 1 carries the weight −128: −128 + 64 + 8 = −56.

Example 2.2.2

The formula that converts Celsius to Fahrenheit is F = C × 9 / 5 + 32. With int c = 37;, what are the results of three different ways of writing it?

  • c * 9.0 / 5 + 32: because 9.0 is a double, the computation runs in double from the start. 37 × 9.0 = 333.0; 333.0 / 5 = 66.6; 66.6 + 32 = 98.6.
  • c * 9 / 5 + 32: everything is int. 37 × 9 = 333; 333 / 5 = 66 (fraction discarded); 66 + 32 = 98. The result is 0.6 too small.
  • 9 / 5 * c + 32: operations go from left to right. 9 / 5 = 1 (integer division); 1 × 37 = 37; 37 + 32 = 69. The result is almost 30 degrees off.

In mathematics these three forms are the same. In Java the order of the operations and the types of the operands change the result. How early the integer division happens determines the size of the loss.

2.2.4.10Converting between char and int

Every char is really a number: the character’s Unicode code. 'A' = 65, 'B' = 66, 'a' = 97. That is why arithmetic can be done on characters. The rules are the same as for the other numeric types:

  • char → int is implicit. (char) is needed for int → char.
  • If two char values are added with +, both are promoted to int and a number results. To get text, the expression must start with a String.
  • In the English alphabet the codes of uppercase and lowercase letters differ by 32: 'a' - 'A' = 97 − 65 = 32.
  • The codes of the digits start at 48 and are consecutive. That is why '7' - '0' gives the numeric value of the digit, that is, 7.

All the character codes can be seen in the ASCII table.

char ch = 'A';
int code = ch;               // 65
System.out.println(code);
char next = (char) (code + 1);
System.out.println(next);
System.out.println('B' + 'C');
System.out.println("" + 'B' + 'C');
System.out.println((char) (ch + 32));
System.out.println((int) 'ş');
65
B
133
BC
a
351

'B' + 'C' gives 66 + 67 = 133; there is no text here. The expression "" + 'B' + 'C', on the other hand, starts with an empty string. From left to right, first "" + 'B' is computed and the text "B" results. Then 'C' is appended to this text: BC. (char) (ch + 32) turns capital A into lowercase a. The last line gives the code of the Turkish letter 'ş': 351. Turkish letters are not among the English letters but in a later part of the Unicode table. The rule of a difference of 32 therefore does not hold for them: 'Ş' has code 350, 'ı' 305, and 'İ' 304.

Let us combine these rules in one trace:

char c = 'd';
int code = c;
char upper = (char) (c - 32);
int diff = 'z' - c;
char next = c;
next++;
System.out.println(code + " " + upper + " " + diff + " " + next);
System.out.println(c + 1);
System.out.println("" + c + 1);
Table 2.2.17: Trace of char ↔ int.
LineComputationResult
char c = 'd';the code of 'd' is storedc = 'd' (100)
int code = c;implicit char → intcode = 100
char upper = (char) (c - 32);100 − 32 = 68 (int), with (char) 68 = 'D'upper = 'D'
int diff = 'z' - c;122 − 100diff = 22
char next = c; next++;100 → 101; ++ needs no castnext = 'e'
println(code + " " + … )concatenation because of the text " "100 D 22 e
println(c + 1)char is promoted to a number: 100 + 1101
println("" + c + 1)first "d", then + 1 is appended to the textd1
c'd'char · 100code100intupper'D'char · 68 c'd'char · 100code100intupper'D'char · 68diff22intnext'e'char · 101"" + c + 1 → "d" + 1 → "d1"
Figure 2.2.21: Two moments from the char ↔ int trace. (a) c = 'd', code = 100, and upper = 'D' have been computed. (b) All variables are ready; the last two lines print 101 and d1.

The last two rows of the table produce very different results from the same values. There is no text in c + 1. The char is promoted to a number and 101 is printed; no letter is written. If a letter is wanted, write (char) (c + 1) and e results. In "" + c + 1, on the other hand, the empty string on the left turns the whole expression into a text operation. c is appended to the text as d and 1 as 1. The line next++ is also worth noticing. next = next + 1; would not compile, because the right-hand side is an int. ++, like compound assignment, does the conversion itself.

2.2.5Operators

Operators are symbols that perform operations on values. +, <, and && are operators; the values they work on are called operands. Java’s operators fall into four groups: arithmetic, comparison, logical, and assignment operators. When an expression contains more than one operator, the precedence rules determine which is applied first.

2.2.5.1Arithmetic operators

Table 2.2.18: Arithmetic operators (x = 17, y = 5).
OperatorMeaningExpressionResult
+additionx + y22
-subtractionx - y12
*multiplicationx * y85
/divisionx / y3
%remainder (mod)x % y2
-17 / 5−3
-17 % 5−2
17.0 / 53.4
17 / 5 = 3 (full groups)17 % 5 = 23 groups of five, 2 left over
Figure 2.2.22: When 17 objects are split into groups of 5, there are 3 groups and 2 objects are left over: 17 / 5 = 3, 17 % 5 = 2.

/ performs integer division between two integers. % gives the remainder of the division. Figure 2.2.22 shows the two together: 17 = 5 × 3 + 2. The quotient and the remainder always satisfy this identity: the expression (x / y) * y + x % y equals x. With negative numbers, Java truncates the quotient toward zero: −17 / 5 is −3, not −3.4. To keep the identity, the remainder is −2: 5 × (−3) + (−2) = −17. The rule is that the sign of the remainder is the sign of the dividend. 17 % -5 therefore gives 2.

The % operator has a few common uses:

  • Odd-even test: if n % 2 == 0, n is even. For an odd test, write n % 2 != 0. n % 2 == 1 gives a wrong result for negative odd numbers, because -7 % 2 is −1.
  • Last digit: n % 10 gives the last digit and n / 10 gives the number with its last digit dropped. For n = 1234, 4 and 123 result.
  • Splitting units: jobs such as splitting seconds into hours, minutes, and seconds are done with / and %.
Example 2.2.3

How many hours, minutes, and seconds are 3725 seconds? With int s = 3725;:

  • s / 3600 = 1. One hour is 3600 seconds, and it fits once in 3725.
  • s % 3600 / 60 = 125 / 60 = 2. First the 125 seconds left over after the hour are found, then the whole minutes in them are counted. % and / have equal precedence and are applied from left to right.
  • s % 60 = 5. These are the seconds left over after the whole minutes.

The result: 1 hour, 2 minutes, 5 seconds. Check: 1 × 3600 + 2 × 60 + 5 = 3725.

Java has no exponentiation operator. 2 ** 3 does not compile, and 2 ^ 3 compiles but does not raise to a power: ^ is the bitwise exclusive or, and it gives 1. For powers, Math.pow(2, 3) is used; the result is 8.0 of type double. The + operator has a second meaning too. If one of its operands is a String, it performs concatenation: the expression "Age: " + 20 gives the text Age: 20.

In integer division, if the divisor is 0 the program stops with ArithmeticException: / by zero. In floating-point division no exception occurs: 5.0 / 0 gives Infinity and 0.0 / 0 gives NaN (not a number). This difference too comes from the types of the operands.

2.2.5.2Increment and decrement

Definition 2.2.20

The increment (++) and decrement (--) operators increase or decrease a variable by 1. If the operator is written after the variable, it is the postfix form (x++); if before, the prefix form (++x).

Both x++ and ++x increase x by 1. The difference is in the value of the expression. The postfix form gives the old value and the prefix form gives the new value. When i++; is written alone as a statement, the value of the expression is not used and there is no difference between the two forms. The difference shows only when the expression is part of another operation.

int a = 5;
int b = a++;
System.out.println(a + " " + b);
int c = ++a;
System.out.println(a + " " + c);
int d = a--;
System.out.println(a + " " + d);
Table 2.2.19: Trace of increment and decrement.
LineWhat happens?aNew variableOutput
int a = 5;—5
int b = a++;first the old value (5) is used, then a increases6b = 5
println(a + " " + b)66 5
int c = ++a;first a increases, then the new value (7) is used7c = 7
println(a + " " + c)77 7
int d = a--;first the old value (7), then a decreases6d = 7
println(a + " " + d)66 7
a6intb5int a7intb5intc7int a6intb5intc7intd7int
Figure 2.2.23: (a) After b = a++: a = 6, b = 5. (b) After c = ++a: a = 7, c = 7. (c) After d = a--: a = 6, d = 7.
Common mistake

Writing i = i++;. This line does not increase i. The right-hand side is computed first: i++ gives the old value, say 5, and makes i 6. Then the assignment follows and writes that old value, 5, into i. The increment is thereby erased. To increase a variable, i++; or i += 1; is enough. A general rule follows from this: both changing and reading the same variable in one expression makes the code unreadable.

2.2.5.3Operator precedence

Definition 2.2.21

Operator precedence is the order that determines which operator is applied first when an expression contains more than one. Among operators of equal precedence, associativity decides: left to right or right to left.

Table 2.2.20: Order of precedence of the operators. → groups left to right, ← groups right to left.
PrecedenceOperatorsDirection
1 (highest)postfix: x++ x--→
2unary: +x -x ! ++x --x · cast (int)←
3multiplication, division, mod: * / %→
4addition, subtraction: + -→
5comparison: < > <= >=→
6equality: == !=→
7logical AND: &&→
8logical OR: ||→
9conditional: ? :←
10 (lowest)assignment: = += -= *= …←

The table extends the order of operations from mathematics. Multiplication and division come before addition; comparisons come after arithmetic, logical connectives after comparisons, and assignment last. This order agrees with everyday notation: the expression x + 1 < y * 2 && z == 0 is read, even without parentheses, as expected: ((x + 1) < (y * 2)) && (z == 0).

For binary operators of equal precedence the one on the left is applied first: 10 - 4 - 3 = (10 − 4) − 3 = 3, not 10 − (4 − 3) = 9. For unary operators and assignment, the one on the right is applied first: a = b = 0 zeroes b first and then a. Parentheses are used to change the order or to improve readability. A parenthesis that looks unnecessary is often useful too; it saves the reader from having to remember the precedence table.

Let us see step by step how precedence is applied to one expression: System.out.println(2 + 3 * 4 - 6 / 2);

  1. 2 + 3 * 4 - 6 / 2: * and / come before + and -. Of the two, the left one first: 3 * 4 = 12.
  2. 2 + 12 - 6 / 2: the remaining high-precedence operation is 6 / 2 = 3.
  3. 2 + 12 - 3: the remaining + and - have equal precedence and go from left to right: 2 + 12 = 14.
  4. 14 - 3 = 11.

The result is 11. Parentheses change the order: (2 + 3) * 4 - 6 / 2 = 5 × 4 − 3 = 20 − 3 = 17. A few more short examples: 20 / 4 * 2 is computed from the left and gives 5 × 2 = 10, not 20 / 8. In the expression -2 * -3 the unary minuses are applied first and the result is 6.

String concatenation obeys the same left-to-right rule and can therefore give surprising results. In the expression 1 + 2 + "3" + 4 + 5, first 1 + 2 = 3 is computed; there is no text yet. Then 3 + "3" becomes text: "33". Every + after that is concatenation: "334", "3345". The result is 3345.

2.2.5.4Comparison operators

Definition 2.2.22

Comparison operators (also relational operators) evaluate the relationship between two values. The result is always a boolean: true or false.

Table 2.2.21: Comparison operators (x = 10, y = 20).
OperatorMeaningExampleResult
==equal?x == yfalse
!=not equal?x != ytrue
>left greater?y > xtrue
<left less?x < ytrue
>=greater or equal?x >= 30false
<=less or equal?x <= ytrue

The result of a comparison can be stored in a variable: boolean bigger = y > x;. After this line bigger is true. The spelling of the two-character operators is fixed: >= is correct, and => cannot be written. A space cannot be put inside an operator either: > = does not compile.

The mathematical notation 0 < x < 10 does not work in Java. In the expression 0 < x < 10, first 0 < x is computed and a boolean results. Then this boolean is compared with 10, and the compiler reports an error. The correct way joins the two comparisons with logical AND: 0 < x && x < 10.

Common mistake

Confusing = with ==. = is assignment and == is comparison. When if (x = 5) is written, an assignment takes the place of the condition. The value of the assignment is 5, that is, an int. Because Java accepts only boolean as a condition, the code does not compile:

Eq.java:4: error: incompatible types: int cannot be converted to boolean
        if (x = 5) { }
              ^
1 error

In C the same line compiles and the condition is always taken to be true; the error stays hidden. Java’s strict type checking catches this mistake at compile time. There is one exception: boolean done; … if (done = true) compiles, because the value of the assignment is a boolean. With boolean variables the safest way to write is not to use a comparison at all: if (done) and if (!done).

2.2.5.5Logical operators

Definition 2.2.23

Logical operators combine boolean values. AND &&: true if both conditions are true. OR ||: true if at least one is true. NOT !: reverses the value.

Table 2.2.22: Truth table of the logical operators.
ABA && BA || B!A
truetruetruetruefalse
truefalsefalsetruefalse
falsetruefalsetruetrue
falsefalsefalsefalsetrue

The table reads briefly as follows: A && B is true only when both are true; A || B is false only when both are false. The “or” of everyday language sometimes means “only one of the two” (“tea or coffee”). The || in Java, however, also gives true when both are true.

int x = 10, y = 20, z = 30;
System.out.println(x < y && y < z);
System.out.println(x > y || y < z);
System.out.println(!(x < y));
int age = 20;
boolean hasLicense = true;
System.out.println(age >= 18 && hasLicense);
true
true
false
true

In the expression x < y && y < z both comparisons are true (10 < 20 and 20 < 30), so the result is true. In x > y || y < z the first comparison is false and the second is true; for OR one is enough. !(x < y) reverses the true x < y and gives false. The last line turns a rule into code: a person who is 18 or older and holds a license may drive. Since both conditions are met, the result is true.

The ! operator has high precedence. If !x < y is written, ! is applied to x alone, and since an int value cannot be negated logically, the code does not compile. The negation of a comparison is therefore written with parentheses: !(x < y). The same expression can be written more simply as x >= y.

2.2.5.6Short-circuit evaluation

Definition 2.2.24

Short-circuit evaluation means that in the && and || operators the right-hand side is not evaluated at all once the result is already known from the left-hand side.

In &&, if the left side is false, the result is already false; whatever the right side is, it cannot change that. In this case Java does not evaluate the right side at all. In ||, if the left side is true, the result is already true and the right side is skipped again. In the expression day == 6 || day == 7, if day is 6 the second comparison is never made. This expression means “weekend.” Its negation !(day == 6 || day == 7) means “weekday.”

Short-circuiting does not only save time; it is also used to guard a dangerous operation. First the program checks “is the divisor nonzero?”, and only if so does it divide:

int divisor = 0;
int num = 10;
if (divisor != 0 && num / divisor > 1) {
    System.out.println("Ratio above 1");
} else {
    System.out.println("Can't divide or too small");
}
Can't divide or too small

divisor is 0. divisor != 0 comes out false and && never moves on to the right side. The division num / divisor is therefore not performed, and the program goes to the else block. Order matters. If the condition had been written num / divisor > 1 && divisor != 0, the division would have been done first. The program would have stopped with a division-by-zero error, the message java.lang.ArithmeticException: / by zero. The guarding condition is always written on the left.

Java has two more operators that do not short-circuit: the single & and the single |. When used with boolean values they always evaluate both sides. The expression a != 0 & 10 / a > 1 performs the division even when the left side is false for a = 0, and throws the exception. In conditions the two-character && and || are almost always used.

2.2.5.7The conditional operator

Definition 2.2.25

The conditional operator (also called the ternary operator) is a short expression that chooses one of two values according to a condition: if the condition is true the result is value1, otherwise value2. It is the only Java operator with three operands.

result = (condition) ? value1 : value2;

To decide whether a number is positive or negative:

int num = -5;
String result = (num > 0) ? "Positive" : "Negative";
System.out.println("Result: " + result);
Result: Negative

Because num is −5, num > 0 is false and the value after the colon, "Negative", is chosen. The if-else that does the same job is:

String result;
if (num > 0) {
    result = "Positive";
} else {
    result = "Negative";
}

The basic difference between the two forms is this: if-else is a statement and does a job, while ?: is an expression and produces a value. That is why ?: is used on the right of an assignment or inside a println. It cannot be written alone as a statement:

Tern.java:4: error: not a statement
        x > 0 ? System.out.println("a") : System.out.println("b");
              ^
1 error

The types of the two alternatives must be compatible. A few examples: double abs = (num < 0) ? -num : num; gives the absolute value, and for −4.5 the result is 4.5. int bigger = (a > b) ? a : b; chooses the larger of two numbers; for 8 and 13 the result is 13. If the alternatives are of different numeric types, the result is promoted to the wider one: the value of true ? 1 : 2.0 is 1.0, not 1.

Conditional operators can be nested. Whether a number is zero, positive, or negative can be found in one line:

int num = -5;
String result = (num == 0) ? "Zero" : (num > 0) ? "Positive" : "Negative";
System.out.println("Result: " + result);
Table 2.2.23: Results of a nested conditional operator.
numnum == 0num > 0Result
0truenot evaluatedZero
7falsetruePositive
−5falsefalseNegative

The expression reads: “zero? yes → Zero; no → positive? yes → Positive; no → Negative.” The second ?: is the value2 of the first; the conditional operator groups from the right. More than two nested ?: hurt readability. In that case an if-else if chain is preferred.

2.2.6The syntax of control statements

Control statements govern the flow of a program. They provide branching on a condition and the repetition of a task. Their detailed use is a topic in itself. Here the writing rule of each and the most common syntax traps are given.

Table 2.2.24: The syntax of control statements.
StatementSyntaxRule
if / elseif (condition) { … } else { … }the condition must be boolean; a ; after if (…) is an empty statement
switchswitch (d) { case 1: … break; default: … }int, char, String, enum; without break execution falls through to the cases below
switch (Java 14 and later)x = switch (d) { case 1 -> "P"; default -> "?"; };no fall-through; an expression that produces a value
forfor (int i = 0; i < n; i++) { … }initialization once; the condition before each pass, the update after
whilewhile (condition) { … }the body may never run
do-whiledo { … } while (condition);the body runs at least once; the final ; is required
break / continuebreak; · continue;break exits, continue skips the rest of the pass

In the if statement the condition is always written in parentheses and must be boolean. If the body is a single statement, the braces may be left out, but this habit invites mistakes. Only the first statement is attached to an if without braces; a second line written below it with indentation runs regardless of the condition. The compiler does not look at indentation. It is therefore safe to use braces even when the body is one line.

In the switch statement the value being tested can be int (and byte, short), char, String, or enum. long, double, and boolean cannot be used; the compiler gives a message such as selector type double is not allowed. In the classic form, break is written at the end of each case. If break is forgotten, the cases after the matching one run in turn as well. This behavior is called fall-through. Fall-through is sometimes used deliberately: writing case "Sat": case "Sun": ties two cases to one piece of code. In the arrow (->) form introduced in Java 14 there is no fall-through, and switch can produce a value. The two forms cannot be mixed in the same switch (different case kinds used in the switch).

The header of the for loop consists of three parts separated by semicolons. The initialization part runs only once, on entering the loop. The condition is checked before every pass; if it is false the loop ends. The update runs at the end of every pass. Every for loop can also be written as a while loop: the initialization moves before the loop and the update to the end of the body.

The difference between while and do-while is where the condition is. while checks the condition first; if the condition is false from the start, the body never runs. do-while runs the body first and checks the condition afterwards; the body runs at least once. The semicolon at the end of do-while is required, and if it is forgotten a ';' expected error results.

break leaves the nearest enclosing loop or switch at once. continue skips only the rest of that pass and moves to the next one. In a for loop the update part still runs after continue. If a switch is inside a loop, a break inside the switch leaves only the switch; the loop continues.

Example 2.2.4

The sum of the numbers from 1 to 100 that are not multiples of 3 can be found with continue as follows:

int sum = 0;
for (int i = 1; i <= 100; i++) {
    if (i % 3 == 0) continue;   // skip multiples of 3
    sum += i;
}

For an i that is a multiple of 3, continue runs, sum += i is skipped, and the loop goes on with i++. Check: the sum of the numbers from 1 to 100 is 5050. The multiples of 3 are 3, 6, …, 99; there are 33 of them and their sum is 3 × (1 + 2 + … + 33) = 3 × 561 = 1683. The result is 5050 − 1683 = 3367.

Common mistake

An infinite loop. A loop with no step that makes the condition false never ends. In the loop for (int i = 1; i <= 10; i--), as i decreases the condition stays true. In int i = 1; while (i <= 3) { System.out.println(i); }, i is never updated in the body and 1 is printed on the screen endlessly. Whenever a loop is written, the question to ask is: “at which step will the condition become false?”

2.2.7Common mistakes

Syntax errors fall into two groups. Those in the first group are caught by the compiler; the program never runs and the message points to the place of the error. Those in the second group compile but run wrongly. These are more dangerous, because they are noticed only when the output is examined carefully.

Table 2.2.25: Errors the compiler catches and their messages.
MistakeExampleMessageCorrect form
Missing semicolonSystem.out.println("a")';' expected; at the end of the line; the error is often at the end of the previous line
File name ≠ class namepublic class HelloWorld inside helloworld.javaclass HelloWorld is public, should be declared in a file named HelloWorld.javasave the file under the class name
Uppercase versus lowercasestring, Int, system.outcannot find symbol; package system does not existString, int, System
Local variable without a valueint count; println(count);variable count might not have been initializedgive a value before reading
Literal without a suffixfloat f = 3.14; · long l = 3000000000;possible lossy conversion from double to float · integer number too large3.14f · 3000000000L
Forgetting the cast when narrowingchar k = i; · int n = d;incompatible types: possible lossy conversion(char) i · (int) d
= versus ==if (x = 5)int cannot be converted to booleanif (x == 5)
Table 2.2.26: Code that compiles but runs wrongly.
MistakeExampleResultCorrect form
Integer divisiondouble avg = (3 + 4) / 2;3.0(3 + 4) / 2.0 → 3.5
A cast that comes too late(double) (a / b)the fraction is already lost(double) a / b
Overflowlong l = Integer.MAX_VALUE + 1;−2147483648Integer.MAX_VALUE + 1L
No break in a switchcase 1: … case 2: …the following cases run toobreak at the end of every case, or the -> form
; after ifif (x > 0); { … }the empty statement is attached to the condition, and the block always runsdelete the ;
Infinite loopfor (int i = 1; i <= 10; i--)the loop never endsan update that makes the condition false
== on floating-point values0.1 + 0.2 == 0.3falseMath.abs(a - b) < 1e-9
Order of concatenation"Total: " + a + bthe numbers are written side by side"Total: " + (a + b)

The if (x > 0); { … } mistake is especially insidious. The semicolon right after the if is an empty statement that does nothing. That is what gets attached to the condition. The braced block below it is an ordinary block independent of the condition and always runs. The block runs even when x = −3. The compiler does not count this as an error, because each of the two lines is valid by itself.

2.2.8Summary

  • Compiling: javac Name.java checks the source code and writes it as bytecode to Name.class. java Name starts the JVM, loads the class, and calls main. The same bytecode runs on every platform that has a JVM.
  • The JVM is a stack machine: instructions push values onto the operand stack and take them from it. The interpreter runs the bytecode, and the JIT compiler turns frequently executed code into machine code.
  • Syntax: statements end with ;, blocks are opened and closed with { }, and Java is case-sensitive. Comments are written with // and /* */.
  • Primitive types: byte 1, short 2, int 4, long 8 bytes; float 4, double 8 bytes; char 2 bytes; boolean. An integer that exceeds the limit overflows without error and wraps to the other end of the range.
  • Floating-point numbers are stored approximately in binary: 0.1 + 0.2 is not 0.3. Floating-point numbers are not compared with ==.
  • Names contain letters, digits, _, and $; they do not start with a digit; they cannot be keywords. Classes are written in PascalCase, variables in camelCase, and constants in UPPER_CASE.
  • Assignment: the right-hand side is computed first. Compound assignments such as += do the conversion themselves. A local variable must be given a value before it is read. A final variable receives a value once.
  • Conversion: the direction byte → short → int → long → float → double is automatic. The reverse is done with (type); the fraction is discarded and a value that does not fit overflows. int / int is integer division, and the cast must be done before the division.
  • Operators: the order of precedence is unary > * / % > + - > comparison > && > || > ?: > assignment. && and || short-circuit. ?: is an expression that produces a value.
  • Flow: if/else, switch (+ break), for, while (0 or more passes), do-while (at least 1 pass). break exits, continue skips the rest of the pass.

2.2.9Key terms

  • source code
  • comment
  • block
  • Java Development Kit (JDK)
  • bytecode
  • Java Virtual Machine (JVM)
  • JIT compiler
  • platform independence
  • variable
  • declaration
  • initialization
  • data type
  • primitive type
  • reference type
  • integer
  • character
  • boolean
  • overflow
  • identifier
  • keyword
  • naming convention
  • assignment
  • compound assignment
  • default value
  • literal
  • named constant
  • type conversion
  • cast
  • widening / narrowing conversion
  • integer division
  • expression
  • operator
  • increment / decrement
  • operator precedence
  • comparison operator
  • logical operator
  • short-circuit evaluation
  • conditional (ternary) operator

2.2.10Test Yourself

  1. A file named Demo.java defines public class Test. The file is to be compiled with javac Demo.java. What happens? How can the program be made to run?

    Answer

    The compilation fails: class Test is public, should be declared in a file named Test.java. The name of a public class must be exactly the same as the file name. Save the file as Test.java, compile it with javac Test.java, and run it with java Test (without the extension).

  2. When the lines int a = 5, b = 7; int c = a * b; are compiled, which values are on the JVM’s operand stack while a * b is computed? What is left on the stack right after the imul instruction?

    Answer

    First iload_1 pushes 5 and then iload_2 pushes 7; the stack holds 5, 7 from bottom to top. imul pops these two values, multiplies them, and pushes the result: only 35 remains on the stack. Then istore_3 writes 35 into c and the stack is empty. The same pattern holds as for iadd in the addition.

  3. Why does the following line give a wrong result? How is the correct value obtained?
    long microseconds = 24 * 60 * 60 * 1000 * 1000;

    Answer

    All the constants are int and the multiplication is done in int. The true result is 86,400,000,000, which exceeds the int limit; the overflowed value is 500654080. Only this overflowed value is assigned to the long variable. When L is added to the first constant, the multiplication runs in long from the start: 24L * 60 * 60 * 1000 * 1000 = 86400000000.

  4. What is b after the lines byte b = 120; b += 10;? What would happen if the same thing were written b = b + 10;?

    Answer

    b becomes −126. 130 exceeds the byte limit of 127; the compound assignment converts the result to byte itself, and 130 − 256 = −126 remains. b = b + 10;, on the other hand, does not compile: b + 10 is an int expression and can be assigned to a byte only with (byte) (possible lossy conversion from int to byte).

  5. Which of these names are valid identifiers? _2x, x-2, int, Integer, total$, 9th

    Answer

    Valid: _2x (starts with an underscore), Integer (the name of a class, not a keyword; but using it as a name would surprise the reader), total$ ($ is allowed). Invalid: x-2 (- is the subtraction operator), int (a keyword), 9th (starts with a digit).

  6. With char c = '5';, what do System.out.println(c + 1); and System.out.println(c - '0' + 1); print?

    Answer

    The first line prints 54: the code of '5' is 53, and c + 1 is an int sum. The second line prints 6: c - '0' = 53 − 48 = 5, that is, the numeric value of the digit; 1 is added to it.

  7. After the lines int x = 7; int y = x-- - --x;, what are x and y?

    Answer

    The operands are evaluated from left to right. x-- gives the old value, 7, and x becomes 6. --x first makes x 5 and gives 5. y = 7 − 5 = 2, and x = 5.

  8. With int a = 0;, what is the difference between the conditions if (a != 0 & 10 / a > 1) and if (a != 0 && 10 / a > 1)?

    Answer

    The single & does not short-circuit and evaluates both sides. Even though the left side is false, the division 10 / a is performed and the program stops with ArithmeticException: / by zero. &&, by contrast, never looks at the right side once the left side is false; the condition counts as false and the program continues safely.

  9. What is k at the end of the two loops below, each starting with int k = 3;?
    do { k -= 4; } while (k > 5);
    while (k > 5) { k -= 4; } (again starting with k = 3)

    Answer

    do-while runs the body once: k becomes −1, -1 > 5 is false, and the loop ends; the result is −1. while checks the condition first: because 3 > 5 is false, the body never runs; the result is 3.

2.2.11Further reading

  • Oracle, The Java Tutorials, “Language Basics” section: the official tutorial that explains variables, operators, expressions, and control-flow statements with short examples.
  • J. Gosling et al., The Java Language Specification, Java SE 21: the exact definition of keywords, literals (Chapter 3), types (Chapter 4), and the conversion rules (Chapter 5). The place to turn when you wonder why a compiler message appears.
  • T. Lindholm et al., The Java Virtual Machine Specification, Java SE 21: defines the bytecode instructions, the operand stack, and the structure of the .class file in detail; makes it easier to read javap -c output.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 13th ed., Chapter 3: treats primitive types, conversions, and operators from an experienced programmer’s point of view, pointing out common mistakes.

2.2.12References

  1. Oracle, The Java Tutorials: “Language Basics” (variables, operators, expressions, control flow), docs.oracle.com/javase/tutorial.
  2. J. Gosling et al., The Java Language Specification, Java SE 21 Edition (Chapter 3: lexical structure, keywords, literals; Chapter 4: types; Chapter 5: conversions).
  3. T. Lindholm et al., The Java Virtual Machine Specification, Java SE 21 Edition (bytecode and the JVM).
  4. P. Deitel, H. Deitel, Java: How to Program, 11th ed., Pearson, 2017 (Chapters 2–5).
  5. K. Sierra, B. Bates, Head First Java, 3rd ed., O’Reilly, 2022.
  6. C. S. Horstmann, Core Java, Volume I: Fundamentals, 13th ed., 2024 (Chapter 3).
  7. A. B. Downey, C. Mayfield, Think Java, 2nd ed., O’Reilly, 2019.

Related pages: Chapter 2.2 slides · Study questions · ASCII Table · Primitive Types Lab · Glossary · © Sercan Külcü. All rights reserved.