Computer Fundamentals and Introduction to Programming · Lecture Notes
Chapter 5: Getting Started with Java
Writing a program is only the first step of running it. The text you write is saved to a file, passes through a compiler, becomes an intermediate code, and runs on a virtual machine. Each step along this path has its own rules and its own error messages. This note begins with the concepts of a program and a programming language. It then describes the origins of Java, the relationship among the JDK, the JRE, and the JVM, and the first Java program line by line. Printing to the console, escape sequences, and string concatenation are worked through with examples. These are followed by the compile-and-run steps, the inside of bytecode, the basic building blocks of the language, and comments. The last sections cover the kinds of errors, how to read error messages, and the preparation to do before coding. All programs shown in the note were compiled and run with JDK 21; the compiler messages and console outputs are taken verbatim from those runs.
Learning outcomes
- Program
- Explain a program as a whole made of input, processing, state, and output; distinguish the syntax, semantics, type system, and execution model of a programming language.
- Java
- Relate source code, bytecode, and the JVM; explain what the JDK, the JRE, and the JVM contain and what each does.
- First program
- Write a Java file, compile it with
javac, and run it withjava; use themainmethod, command-line arguments, the difference betweenprintandprintln, escape sequences, and string concatenation correctly. - Errors
- Distinguish syntax, type, runtime, and logic errors; read compiler and JVM messages to find the place and the cause of an error.
5.1Programs and programming languages
A computer does nothing on its own. A calculator app, a game, and a banking system are all made of commands that tell the computer what to do, step by step. Writing these commands is called programming, and the whole of the commands written is called a program. The commands are written in an artificial language that both the computer and the human can work with.
5.1.1What is a program?
A program is a whole made of commands that a computer executes to perform a particular task. A program can take input, process data, keep intermediate values in memory, and produce output.
The four elements in the definition appear in every program. Input is the information given to the program from outside: a number typed at the keyboard, the contents of a file, or a measurement from a sensor. Processing is the steps that produce new values from the input: adding, comparing, sorting. State is the current condition of the values the program holds in memory while it runs. Output is the results the program gives to the outside: a line written to the screen, a saved file, or a lit lamp.
Figure 5.1 shows these elements on a small example. The program takes two grades: 70 and 90. In the first step the grades are read. In the second step they are added, and the total, 160, is stored in memory. In the third step the total is divided by 2 and 80 results. In the last step 80 is printed to the screen. For the grades 50 and 60, the same program prints 55. The program does not change; only the input changes. This is what makes a program valuable: it is written once and run over and over with different inputs.
Two things determine a program's behavior. The first is the rules of the language it is written in: what each symbol means and how a number is stored. The second is the method the programmer chose, that is, the algorithm. In the average example, "first add, then divide" is an algorithm. The same algorithm can be written in different languages. This note uses Java as the language.
5.1.2The aspects of a programming language
In natural languages such as English, a sentence also has two aspects: whether it is written correctly and what it says. "Me read the book on table" is defective grammatically. "The table read the book" is well formed but makes no sense. In programming languages, two more aspects are added to these two. A programming language is studied from four aspects.
int total = price * qty;. The syntax requires the statement to end with ;. The type system says that the product of two ints is also an int. The meaning is "multiply, store the result in the box." The execution model says that the result is stored in the total box in memory.Syntax is the set of rules that determines the valid way of writing a program. Semantics defines what happens when a valid piece of program is executed. The type system ensures that every value has a type and that only operations appropriate to its type are performed on a value. The execution model describes the order in which commands are executed and how values are held in memory.
Figure 5.2 shows these four aspects on a single statement: int total = price * qty;. In terms of syntax, the statement starts with a type name, followed by a name, an equals sign, an expression, and a semicolon. If the semicolon is forgotten, the statement is invalid. In terms of the type system, price and qty are integers (int), and the product of two integers is also an integer. The result can therefore be put into total, which has type int. In terms of meaning, the statement says "multiply price by qty and write the result to total." In terms of the execution model, a box named total is set aside in memory and the result is stored in this box.
In Java, the syntax and type rules are checked before the program is run. This check is done by the compiler. A program with a forgotten semicolon, or one that tries to put text into a number box, is never run; the compiler reports the error with a line number. Mistakes concerning meaning, on the other hand, often show up only while the program is running. A program that forgets to divide when computing an average compiles flawlessly but produces a wrong result.
5.2Source code and tools
The text a programmer writes is called source code. Source code is written for humans: it consists of readable words, numbers, and symbols. A processor, however, understands only its own machine instructions. Several tools are used together to turn source code into a running program.
5.2.1The plain-text source file
A Java program is written to a file with the extension .java. This file is called a source file. A source file is plain text. A plain-text file contains only characters; it has no formatting information such as font, color, bold type, or page layout. A Java file can therefore be opened with Notepad, a code editor such as VS Code, or an integrated development environment. A Word document, on the other hand, is not plain text; it also stores formatting information. If source code is written in Word and saved as .docx, the compiler cannot read the file.
Hello.java is a plain-text file. On disk each character is stored as one or more bytes: the letters of the word "public" are the bytes 70, 75, 62, 6C, 69, 63 in hexadecimal. ASCII characters take 1 byte in UTF-8, while letters such as ç, ğ, ş take 2 bytes.On disk everything is bytes. In a plain-text file, each character is converted to one or more bytes according to a character encoding. Today the most common encoding is UTF-8. In UTF-8, the letters of the English alphabet, digits, and punctuation marks take a single byte, as in ASCII. Figure 5.3 shows the bytes of the word "public": the letter p is 70 in hexadecimal, that is, 112 in decimal. The letters ç, ğ, ı, ö, ş, ü, which are specific to Turkish, take two bytes each in UTF-8.
The encoding is an agreement between the programs that write and read the file. If a file is saved as UTF-8 and read with another encoding, non-ASCII letters get corrupted. The word "Dünya" may appear as "Dünya". The Java compiler also assumes an encoding when it reads a source file. Since JDK 18 the default encoding has been UTF-8. The examples in this note were compiled with JDK 21 without any extra options; words such as "Dünya", "Satır", and "İndirim" came out correctly. If an older JDK is used, the encoding must be stated explicitly to the compiler with the -encoding UTF-8 option.
Beyond the encoding, two more details should be consistent. The first is line endings: Windows writes a line ending with two characters (CR LF), Linux and macOS with a single character (LF). The Java compiler accepts both. But mixed line endings in the same project cause needless differences in tools that track changes. The second is the file name. In Java, the file name must be the same as the name of the public class inside it: the class Hello is written to the file Hello.java.
Plain text has one more advantage. Version control systems record which line of a file was changed, by whom, and when. Git is the most common example. Because these tools compare line by line, they work best with plain-text files.
5.2.2Programming tools
Between writing a Java program and running it, it passes through the hands of several tools. Each tool has one specific job.
| Tool | Job | Example |
|---|---|---|
| Editor | Writing and saving source code | Notepad, VS Code |
| IDE | Project management, code completion, compiling, running, and debugging | IntelliJ IDEA, Eclipse, NetBeans |
javac | Compiling source code to bytecode | javac Hello.java |
java | Running a class on the JVM | java Hello |
javadoc | Generating API documentation in HTML from the documentation comments in the source code | javadoc Hello.java |
| Version control | Keeping the history of changes | Git |
An editor is enough to write source code. Unlike ordinary text editors, code editors color keywords, adjust indentation automatically, and show line numbers. An integrated development environment (IDE) combines the editor with a compiler, a runner, and a debugger in a single window.
javac is the Java compiler; it reads the source code, checks it, and translates it into an intermediate code called bytecode. The java command starts a Java Virtual Machine and runs the bytecode. javadoc generates documentation as web pages from comments written in a special format inside the code. The online documentation of Java's own class library was also produced with this tool.
Hello.java, written in the editor, is compiled with javac into the file Hello.class. The java command runs this file on the JVM and Hello is printed to the console. javadoc generates documentation from the source code; version control keeps the history of the source code (v1 → v2 → v3).Figure 5.4 shows the order of the tools. The point to notice is this: javadoc and version control work with the source file, not with the .class file. Because the .class file can be regenerated at every compilation, it is usually not added to version control. The real product to keep is the source code.
5.3Java
Java is one of the most widely used programming languages today. We meet it in banking systems, in Android apps, in big-data tools, and in universities' introductory programming courses. The most important reason for this ubiquity is that Java programs can run independently of the operating system and the processor. This section describes how Java was born, where it is used, and what software is needed to run a Java program.
5.3.1The birth and versions of Java
Java's story begins at Sun Microsystems in 1991. In a project called the "Green project," James Gosling and his team set out to design a language for smart home devices such as television set-top boxes. The language was first called Oak. The home-device market did not attract the expected interest, but in those same years the Web was spreading rapidly. A language that could behave the same way on computers with different operating systems was exactly what the Web needed. The language was released in 1995 under the name Java.
Java's design goal is summed up in a single sentence: write once, run anywhere. A Java program is compiled once. The bytecode the compiler produces runs unchanged on Windows, Linux, or macOS, on a Java Virtual Machine written for that system. The programmer does not have to compile separately for each operating system.
Java's other basic features are these:
- Object-oriented: Programs are built around classes and objects. Even the smallest Java program is written inside a class.
- Strong type checking: Every variable has a type, and the compiler catches type mismatches before the program runs.
- Automatic memory management: The memory of objects that are no longer used is reclaimed automatically by garbage collection. The programmer does not free memory by hand.
- A large class library: There are ready-made classes for jobs such as printing to the screen, reading files, network connections, and date computation.
Java's owner changed in 2010: Oracle bought Sun Microsystems and has developed the language ever since. Java's source code has been open since 2006 and is published in the OpenJDK project. Today, besides Oracle, organizations such as Eclipse Adoptium (Temurin), Amazon (Corretto), and Microsoft offer OpenJDK-based JDK distributions. The examples in this note were run with the Eclipse Adoptium distribution of JDK 21.
Since 2018 a new Java release has come out every six months: in March and September. Each release receives updates for only a few months. Some releases, however, are declared long-term support (LTS) releases and receive security updates for years. Organizations and courses therefore prefer LTS releases. Java 8, 11, 17, 21, and 25 are LTS releases. This course uses Java 21.
5.3.2Where is Java used?
Java's areas of use are very broad. The table below summarizes the best-known ones.
| Area | Description |
|---|---|
| Enterprise servers | Back ends of banking, e-commerce, and government systems; the Spring and Jakarta EE frameworks |
| Android | Apps are written in Java or Kotlin; the bytecode is converted to a form suited to the Android runtime (ART) on the phone |
| Big data | Data-processing tools such as Hadoop and Kafka run on the JVM |
| Development tools | IDEs such as IntelliJ IDEA, Eclipse, and NetBeans are themselves written in Java |
| Smart cards | The small programs on SIM cards and bank cards run with Java Card |
| Games | The Java Edition of Minecraft; desktop games and simulations |
Some of the examples in the table are the achievement not of the Java language but of the Java Virtual Machine. The JVM does not run only Java. Languages such as Kotlin, Scala, and Groovy are also compiled to the same bytecode and run on the same virtual machine. Most Android apps today are written in Kotlin, but the underlying execution model is the same.
5.3.3JDK, JRE, and JVM
Three abbreviations appear constantly in Java documents: JDK, JRE, and JVM. The three are nested layers; the outer layer contains the inner one.
The Java Virtual Machine (JVM) is the software that executes bytecode. The JRE (Java Runtime Environment) is the combination of the JVM and the Java class library: it contains everything needed to run a Java program. The JDK (Java Development Kit) adds the development tools (javac, jar, javadoc …) to the JRE.
In short: JDK = JRE + development tools, JRE = JVM + class library. Figure 5.6 shows this relationship. A user who will only run a ready-made Java program needs just the JRE. A developer who will write and compile programs must install the JDK, because javac exists only in the JDK.
This distinction has changed somewhat today. Since Java 11, Oracle no longer offers a separate JRE package; both developers and users install the JDK. Some distributors still offer the JRE separately. Knowing the three layers as concepts remains important, because error messages and documentation use these names.
The five parts of the JVM do their work in turn during the life of a program. The class loader reads the .class file from disk and brings it into memory. The bytecode verifier checks that the loaded code obeys the rules; for example, that an instruction does not try to use a value that is not on the stack. The interpreter executes the bytecode instructions one by one. The JIT compiler (just-in-time compiler) speeds up the frequently run parts by translating them into the processor's machine code. The garbage collector reclaims unused memory as the program runs.
More than one Java may be installed on a computer, and the command line uses the first one it finds. On the computer where this note was prepared, javac came from JDK 21 while the java on the PATH came from an old Java 8 installation. When Hello.class, compiled with JDK 21, was run with Java 8, this message was received:
Exception in thread "main" java.lang.UnsupportedClassVersionError: Hello has been compiled by a more recent version of the Java Runtime (class file version 65.0), this version of the Java Runtime only recognizes class file versions up to 52.0The message is clear: the class file is in version 65 (Java 21) format, while the JVM running it recognizes at most version 52 (Java 8). An old JVM cannot run new bytecode. The fix is to make sure that the outputs of java -version and javac -version show the same version.
5.4The first Java program
The traditional first step in learning programming is a program that prints a short greeting to the screen. This program is small, but it contains all the required parts of a Java program. This section first breaks the program into its parts and then traces step by step how the JVM runs it.
5.4.1The parts of the program
The following program is saved in a file named Hello.java:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello");
}
}When the program is compiled and run, it writes a single line to the console:
> javac Hello.java
> java Hello
HelloIn console sessions, lines starting with > are commands typed by the user; the lines below are the command's output. There is no line under the javac command: when compilation succeeds, the compiler stays silent.
main method, the entry point of the program. The innermost line is the statement that writes to the console, and it ends with ;. Each } closes the block it opened.Figure 5.7 shows the program as three nested layers. Let us examine the lines one by one.
public class Hello {is a class declaration. In Java all code lives inside a class. After theclasskeyword comes the name of the class.publicsays that the class is accessible from anywhere. The name of a public class must be exactly the same as the file name: the classHellois written to the fileHello.java. The{at the end of the line opens the body of the class.public static void main(String[] args) {declares the main method. A method is a unit of work with a name. When the JVM runs a program, it always starts at themainmethod; for this reasonmainis the program's entry point.System.out.println("Hello");is the statement that does the real work of the program.System.outrepresents the standard output stream, that is, the console. Theprintlnmethod writes the text given to it to the console and ends the line. The"Hello"in double quotes is a string: a text value made of characters. The statement ends with a semicolon.- The first
}closes the body of themainmethod, and the second}closes the body of the class.
Each of the words at the head of the main method has a job:
| Word | Meaning |
|---|---|
public | The method is accessible from anywhere; the JVM can also call it from outside |
static | The method belongs to the class; no object needs to be created first to call it |
void | The method returns no value |
main | The name of the method; the JVM looks for the entry point by this name |
String[] args | The method's parameter: an array of strings that carries the command-line arguments |
Each of these words (access modifiers, static methods, return types, arrays) is a topic in its own right. For the first programs it is enough to write this line as it is. Still, knowing why each word is there makes it easier to understand the message you get when it is written wrong.
5.4.2The signature of the main method
A method's name, parameters, and return type make up its signature. When the JVM runs a class, it looks for a method with exactly the signature public static void main(String[] args). What is interesting is this: a main with a wrongly written signature gives no compile error. To the compiler, a method named Main, or one that returns int, is an ordinary, valid method. The error appears only when the java command tries to start the program.
The table below shows what happens when main is written in different forms in class A in the file A.java. Each version was compiled without errors with javac A.java and then run with java A.
| As written | When run with java A |
|---|---|
public static void main(String[] args) | runs |
public static void Main(String[] args) | Error: Main method not found in class A, … |
public void main(String[] args) | Error: Main method is not static in class A, … |
public static int main(String[] args) | Error: Main method must return a value of type void in class A, … |
static void main(String[] args) | Error: Main method not found in class A, … |
public static void main(String a[]) | runs |
The JVM's message is actually longer and also suggests the correct signature. For example, when Main is written with a capital letter, the full message is:
Error: Main method not found in class A, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.ApplicationThe JavaFX sentence on the last line is a reminder that JavaFX applications with a graphical interface have another way of starting; it is not used in this course. Three conclusions follow from the table:
- Java is case-sensitive:
Mainandmainare different names. public,static, andvoidare mandatory. When one is missing, the JVM either cannot find the method at all or finds it and rejects it.- The parameter's name is free:
acan be written instead ofargs. The old notationString a[]is also valid. Still, the Java convention is to writeString[] args.
In newer versions of Java these rules have been relaxed. From Java 25 on, a main method that is not public or static, or even one with no parameter, can also be launched. This course uses the classic signature that works in Java 21 and in every version.
5.4.3The program step by step
After the command java Hello is typed, several steps pass before Hello appears on the screen. Knowing these steps is the basis for understanding runtime errors and stack traces.
Hello.class file and runs the main() method; the System.out output stream carries the text to the console.| Step | Line | What happens | Call stack | Console |
|---|---|---|---|---|
| 1 | 1 | The JVM starts and loads Hello.class into memory | empty | |
| 2 | 2 | The JVM calls the main method; since no argument was given, args is an empty array | main(args) | |
| 3 | 3 | The text "Hello" is passed to the println method | main(args) → println | |
| 4 | 3 | println writes the text and adds a newline; control returns to main | main(args) | Hello⏎ |
| 5 | 4 | The } of the main block is reached; main ends | empty | Hello⏎ |
| 6 | 5 | There is no more code to run; the JVM exits | — | Hello⏎ |
The "call stack" column of the table shows which methods are running at that moment. When one method calls another, the called method is added to the top of the stack; when it finishes, it is removed. In step 3, main has called println, and both are on the stack. When println finishes, only main remains. When main also finishes, the stack empties and the program ends. In total 1 statement ran and 1 line of output was produced.
5.4.4Command-line arguments
The args parameter of the main method is the way to give the program information from the command line. The words written after the class name in the java command are called command-line arguments. The JVM puts these words into an array of strings and passes it to main.
An array is a structure that holds several values of the same type, by sequence number. Each cell in the array has an index, and indices start at 0. args[0] is the first argument and args[1] is the second. args.length gives the number of arguments in the array. The following program uses the arguments:
public class Greet {
public static void main(String[] args) {
System.out.println(args.length);
System.out.println("Hi " + args[0]);
System.out.println("Hi " + args[1]);
}
}The program was run first with two arguments and then with one argument:
> java Greet Ali Veli
2
Hi Ali
Hi Veli
> java Greet Ali
1
Hi Ali
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Greet.main(Greet.java:5)args array in two runs. Top, java Greet Ali Veli: two cells are filled, args.length = 2. Bottom, java Greet Ali: only args[0] exists, args[1] does not; the length is 1.In the first run the args array is ["Ali", "Veli"] (Figure 5.9, top). Line 3 prints the number of arguments, that is, 2. On line 4 the expression "Hi " + args[0] joins two strings side by side and Hi Ali is printed. Line 5 prints Hi Veli in the same way.
In the second run, both the code and the .class file are the same; there is no need to recompile. Only the input changes. The array has a single cell. Lines 3 and 4 print 1 and Hi Ali. Line 5 tries to access the nonexistent args[1]. In this case the JVM throws an exception: ArrayIndexOutOfBoundsException, that is, "array index out of bounds." The message says that index 1 lies outside an array of length 1. The line below shows that the error occurred in line 5 of the file Greet.java, in the main method. The program stops at that point.
The compiler could not have known this error. At compile time it is not known how many arguments the program will be given. The error appears at run time and depends on the input. If no argument is given at all, the error occurs one line earlier, on line 4:
> java Greet
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Greet.main(Greet.java:4)The same Greet program is run with the command java Greet Ayşe "Ali Veli". What is the output?
Command-line arguments are separated by spaces. Double quotes, however, make the space inside part of the argument. So "Ali Veli" is not two arguments but one, and the quotes are not included in the argument. The args array is ["Ayşe", "Ali Veli"], with length 2:
> java Greet Ayşe "Ali Veli"
2
Hi Ayşe
Hi Ali VeliExtra arguments, on the other hand, cause no error. In the command java Greet 1 2 3 the length of the array is 3. Since the program uses only the first two cells, the third is ignored:
> java Greet 1 2 3
3
Hi 1
Hi 25.4.5print and println
There are two basic ways to write to the console: System.out.print and System.out.println. Both write the value given to them. The difference between them appears after the writing is done. println (print line) adds a newline after writing; the next output starts on the line below. print adds no newline; the next output continues on the same line, where it left off.
In the console, the cursor determines where the text will appear. It is enough to think of the cursor as the place where the next character will be written. Let us follow the cursor's journey in the following program:
public class Greeting {
public static void main(String[] args) {
System.out.print("Hello ");
System.out.println("World");
System.out.println("Java");
}
}Hello World
Java| Line | Statement | Console | Cursor |
|---|---|---|---|
| 2 | (main starts) | ▌ | line 1, column 1 |
| 3 | print("Hello ") | Hello ▌ | line 1, column 7 |
| 4 | println("World") | Hello World▌ | line 2, column 1 |
| 5 | println("Java") | Hello WorldJava▌ | line 3, column 1 |
print("Hello "): the cursor is on the same line, right after the space (line 1, column 7). Bottom, after println("World"): the line has ended and the cursor is at the start of the next line (line 2, column 1).The string "Hello " has six characters: five letters and the trailing space. print writes these six characters and the cursor stays at column 7 (Figure 5.10). The trailing space matters. Without it "World" would be written right against it, and the output would be HelloWorld. println("World") continues on the same line and then ends the line. println("Java") writes to the new line and ends that line too. Three calls were made, but only two lines were formed, because only println ends a line.
System.out.println() with no parameter writes only a newline. If the cursor is in the middle of a line, it ends that line; if it is at the start of a line, it produces an empty line. print, on the other hand, always needs a value; System.out.print() with no parameter is a compile error.
Writing the last output of the program with print. The output appears on the screen, but because the line is not ended, the console prompt sticks to the same line: Result: 80C:\docs>. Using println on the last line of the program prevents this mess.
5.5Escape sequences and string concatenation
A string begins with a double quote and ends with a double quote. This simple rule raises two questions. First, what do you do if a double quote has to appear inside the text? Second, how do you put characters that cannot be typed directly at the keyboard, such as a newline or a tab, into a string? Java solves both in the same way: escape sequences.
5.5.1Escape sequences
An escape sequence is a notation inside a string or character literal that begins with a backslash (\) and stands for a single special character. The backslash makes the character that follows "escape" from its usual meaning.
| Sequence | Meaning | Example | Output |
|---|---|---|---|
\n | newline (line break) | "A\nB" | A, then B on the line below |
\t | tab | "Name\tGrade" | Name Grade |
\" | double quote | "\"Java\"" | "Java" |
\\ | backslash | "C:\\docs" | C:\docs |
\' | single quote (inside a character literal) | '\'' | ' |
In the source code, \n looks like two characters: a backslash and the letter n. The compiler, however, turns it into a single character, the newline character. Neither the backslash nor the n appears on the screen; the line simply ends. In the same way \" is a single double-quote character and does not end the string. \\ gives a single backslash. Because the backslash itself starts escape sequences, the only way to write it is to write it twice.
A single quote causes no problem inside a string: "Ali's grade" is written without an escape. The single quote has a special meaning only in char literals, which hold a single character. 'A' is a character literal; the single-quote character itself is written '\''.
5.5.2Tab and newline step by step
The tab character \t moves the cursor to the next tab stop. In consoles, tab stops are usually every 8 columns: at columns 1, 9, 17, 25 … A tab takes the cursor to the next stop whatever column it is in. That is why values written after words of different lengths line up in the same column. The following program uses this:
public class Escape {
public static void main(String[] args) {
System.out.println("Name\tGrade");
System.out.println("Ali\t85");
System.out.println("\"Java\" rocks");
System.out.print("Line 1\nLine 2\n");
}
}Name Grade
Ali 85
"Java" rocks
Line 1
Line 2| Line | As written | What happened? |
|---|---|---|
| 3 | Name, tab, Grade, newline | "Name" occupies columns 1 to 4; the tab moves the cursor to column 9. 4 spaces fall in between; "Grade" starts at column 9. |
| 4 | Ali, tab, 85, newline | "Ali" occupies 3 columns; the tab again moves the cursor to column 9. 5 spaces fall in between; 85 lands exactly under the "Grade" heading. |
| 5 | "Java" rocks, newline | \" writes a double quote without ending the string. |
| 6 | Line 1, newline, Line 2, newline | A single print produces two lines: the two \n in the string end two lines. |
The print call on the last line is worth noting. print itself adds no newline, but the \n characters inside the string end the lines. So System.out.print("Line 1\nLine 2\n") and two separate println calls give the same output. One detail: the newline that println adds varies by operating system. On Windows, println writes two characters (\r\n), while \n is a single character everywhere. In the console the two look the same.
Alignment with tabs has a limit. If a word is 8 characters or longer, the tab moves the cursor to the next stop, column 17, and the alignment breaks. That is why tabs suit simple tables with short headings.
How do you write a program that prints a student's term courses as an aligned table with their credit and ECTS values, and adds the totals below it?
Each row is written with a println, and the columns are separated with \t. The totals are written on two lines with a single print and two \n:
public class Card {
public static void main(String[] args) {
System.out.println("Course\tCredits\tECTS");
System.out.println("Physics\t4\t6");
System.out.println("Java\t3\t5");
System.out.print("Total credits: 7\nTotal ECTS: 11\n");
}
}Course Credits ECTS
Physics 4 6
Java 3 5
Total credits: 7
Total ECTS: 11"Course" has 6 characters, "Physics" 7, and "Java" 4. Since all three are shorter than 8, the first tab moves the cursor to column 9 on every line, and the credit values line up. The second tab moves to column 17; the ECTS values are aligned too. Because "Physics" has 7 characters, only 1 space follows it.
5.5.3Escape sequence pitfalls
The backslash causes the most trouble when writing Windows file paths. Windows separates folders with a backslash: C:\data. If this path is written into a string as it is, the compiler takes \d as the start of an escape sequence:
public class BadPath {
public static void main(String[] args) {
System.out.println("C:\data");
}
}BadPath.java:3: error: illegal escape character
System.out.println("C:\data");
^
1 errorThere is no escape sequence \d. The compiler says illegal escape character and points at the problem with ^. The program does not compile. A more insidious case is when the letter after the backslash forms a valid escape sequence:
"C:\new" looks like 6 characters in the source but is 5 characters in memory: C, :, newline, e, w. The screen shows "C:" and, on the line below, "ew".| Statement | Result |
|---|---|
System.out.println("C:\data"); | compile error: illegal escape character; there is no escape sequence \d |
System.out.println("C:\new"); | compiles but prints two lines: C: and ew |
System.out.println("C:\\data"); | C:\data: the backslash is written twice |
System.out.println("Ali's grade"); | Ali's grade: a single quote inside a string is written without an escape |
System.out.println("Caf\u00E9"); | Café: \u and four hexadecimal digits give a Unicode character |
System.out.println("C:/data"); | C:/data: Java's file operations accept a forward slash on Windows too |
System.out.println("A\\nB"); | A\nB (one line): \\ gives one backslash, and the n that follows is an ordinary letter |
Run together in a single program, in the order of the two tables, all the examples that can be compiled give this output:
public class Escapes {
public static void main(String[] args) {
System.out.println("A\nB");
System.out.println("Name\tGrade");
System.out.println("\"Java\"");
System.out.println("C:\\docs");
System.out.println('\'');
System.out.println("C:\new");
System.out.println("C:\\data");
System.out.println("Ali's grade");
System.out.println("Caf\u00E9");
System.out.println("C:/data");
System.out.println("A\\nB");
}
}A
B
Name Grade
"Java"
C:\docs
'
C:
ew
C:\data
Ali's grade
Café
C:/data
A\nBLines 7 and 8 of the output come from the statement "C:\new" (Figure 5.12). Because the program runs without error, this mistake is easy to miss: the compiler does not warn; only the output is odd. The last line shows the opposite: "A\\nB" produces no newline and writes a backslash and the letter n to the screen.
The notation that starts with \u is called a Unicode escape. The four hexadecimal digits that follow are the Unicode number of the character. The number of the letter é is 00E9 in hexadecimal. Unicode escapes are used to write characters that are not on the keyboard or that risk corruption because of the file encoding:
public class Unicode {
public static void main(String[] args) {
System.out.println("Café");
System.out.println("İstanbul");
System.out.println("Zürich");
}
}Café
İstanbul
ZürichWriting a Windows path with a single backslash. Whether "C:\docs\notes" compiles depends on the letters: because \d is invalid, you get a compile error. "C:\temp\new", on the other hand, compiles, but \t becomes a tab and \n a newline. The rule is simple: every backslash in a string is written as \\, or the path is written with forward slashes as "C:/temp/new".
5.5.4String concatenation
The + sign does two different jobs in Java. Between two numbers it adds: the result of 40 + 45 is 85. If at least one operand is a string, it concatenates: the other operand is converted to text and appended. The result of "Score: " + 85 is the string "Score: 85". This second job is called string concatenation.
When an expression contains several + signs, two rules determine the result:
- Operations at the same precedence are performed from left to right. The expression
a + b + cis evaluated as(a + b) + c. *and/are always performed before+. Parentheses come before everything.
At each + step the question "is one of the operands a string?" is asked afresh. If the answer is yes, concatenation is done; if no, addition. Once a string has appeared, all the + signs to its right are concatenations, because the intermediate result on the left is now a string.
"Score: " + 40 + 45 is evaluated left to right with two concatenations: first "Score: " + 40 → "Score: 40", then "Score: 40" + 45 → "Score: 4045".public class Concat {
public static void main(String[] args) {
System.out.println(40 + 45 + " points");
System.out.println("Score: " + 40 + 45);
System.out.println("Score: " + (40 + 45));
System.out.println("Avg: " + 85 / 2);
System.out.println(5 + 3);
System.out.println("5 + 3");
}
}85 points
Score: 4045
Score: 85
Avg: 42
8
5 + 3| Expression | Steps | Output |
|---|---|---|
40 + 45 + " points" | 40 + 45 → 85 (two ints: addition); 85 + " points" → "85 points" | 85 points |
"Score: " + 40 + 45 | "Score: " + 40 → "Score: 40"; "Score: 40" + 45 → "Score: 4045" | Score: 4045 |
"Score: " + (40 + 45) | parentheses first: 40 + 45 → 85; "Score: " + 85 → "Score: 85" | Score: 85 |
"Avg: " + 85 / 2 | / first: 85 / 2 → 42 (when two integers are divided, the fraction is discarded); "Avg: " + 42 | Avg: 42 |
5 + 3 | two ints: addition | 8 |
"5 + 3" | everything inside quotes is text; no computation is done | 5 + 3 |
The fourth row of the table needs separate attention. In 85 / 2, both operands are integers, so the result is an integer too. The fractional part is not rounded but discarded: the result is 42, not 42.5. Note that here / is performed before + and that the result is appended to the string as 42.
Writing a sum with a description but without parentheses. The statement System.out.println("Sum: " + a + b); prints Sum: 4045 for a = 40 and b = 45, because the leftmost operand is a string and both numbers are appended to the text. If the sum itself is wanted, "Sum: " + (a + b) must be written.
5.6The structure of a Java file
The Hello program consisted of a single class. In real programs, two more kinds of declarations can appear before the class at the top of a file: package and import. The parts of a Java file are written in a fixed order.
package school;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
System.out.println("Hello");
}
}school/Program.java: 1. the package declaration, 2. the import declarations, 3. the class. Inside the class is the main method, and inside the method are the statements.Figure 5.14 shows the structure. The order is as follows:
package school;says which package the class belongs to. A package is a namespace that keeps related classes together; it is similar to folders on a computer. If there is a package declaration, it must be the first statement in the file, and the file lives in a folder with the same name as the package:school/Program.java.import java.util.Scanner;makes it possible to use a class from another package by its short name. Without this line the class would have to be written everywhere with its full name,java.util.Scanner.importdeclarations come after the package declaration and before the class. In this exampleScanneris not used; it is written only to show the place. An unusedimportgives no error.public class Program { … }is the class itself. The name of a public class is the same as the file name.
Note that no import is needed for the System class. The most basic classes such as System and String are in the java.lang package, and this package is added to every file automatically.
A class with a package is compiled and run from the folder one level above the package folder. When running, the full name of the class, including the package name, is written:
> javac school/Program.java
> java school.Program
Hello
> java Program
Error: Could not find or load main class Program
Caused by: java.lang.ClassNotFoundException: ProgramWhen only Program is typed in the last command, the JVM looks for a Program class with no package and cannot find it. The real name of the class is school.Program. The first programs use no package; the classes live in the default, unnamed package. IDEs, however, often add a package declaration when creating a new project. This detail must not be forgotten when a file written in an IDE is compiled on the command line.
5.7Compiling and running
A Java program does not run the moment it is written. It is first compiled and then run. These two steps are done with two separate commands and involve two kinds of files: the compiler reads the .java file, while the JVM runs the .class file. Understanding this distinction well prevents most of the problems beginners run into most often.
5.7.1The compilation pipeline
Compilation is checking the source code as a whole and translating it into another language. In Java, the compiler javac translates the source code into a processor-independent intermediate code called bytecode. Bytecode is stored in files with the extension .class and runs on the Java Virtual Machine.
There are five steps from writing a Java program to seeing its output. Let us call all of these steps together the compilation pipeline:
- Write. The source code is written in an editor and saved as
Hello.java. The file name must be the same as the name of the public class. - Compile. The command
javac Hello.javaruns the compiler. The compiler reads the whole file before the program has even started to run; it checks the syntax and the types. - Bytecode. If compilation succeeds, the file
Hello.classappears in the same folder. This file is not plain text but a binary file. It is the same on Windows, Linux, and macOS. - Run. The command
java Hellostarts the JVM. This command is given the class name, not the file name; the.classextension is not written. The JVM's class loader brings the.classfile into memory, the verifier checks the bytecode, and thenmainis called. - Output. The JVM interprets the bytecode; it translates the frequently run parts into machine code with the JIT compiler.
printlnwritesHelloto the console.
javac succeeds, Hello.class appears in the folder. This file is a processor-independent intermediate code, and its first four bytes are CA FE BA BE in hexadecimal.Every .class file begins with the same four bytes: CA FE BA BE in hexadecimal. This "magic number" lets the JVM recognize that the file really is a Java class file. The first eight bytes of the Hello.class file compiled for this note are ca fe ba be 00 00 00 41. The last two bytes are the class file's version number: 41 in hexadecimal is 65 in decimal and denotes Java 21. This is the "class file version 65.0" mentioned when an old JVM rejects a new class file.
If the compiler finds an error, the pipeline stops at the second step:
javac reports the error with a line number (Hello.java:3: error: ';' expected) and produces no .class file. There is nothing to run.A program with a compile error does not run at all; not even part of it runs. The compiler checks the whole file, and if it finds even a single error it produces no .class. This is an important difference from interpreted languages that run line by line. In a language such as Python, the lines before the faulty line may run. In Java, an error on line 50 means line 1 will not run either.
5.7.2Installing the JDK and the commands
To write Java programs you first install a JDK. After installation, a few basic commands are used on the command line:
| Command | What it does |
|---|---|
java -version | shows the installed Java version |
javac -version | shows the compiler version (javac exists only in the JDK) |
javac Hello.java | compiles: produces Hello.class |
java Hello | runs (no extension is written) |
java Hello.java | Java 11 and later: compiles and runs a single-file program, leaving no .class file |
After installation, the first thing to do is to run the two version commands and check that they show the same version. On the computer used for this note, the output of the JDK 21 commands is:
> java -version
openjdk version "21.0.3" 2024-04-16 LTS
OpenJDK Runtime Environment Temurin-21.0.3+9 (build 21.0.3+9-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.3+9 (build 21.0.3+9-LTS, mixed mode, sharing)
> javac -version
javac 21.0.3The usage in the last row of the table is practical for quick experiments. If a .java file is given to the java command, the JVM compiles the file in memory and runs it immediately:
> java Hello.java
HelloThis way works for single-file programs and leaves no .class file on disk. To show that compiling and running are two separate steps, this note uses the two-step way.
PATH and JAVA_HOME. When javac is typed on the command line, the operating system looks for a program of that name in the folders listed in the PATH environment variable. If the JDK's bin folder is not on the PATH, you get a "command not found" error. The fix is to add the JDK's bin folder, for example C:\Program Files\Eclipse Adoptium\jdk-21.0.3.9-hotspot\bin, to the PATH. The JAVA_HOME environment variable points to the JDK's main folder; build tools and IDEs look at this variable to find Java.
Non-ASCII letters in the Windows console. Turkish letters can get corrupted in two places. The first is at compile time: if the compiler reads the file with the wrong encoding, the letters are corrupted before they even enter the bytecode. In JDK 18 and later the compiler's default encoding is UTF-8; in earlier versions you have to write javac -encoding UTF-8 Hello.java. The second is the console itself. If the program runs correctly but the letters look corrupted on the screen, the console's code page can be switched to UTF-8: first run the command chcp 65001.
5.7.3Compile, change, recompile
One of the things that surprises beginners most is this: the source code is changed, the program is run, but the old output appears. The reason is that the java command never looks at the source code. The JVM runs only the bytecode in the .class file. In the following session, the folder initially contains only Hello.java, and the program prints Hello.
> java Hello
Error: Could not find or load main class Hello
Caused by: java.lang.ClassNotFoundException: Hello
> javac Hello.java
> java Hello.class
Error: Could not find or load main class Hello.class
Caused by: java.lang.ClassNotFoundException: Hello.class
> java Hello
HelloThree separate situations appear in this part. In the first command there is no Hello.class yet; the JVM cannot find a class named Hello. The Caused by line gives the underlying cause of the error: ClassNotFoundException, that is, the class was not found. Compilation then succeeds silently. In the third command, java is given a file name. The JVM looks for a class named "Hello.class". Because class names cannot contain a dot in Java, it interprets this as a class named class in a package named Hello and cannot find it. The correct command, without the extension, runs the program.
Now in the editor the text "Hello" is changed to "Hi", the file is saved, and the session continues:
> java Hello
Hello
> javac Hello.java
> java Hello
Hi| Step | Command or action | Hello.java | Hello.class | Output |
|---|---|---|---|---|
| 1 | javac Hello.java | println("Hello") | prints "Hello" (new) | — |
| 2 | java Hello | println("Hello") | prints "Hello" | Hello |
| 3 | edit and save | println("Hi") | prints "Hello" (old!) | — |
| 4 | java Hello | println("Hi") | prints "Hello" (old!) | Hello |
| 5 | javac Hello.java | println("Hi") | prints "Hi" (new) | — |
| 6 | java Hello | println("Hi") | prints "Hi" | Hi |
Hello.java now contains println("Hi"), but Hello.class is still the old bytecode that prints "Hello." The source changed; the .class did not.Table 5.12 and Figure 5.17 show the same result: the .class file is not updated by itself. In the fourth step the output is still Hello. You must recompile after every change to the source code.
Letter case in the class name also matters. Windows file names do not distinguish case, but Java does. With the command java hello, Windows finds the file Hello.class, but the JVM sees that the name of the class inside the file is Hello, not hello, and rejects it:
> java hello
Error: Could not find or load main class hello
Caused by: java.lang.NoClassDefFoundError: hello (wrong name: Hello)The phrase wrong name: Hello in the message means "wrong name; the correct one is Hello."
5.7.4Working with an IDE
Compiling and running on the command line shows plainly what happens behind the scenes. In daily work, however, most programmers use an IDE. The IDE hides the same steps behind a button.
';' expected) is shown. When the error is fixed and the ▶ Run button is pressed, the IDE first compiles and then runs.The main conveniences an IDE provides are these:
- The ▶ Run button performs the compile and run steps back to back. Changed files are recompiled first; for that reason the stale-
.classproblem does not arise. - Instant error display: the IDE compiles in the background while you type. Compile errors are marked with a red underline; when the pointer is over it, the compiler's message appears.
- Code completion: when you type
System.out., the methods that can be used are listed. Misspelled method names become rarer this way. - Automatic indentation and renaming: when a variable's name is changed, it changes everywhere it occurs.
- Debugger: stops the program at a breakpoint, shows the current values of the variables, and steps through the program line by line.
The common Java IDEs are IntelliJ IDEA, Eclipse, and NetBeans. VS Code does the same jobs with Java extensions. An IDE is a great convenience, but knowing what happens behind the scenes is still necessary. On servers or over remote connections there is often no IDE; there is only the command line. The messages an IDE shows are also javac's messages. Someone who knows the compile steps on the command line can read these messages in any environment.
5.8Bytecode and the JVM
Java's "compile once, run anywhere" principle is possible thanks to bytecode. This section explains why bytecode is processor-independent, what is inside a .class file, and how the JVM executes bytecode.
5.8.1Compile once, run anywhere
In languages such as C, the compiler translates source code directly into the machine code of a particular processor. A program compiled for a Windows computer with an Intel processor does not run on a Mac with an ARM processor; it has to be compiled separately for that one. The Java compiler, however, produces the machine code of no real processor. It produces the instructions of an imaginary processor that does not exist, namely the Java Virtual Machine. These instructions are called bytecode.
Hello.class file runs on the JVMs on Windows (x86-64), Linux (x86-64), and macOS (ARM64). Each JVM translates the bytecode into the machine code of its own processor.What makes the imaginary processor real is the JVM written separately for each platform (Figure 5.19). The Windows JVM and the macOS JVM read the same bytecode. Each runs it on its own processor. Two ways are used for this. The interpreter reads the bytecode instructions one by one and executes them. The JIT compiler translates the frequently run parts, for example a loop that runs thousands of times, into that processor's machine code and runs the machine code directly on later iterations. In this way Java programs are both portable and fast.
Class loading, bytecode verification, and garbage collection are also parts of the runtime. The verifier is especially important. A .class file may have been downloaded from the network or may be corrupted. The verifier checks, before running, that the code obeys the JVM's rules.
5.8.2Inside bytecode: javap
A .class file is a binary file; if it is opened with Notepad, meaningless characters appear. The javap tool that comes with the JDK is used to read the instructions inside it. The -c option lists the bytecode instructions of each method in readable form:
> javap -c Hello
Compiled from "Hello.java"
public class Hello {
public Hello();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #13 // String Hello
5: invokevirtual #15 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
}The output has two methods. The first is public Hello();, that is, the class's constructor. No such method was written in the source code. If no constructor is written for a class, the compiler adds an empty one itself. The second method is main, and it consists of four instructions:
| Position | Command | What it does |
|---|---|---|
| 0 | getstatic | pushes the reference to the System.out object onto the operand stack |
| 3 | ldc | pushes the constant "Hello" onto the operand stack |
| 5 | invokevirtual | takes two values from the stack and calls println |
| 8 | return | ends main |
The numbers to the left of the instructions are the instruction's byte position within the method. The opcode of each instruction is a single byte; the name "bytecode" comes from this. Some instructions are followed by operand bytes. getstatic takes 3 bytes (1 opcode, 2 operand), so the next instruction is at position 3. ldc takes 2 bytes, and invokevirtual starts at position 5. It also takes 3 bytes; return is at position 8. Markers such as #7 and #13 are entry numbers in the class file's constant pool. javap writes what each entry is in the comment on the right: #13 is the string "Hello."
The JVM is a stack machine. Real processors hold values in small memory cells called registers when they compute. The JVM instead puts values on an operand stack and performs operations on the values at the top of the stack. A stack is like plates piled on top of each other: the value put on last is taken off first. Not using registers keeps bytecode processor-independent, because every processor has a different number of registers.
Comments and whitespace in the source code do not enter the bytecode. A Hello program with plenty of comments (5.10) compiles to the same four instructions.
5.8.3The JVM executes bytecode
To see how the stack machine works, let us trace a slightly longer program. The program adds two numbers and prints the result:
public class Sum {
public static void main(String[] args) {
int a = 3;
int b = 4;
int c = a + b;
System.out.println(c);
}
}7The command javap -c Sum gives these instructions for the main method:
0: iconst_3
1: istore_1
2: iconst_4
3: istore_2
4: iload_1
5: iload_2
6: iadd
7: istore_3
8: getstatic // System.out
11: iload_3
12: invokevirtual // println(int)
15: returnThe four lines in the source have turned into 12 bytecode instructions. The names of the instructions follow a pattern. The leading i stands for int. iconst_3 pushes the constant 3 onto the stack. istore_1 takes the value at the top of the stack and writes it into local variable number 1. iload_1 copies the value of local variable number 1 onto the stack. iadd takes two values from the stack, adds them, and pushes the result onto the stack.
The method's local variables are held in numbered slots. Slot 0 holds main's parameter args. The following slots are assigned in the order of the source code: number 1 is a, number 2 is b, number 3 is c. The table below shows the slots and the operand stack after each instruction.
| Position | Command | 1 (a) | 2 (b) | 3 (c) | Operand stack | Console |
|---|---|---|---|---|---|---|
| 0 | iconst_3 | — | — | — | [3] | |
| 1 | istore_1 | 3 | — | — | [ ] | |
| 2 | iconst_4 | 3 | — | — | [4] | |
| 3 | istore_2 | 3 | 4 | — | [ ] | |
| 4 | iload_1 | 3 | 4 | — | [3] | |
| 5 | iload_2 | 3 | 4 | — | [3, 4] | |
| 6 | iadd | 3 | 4 | — | [7] | |
| 7 | istore_3 | 3 | 4 | 7 | [ ] | |
| 8 | getstatic | 3 | 4 | 7 | [System.out] | |
| 11 | iload_3 | 3 | 4 | 7 | [System.out, 7] | |
| 12 | invokevirtual | 3 | 4 | 7 | [ ] | 7 |
| 15 | return | 3 | 4 | 7 | [ ] | 7 |
iadd instruction. Top, after iload_1 and iload_2: the stack holds 3 and 4. Bottom, after iadd: the two values were taken off and their sum, 7, was pushed. The local variables do not change in the meantime.A pattern stands out in the trace. The line int c = a + b; becomes four instructions: two loads, one addition, one store. The addition instruction iadd knows nothing of variable names; it works only with the two values at the top of the stack. Bringing values onto the stack is the job of iload and taking them from the stack to a variable is the job of istore (Figure 5.20).
The line System.out.println(c); follows the same pattern. First the object on which println will be called (System.out), then the value to be printed (7), are pushed onto the stack. invokevirtual takes both off the stack and calls the method println(int). 7 is written to the console. main ends with return. The method's frame is removed, and the local variables and the operand stack vanish with the frame.
The gaps in the instruction positions can also be explained. Every instruction from 0 to 7 is a single byte, because instructions such as iconst_3 and istore_1 carry their operands in their names. Because getstatic takes 3 bytes, the next instruction is at position 11. iload_3 is 1 byte and invokevirtual is 3 bytes, so return falls at position 15.
In the Sum program, how does the bytecode change if 5 is written instead of 3, 2 instead of 4, and multiplication is used instead of addition?
public class Product {
public static void main(String[] args) {
int a = 5;
int b = 2;
int c = a * b;
System.out.println(c);
}
}The structure of the instructions stays the same; only the constants and the operation change. iconst_5 replaces iconst_3, iconst_2 replaces iconst_4, and the multiplication instruction imul replaces iadd. javap -c Product confirms this prediction:
public static void main(java.lang.String[]);
Code:
0: iconst_5
1: istore_1
2: iconst_2
3: istore_2
4: iload_1
5: iload_2
6: imul
7: istore_3
8: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
11: iload_3
12: invokevirtual #13 // Method java/io/PrintStream.println:(I)V
15: returnThe program prints 10. The stack is [5, 2] just before imul and [10] just after.
5.9The building blocks of the language
When the compiler reads a Java file, it first breaks it into small pieces and then builds larger structures from those pieces, just as letters form words, words form sentences, and sentences form paragraphs. This section starts with the smallest pieces, tokens, and reaches the concepts of expression, statement, and block.
5.9.1Tokens
A token is the smallest piece of source code that is meaningful to the compiler. Java has five kinds of tokens: keywords, identifiers, literals, operators, and separators.
int total = price * 3;: int is a keyword, total and price are identifiers, = and * are operators, 3 is a literal, and ; is a separator.Let us get to know the five kinds with Figure 5.21:
- Keywords are words reserved for the language itself:
int,class,public,static,void,if, and so on. Their meanings are fixed, and they cannot be used for any other purpose.int class = 5;cannot be written. - Identifiers are names given by the programmer: variable, method, and class names.
total,price,Hello, andmainare identifiers. An identifier starts with a letter,_, or$and continues with letters and digits. It cannot contain a space and cannot start with a digit. - Literals are values written directly into the code:
3,120,2.5,"Hello",'A',true. - Operators are the symbols that perform operations:
+,-,*,/,=,>, and so on. - Separators are the symbols that determine the structure:
;,.(){}[].
Java is a case-sensitive language. count and Count are two different identifiers. System is right and system is wrong. There is no keyword Int; there is only int. Statements usually end with a semicolon; blocks are enclosed in curly braces.
5.9.2Whitespace, indentation, and braces
The following two programs are identical. The first is written on a single line, the second is indented according to Java convention:
public class OneLine { public static void main(String[] args) { System.out.println("Hello"); } }public class OneLine {
public static void main(String[] args) {
System.out.println("Hello");
}
}Both programs compile and turn into the same bytecode. The main instructions in the javap -c output of the one-line version are the same four as in the Hello program: getstatic, ldc, invokevirtual, return. To the compiler, spaces, tabs, and newlines only separate tokens. x=1; and x = 1; are the same. But publicclass counts as a single word and is not read as two tokens. (The two class files are not byte-for-byte identical, because a .class file also stores line numbers for error messages. The instructions, however, are the same.)
If whitespace does not matter to the compiler, why does indentation matter? Because code is written for humans as much as for the compiler. Indentation shows the reader how blocks are nested. In the Java convention the rules are these:
- Each new block starts 4 spaces further in than the previous one.
- The opening brace
{stays at the end of the line. - The closing brace
}is on its own line and lines up with the line that opened it.
When these rules are followed, you can see at a glance which block a } closes. In code with broken indentation it is very hard to notice that a brace is missing.
There is one exception: spaces inside a string are part of the text. "Hello " and "Hello" are different strings; the first has six characters, the second five. print("Hello ") and print("Hello") give different output.
5.9.3Expressions, statements, and blocks
Tokens come together to form expressions, and expressions form statements.
An expression is a piece of code that produces a value when evaluated: 2 + 3 → 5, num > 0 → true or false. A statement is a unit of code that completes an action and usually ends with ;: total = 5;, System.out.println(total);. A block groups the statements inside curly braces into a single structure.
The difference is clear from the question: "Is this piece a value or an action?" price * qty is a value (such as 360); by itself it does nothing. total = price * qty;, however, is an action: it computes the value and writes it to total. A statement can contain one or more expressions.
price * qty, produces the value 360; the expression of the second, total > 300, produces the value true.The following piece of code uses all four concepts together. When the piece is placed in the main method of a class and run, a single line is written to the console:
int price = 120; // declaration
int qty = 3; // declaration
int total = price * qty; // expression + assignment
if (total > 300) { // condition + block
System.out.println("Discount");
}Discount| Step | Line | What happens | price | qty | total | Console |
|---|---|---|---|---|---|---|
| 1 | 1 | an int box is set aside in memory for price, and 120 is written | 120 | ? | ? | |
| 2 | 2 | the qty box is created | 120 | 3 | ? | |
| 3 | 3 | the expression on the right is evaluated: price * qty → 120 * 3 → 360 | 120 | 3 | ? | |
| 4 | 3 | the value produced is assigned to total | 120 | 3 | 360 | |
| 5 | 4 | the condition expression: total > 300 → 360 > 300 → true; the block is entered | 120 | 3 | 360 | |
| 6 | 5 | the statement in the block runs | 120 | 3 | 360 | Discount |
| 7 | 6 | the block ends | 120 | 3 | 360 | Discount |
The first and second lines are declaration statements: each defines a variable and gives it its initial value. In the third line the expression is evaluated first, and then the assignment is made (Table 5.15, steps 3 and 4). The right-hand side of an equals sign is always computed first. The if statement on the fourth line consists of a condition expression and a block. Because the condition comes out true, the block runs. If qty were 2, total would be 240, the condition would be false, and the block would not run at all. A block makes several statements a single unit: if the condition is true, all the statements in the block run; if it is false, none of them does.
5.10Comments
Code is written not only for the compiler but also for the people who will read it: the programmer returning to their own code months later, teammates, the instructor who grades the course. A comment is text added to the source code for the reader, which the compiler ignores.
5.10.1Three comment styles
Java has three comment styles:
- A comment that starts with
//lasts until the end of the line. It is used for short notes. - A comment that starts with
/*and ends with*/can span several lines. - A comment that starts with
/**and ends with*/is a Javadoc comment. Thejavadoctool generates API documentation from these comments. They are usually written immediately above class and method declarations.
/** The Hello program (Javadoc). */
public class Hello {
/* A comment spanning
several lines */
public static void main(String[] args) {
// print the greeting
System.out.println("Hello");
}
}> java Hello
Hello
> javap -c Hello
Compiled from "Hello.java"
public class Hello {
public Hello();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #13 // String Hello
5: invokevirtual #15 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
}javac skips comments. The lines // print the greeting and /* comment */ in the source do not enter the bytecode; the .class file contains only instructions.The javap output of the commented program is the same as that of the uncommented Hello program (Figure 5.23). The compiler skips comments; they do not enter the bytecode and do not slow the program down.
A good comment, instead of repeating what the code does, says why it does it. The comment i = i + 1; // increase i by one is useless; anyone looking at the code already sees that. total = total / 2; // the two exams have equal weight, however, gives information that cannot be derived from the code.
5.10.2Comment pitfalls
Comments look simple, but they hide a few pitfalls.
Nested multi-line comments. /* … */ comments cannot be nested. A comment ends at the first */ it meets:
public class Nested {
public static void main(String[] args) {
/* outer /* inner */ rest */
System.out.println("Hello");
}
}Nested.java:3: error: illegal start of expression
/* outer /* inner */ rest */
^
1 errorThe compiler treats the part /* outer /* inner */ as a comment; the second /* in the middle has no meaning because it is inside the comment. The comment ends at the */ after inner. What remains is rest */, and the compiler takes it for code. rest counts as an identifier and * as the multiplication operator. After the multiplication a value is expected, but a / comes, and no expression can start with /. The compiler says illegal start of expression; the ^ mark points at this last / character. To disable a section that contains /* */, it is safer to comment out the lines one by one with //.
Comment markers inside quotes. // or /* */ inside a string is not a comment; it is part of the text. Let us trace which lines run in the following program:
public class CommentTest {
public static void main(String[] args) {
// System.out.println("1");
System.out.println("2"); // System.out.println("3");
/* System.out.println("4");
System.out.println("5"); */
System.out.println("6 // not a comment");
System.out.println("7 /* not a comment */");
System.out.println("a // b");
}
}2
6 // not a comment
7 /* not a comment */
a // bThe first line is a comment from start to end. On the second line "2" is printed; what comes after //, that is, the statement that would print 3, is a comment. /* … */ comments out two lines (4 and 5) together. The // and /* */ markers in the last three lines are inside quotes, so they are printed as they are.
Disabling code temporarily. Putting // at the start of a line makes it not run without deleting it. This is a method often used when hunting for a bug. In IDEs, the Ctrl+/ shortcut turns the selected lines into comments in this way and reverses it.
Stale comments. The most insidious pitfall is a comment that contradicts the code:
double price = net * 1.20; // VAT 18%The code compiles and works correctly: the VAT rate was updated and the code was written for 20%. But the comment states the old rate and misleads the reader. When a comment and the code contradict each other, the compiler runs the code; the code is always what is right. When the code is changed, the related comment must be updated too.
What does the following program print?
public class Comments {
public static void main(String[] args) {
int x = 5; // x = 10;
/* x = 20; */ x = x + 1;
System.out.println("x = " + x); // x = 100
System.out.println("// x = " + (x * 2));
}
}On line 3, x becomes 5; // x = 10; is a comment. On line 4, /* x = 20; */ is a comment, but x = x + 1; on the same line is outside the comment and runs: x becomes 6. Line 5 prints x = 6; the // x = 100 at the end of the line is merely a wrong note. The // on line 6 is inside quotes, so it is part of the text; x * 2 is computed first in the parentheses and gives 12:
x = 6
// x = 125.11Errors
Every programmer makes mistakes. What sets a good programmer apart is being able to find and fix an error quickly. The first step is to recognize the kind of error. When an error shows up determines who catches it and how to look for it.
5.11.1Kinds of errors
javac), runtime errors while the program runs (the JVM), and logic errors only when the result is checked.| Error | When? | Who catches it? | Example |
|---|---|---|---|
| Syntax | at compile time | javac | a missing semicolon |
| Type | at compile time | javac | assigning text to a number variable |
| Runtime | while the program runs | JVM | dividing an integer by zero |
| Logic | the program runs but the result is wrong | testing only | a wrong order of operations |
A syntax error is a violation of the language's rules of writing: a missing semicolon, an unclosed parenthesis or quote. A type error is when the syntax is correct but a value is used where it does not fit its type. These two together are called compile errors. A program with a compile error does not turn into a .class file and does not run at all.
A runtime error is when a compiled program meets an operation it cannot perform while running. In Java, the JVM then throws an exception and the program stops unless special provision has been made. A logic error is the most insidious kind: the program compiles, runs without error, and produces a result, but the result is wrong. No tool gives an error message. A logic error can be caught only by someone who compares the result with the expected value.
The earlier errors are caught, the cheaper they are to fix. A compile error is found on the programmer's computer, within seconds. A logic error, however, may be noticed only after the program has reached users. That Java checks types at compile time is therefore an advantage: the programmer sees many mistakes before even running the program.
5.11.2Four errors, four examples
The following four programs give one example of each kind of error. The real message on JDK 21 is given for each.
Syntax error. There is no semicolon at the end of line 3:
public class Bug1 {
public static void main(String[] args) {
System.out.println("Hello")
}
}Bug1.java:3: error: ';' expected
System.out.println("Hello")
^
1 errorThe compiler shows where the rule was broken with a line number: Bug1.java:3. ';' expected means "a semicolon was expected." The 1 error on the last line is the total number of errors. No .class is produced. The fix: add ; at the end of the line.
Type error. A string is being put into a variable of type int:
public class Bug2 {
public static void main(String[] args) {
int num = "42";
}
}Bug2.java:3: error: incompatible types: String cannot be converted to int
int num = "42";
^
1 errorThe syntax is flawless: type, name, equals sign, value, semicolon. But because "42" is inside double quotes, it is not a number but a two-character text. The message says "incompatible types: String cannot be converted to int." The ^ points at the incompatible value. The fix: remove the quotes and write int num = 42;.
Runtime error. The program compiles, but while running an integer is divided by zero:
public class Bug3 {
public static void main(String[] args) {
int a = 10, b = 0;
System.out.println(a / b);
}
}> javac Bug3.java
> java Bug3
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Bug3.main(Bug3.java:4)javac stays silent: the syntax and the types are correct. The compiler does not check that the value of b will be 0. While the program runs, an integer division by zero is attempted on line 4. Faced with this operation, which is undefined in mathematics too, the JVM throws an ArithmeticException. The message says / by zero and gives the location of the error: Bug3.java, line 4, the main method. The program stops there.
Logic error. The average of two grades is wanted:
public class Bug4 {
public static void main(String[] args) {
int a = 70, b = 90;
System.out.println(a + b / 2);
}
}> javac Bug4.java
> java Bug4
115There is no error message, but the result is wrong. The average of 70 and 90 is 80, and the program prints 115. The reason is operator precedence: / is performed before +. The expression a + b / 2 is evaluated as a + (b / 2): 90 / 2 = 45, 70 + 45 = 115. The fix: write (a + b) / 2; this expression gives (70 + 90) / 2 = 160 / 2 = 80.
Concluding "the program compiled and ran, so it is correct." Compilation shows only that there are no syntax or type errors. A program with a logic error also compiles and runs without trouble. A program can be trusted to be correct only by comparing its output with the expected results for known inputs.
5.11.3Common compile and launch errors
Most of the compile errors beginners meet fit a few patterns. The table below gives them with the real messages of JDK 21.
| Error | Real message | Fix |
|---|---|---|
| Missing semicolon | Hello.java:3: error: ';' expected | add ; at the end of the previous statement |
Wrong method name (System.out.printn) | error: cannot find symbolsymbol: method printn(String)location: variable out of type PrintStream | make the name println |
Lowercase letter (system.out) | error: package system does not exist | write System with a capital S |
| Class name and file name do not match | error: class Greeter is public, should be declared in a file named Greeter.java | make the file name the same as the public class name |
Wrong way of running (java Greeter) | Error: Could not find or load main class Greeter | there is no .class file, or the name or location is wrong; compile first, and do not write the extension |
The full form of the messages shows more clearly where the problem is. When a method name is misspelled:
Hello.java:3: error: cannot find symbol
System.out.printn("Hello");
^
symbol: method printn(String)
location: variable out of type PrintStream
1 errorcannot find symbol says that the compiler does not recognize a name (a variable, method, or class name). The symbol: line below gives which name was not found, and the location: line where it was looked for. According to this message, a method printn that takes a String was looked for in the variable out of type PrintStream and was not found. The ^ mark points at the dot after out; the method was being attached there.
When System is written in lowercase, the message is surprising at first sight:
Hello.java:3: error: package system does not exist
system.out.println("Hello");
^
1 errorThe compiler knows no class named system. Seeing the dots in system.out.println, it thinks system might be a package name and cannot find such a package either. That is why the message says "package"; the real problem is letter case. The same happens for a misspelled System: for Sytem.out.println the message is package Sytem does not exist.
If the name of the public class differs from the file name, the compiler reports the error on the class declaration line:
public class Greeter {
public static void main(String[] args) {
System.out.println("x");
}
}> javac Hello.java
Hello.java:1: error: class Greeter is public, should be declared in a file named Greeter.java
public class Greeter {
^
1 error
> java Greeter
Error: Could not find or load main class Greeter
Caused by: java.lang.ClassNotFoundException: GreeterBecause compilation failed, Greeter.class was not produced either; the following java Greeter command cannot find the class. Letter case counts too. If the class Hello is saved in the file hello.java, the compiler distinguishes case even though Windows file names do not:
hello.java:1: error: class Hello is public, should be declared in a file named Hello.java
public class Hello {
^
1 errorThere are two more common compile errors. An unclosed quote makes everything up to the end of the line part of the string:
Quote.java:3: error: unclosed string literal
System.out.println("Hello);
^
1 errorIn the "unclosed string literal" message, the ^ points at the quote where the string began. A missing closing brace, on the other hand, is noticed at the end of the file. In the message below, the last } that closes the class has been deleted:
Hello.java:4: error: reached end of file while parsing
}
^
1 errorThe message "reached end of file while parsing" says that the compiler was still expecting a block to close when the file ended. The real location of the error is not the end of the file but the place where the } is missing. In correctly indented code this place is easy to find.
5.11.4Reading an error message
Error messages look frightening at first sight, but they are always written in the same layout. Learning the layout once makes every message easier to read.
javac message: file, line, kind, description; below it the offending source line and a ^ that points at the place where the error was noticed. Bottom, a runtime message: the type and detail of the exception, followed by the stack trace, which says in which method and at which line of which file it occurred.The first line of a javac message has the form file:line: error: description (Figure 5.25). In the message Score.java:3: error: ';' expected, the file is Score.java, the line is 3, the kind is error, and the description is ';' expected. The second line shows the offending source line verbatim. The ^ mark on the third line points at the column where the compiler noticed the problem. At the very end the total number of errors is written.
The ^ does not always point at the error itself but at the place where the compiler noticed it. A missing semicolon is noticed where the statement ends, that is, at the end of the line. A missing } is not noticed until the end of the file and is reported as reached end of file while parsing. So if the error cannot be found at the place shown, look at the previous line or at the blocks above.
Runtime messages have a different layout. The first line begins with Exception in thread "main" and gives the type and detail of the exception: java.lang.ArithmeticException: / by zero. The lines below it that begin with at are the stack trace: they list which methods were on the call stack at the moment of the error, starting from the innermost method. at Bug3.main(Bug3.java:4) says the error occurred in the main method of the class Bug3, at line 4 of the file Bug3.java. In the first programs the stack trace is a single line, because only main runs. As methods call one another, the trace gets longer.
5.11.5Fixing errors in order
A program can have more than one error. The compiler does not always report them all at once. The following program has two errors: the semicolon is missing on line 3, and the method name is wrong on line 4.
public class Score {
public static void main(String[] args) {
int score = 85
System.out.printn("Score: " + score);
}
}The first compilation reports only one error:
Score.java:3: error: ';' expected
int score = 85
^
1 errorThe mistake on line 4 is not visible yet. The reason is that the compiler works in stages. It parses the syntax first. As long as the syntax is broken, it does not go on to semantic checking, that is, checking names and types. The error is fixed, line 3 becomes int score = 85;, and the file is saved. This time the second compilation reports a different error:
Score.java:4: error: cannot find symbol
System.out.printn("Score: " + score);
^
symbol: method printn(String)
location: variable out of type PrintStream
1 errorThe syntax is now correct; semantic checking runs and cannot find a method named printn. The symbol: line states the name that was not found. The method name is corrected to println. The third compilation succeeds silently, Score.class is created, and the program runs:
> javac Score.java
> java Score
Score: 85| Compilation | line 3 | line 4 | Error reported | Score.class |
|---|---|---|---|---|
| 1 | int score = 85 ✗ | printn ✗ | Score.java:3: error: ';' expected | none |
| 2 | int score = 85; ✓ | printn ✗ | Score.java:4: error: cannot find symbol | none |
| 3 | int score = 85; ✓ | println ✓ | none | created |
The lesson of this example is that after fixing one error, the number of errors may not decrease, and may even increase. This does not mean the fix was wrong; the compiler has merely moved on to the next stage. Conversely, errors in the same stage are reported together. The two type errors in the following program appear in a single compilation:
Two.java:3: error: incompatible types: String cannot be converted to int
int a = "5";
^
Two.java:4: error: incompatible types: String cannot be converted to int
int b = "6";
^
2 errorsA syntax error, however, can also confuse the lines that follow it, and errors that do not really exist may be reported. For this reason, always start with the first error. Fix the first error, recompile the file, and read the new messages.
5.12Before coding
Knowing how to read error messages is important, but the cheapest error is the one never made. Most logic errors can be prevented by a little preparation on paper before the code is written.
5.12.1A program is a recipe
A recipe lists the ingredients, gives the steps in order, and says what will be obtained at the end. A program has the same structure. The inputs correspond to the ingredients, the statements to the steps of the recipe, and the output to the finished dish. In a good recipe it is clear what each step requires and what it produces: "After the dough has risen (precondition), it goes into the oven and bakes for 30 minutes (step); the bread browns (result)."
Figure 5.26 gives the recipe of a program that finds the average of two grades in four steps. The precondition and the value produced by each step are clear:
- Take the input. There is no precondition. It produces the values
grade1andgrade2. - Validate. Precondition: two grades have been read. Each grade is checked to be between 0 and 100. If there is an invalid grade, the recipe stops here and gives an error message.
- Process. Precondition: both grades are valid. The average is computed as
(grade1 + grade2) / 2. - Produce the result. Precondition: the average has been computed. A line such as "Average: 80" is printed.
The recipe should be tested by hand before coding. When the steps are followed for 70 and 90, does 80 come out? 160 / 2 = 80; yes. If 101 is entered, which step stops it? The second: because 101 > 100, the validation fails. Testing by hand catches logic errors before any code is written. In the order-of-operations example (a + b / 2), the error could have been seen at the recipe stage, because the recipe clearly says "first add, then divide."
Large recipes are divided into sub-recipes. In a cake recipe, "prepare the cream" can be a recipe of its own. In programs too, large jobs are divided into subtasks; in Java each subtask is written as a method. For the first programs a single main method is enough, but the recipe way of thinking should become a habit from the start.
5.12.2Sample input and expected output
There are four jobs to do before starting to code:
- Write down sample inputs and the expected output for each.
- Break the solution into steps in natural language or pseudocode.
- Determine the boundary cases and what to do on invalid input.
- Only then translate the steps into Java constructs.
The product of the first step is a small table. For the average program, a table like this can be prepared:
| Sample input | Expected output | Why? |
|---|---|---|
| 70, 90 | 80 | typical case |
| 0, 0 | 0 | lower bound |
| 101, 50 | error message | invalid input |
Each row of the table tests something different (Figure 5.27). The typical case shows whether the program works correctly in everyday use. The boundary case is the values at the ends of the valid range; this is where programs most often go wrong. A small slip such as writing <= instead of < shows up only at the boundary. The invalid input shows what the program does when faced with an unexpected value: it must not crash; it must give an understandable message.
The table has one more benefit: once the program is written, each row becomes a test. The program is run with these inputs and its output is compared with the expected column. That is why choosing different kinds of examples matters. A program tested only with typical inputs can hide a mistake such as the fractional part being discarded in the quotient of two integers. For example, for 75 and 80 the correct average is 77.5, but the quotient of two ints gives 77. This mistake does not show up until an input with an odd sum is tried.
5.13Summary
- A program is a whole made of commands that a computer executes to perform a task; it takes input, processes it, keeps state, and produces output. A programming language is studied from the aspects of syntax, semantics, type system, and execution model.
- Source code is written in a plain-text
.javafile. The character encoding (UTF-8), the line endings, and the file name must be consistent. The editor, the IDE,javac,java,javadoc, and version control are the tools on the program's journey. - Java was born at Sun Microsystems in 1995; it has been developed by Oracle since 2010, and its source code is in OpenJDK. Its design goal is the principle of write once, run anywhere. A new release comes out every six months; 8, 11, 17, 21, and 25 are LTS releases.
- JDK = JRE + development tools; JRE = JVM + class library. The JVM executes bytecode; it contains the class loader, the verifier, the interpreter, the JIT compiler, and the garbage collector.
- All Java code is inside a class. The name of the public class is the same as the file name. The JVM starts running at the method with the signature
public static void main(String[] args). Amainwith a wrong signature compiles but cannot be launched. Java is case-sensitive. - Command-line arguments reach
mainthrough theargsarray; indices start at 0, andargs.lengthis the number of arguments. Accessing an argument that does not exist throwsArrayIndexOutOfBoundsExceptionat run time. printlnadds a newline after writing;printdoes not. Escape sequences (\n,\t,\",\\,\',\u) put special characters into a string. In Windows paths, a single backslash either gives a compile error or silently produces wrong output.+adds between two numbers and concatenates if one of the operands is a string. Operations are performed left to right;*and/come first:"Score: " + 40 + 45→Score: 4045,"Score: " + (40 + 45)→Score: 85.javac Hello.javacompiles and producesHello.class;java Helloruns it. When the source changes, it must be recompiled, because the JVM runs only the.classfile. If there is a compile error, no.classis produced.- Bytecode is processor-independent and is stored in files that begin with
CA FE BA BE. The JVM is a stack machine:iloadpushes values onto the operand stack,iaddadds the values on the stack, andistorewrites the result to a local variable.javap -cshows bytecode in readable form. - The compiler splits code into tokens: keyword, identifier, literal, operator, separator. Whitespace only separates tokens; indentation is for the reader. An expression produces a value, a statement completes an action, and a block groups statements.
- Comments are written with
//,/* */, and/** */and do not enter the bytecode./* */cannot be nested; comment markers inside quotes are part of the text. - Syntax and type errors are found at compile time, runtime errors while running, and logic errors only when the result is checked. A
javacmessage has the formfile:line: error: description; the^shows where the error was noticed. The stack trace in a runtime message gives the method and the line of the error. Errors are always fixed starting from the first error. - Before coding, sample inputs, expected outputs, boundary cases, and error behavior are determined; the recipe is tested by hand.
5.14Key terms
The key terms of this chapter are listed below.
- program
- syntax
- semantics
- type system
- execution model
- source code
- source file
- character encoding
- compiler
- compilation
- bytecode
- Java Virtual Machine (JVM)
- Java Runtime Environment (JRE)
- Java Development Kit (JDK)
- class library
- class loader
- bytecode verifier
- just-in-time (JIT) compilation
- garbage collection
- long-term support (LTS)
- integrated development environment (IDE)
- Javadoc
- class declaration
- main method
- case-sensitive
- command-line argument
- console
- newline
- escape sequence
- tab stop
- Unicode escape
- string concatenation
- package
- environment variable
- stack machine
- operand stack
- token
- keyword
- identifier
- literal
- separator
- expression
- statement
- declaration statement
- comment
- syntax error
- type error
- compile error
- runtime error
- logic error
- exception
- stack trace
- error message
- boundary case
5.15Test Yourself
A computer has only a JRE installed and no JDK. Can
Hello.javabe compiled on this computer? Can aHello.classcompiled on another computer be run?Answer
It cannot be compiled:
javacis a development tool and exists only in the JDK. It can be run: the JRE contains the JVM and the class library, which is enough forjava Hello. With one condition: the.classfile must not have been compiled with a JDK newer than the JRE's version. Otherwise you get anUnsupportedClassVersionError.What is the output of the following program, and how many lines does it produce?
public class TY2 { public static void main(String[] args) { System.out.print("1"); System.out.print("2\n3"); System.out.println("4"); System.out.print("\"5\""); System.out.println(); } }Answer
12 34 "5"Three lines are produced. "1" and "2" are written on the same line; the
\nin"2\n3"ends the line and "3" starts on the line below.println("4")writes "4" on the same line and ends it. Because\"writes a double quote, the third line is"5"; the finalprintln()ends this line.What is the output of the following program? In each line, which of the
+signs is addition and which is concatenation?public class TY3 { public static void main(String[] args) { System.out.println("Result: " + 10 / 4 + 1); System.out.println(10 / 4 + 1 + " items"); System.out.println("Result: " + (10 / 4 + 1)); } }Answer
Result: 21 3 items Result: 3Line 1:
/is performed first, 10 / 4 = 2 (integer division). Then"Result: " + 2is concatenation and gives"Result: 2";+ 1is also concatenation:Result: 21. Line 2: 10 / 4 = 2, and2 + 1is addition because it is between two numbers and gives 3;3 + " items"is concatenation. Line 3: the parentheses are computed first, 2 + 1 = 3; then concatenation is done.The program
Bis below. What happens when it is run with the commandsjava Bandjava B Ece? What kind of error is it?public class B { public static void main(String[] args) { System.out.println("First argument: " + args[0]); } }Answer
> java B Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 at B.main(B.java:3) > java B Ece First argument: EceWhen no argument is given,
argsis an empty array (length 0) andargs[0]does not exist. The JVM throwsArrayIndexOutOfBoundsExceptionon line 3. Because the program compiled and the error occurred while running, depending on the input, it is a runtime error. With a single argument the program runs without trouble.What kind of error is each of the following: syntax, type, runtime, or logic? (a)
Public class D {(b)int x = 3.5;(c) Writing2 * a + bfor the perimeter of a rectangle (d)int a = 10, b = 0;thena / b.Answer
(a) A syntax error:
Publicwith a capital letter is not a keyword, and the compiler expects a class declaration at the start of the line. The message:class, interface, enum, or record expected. (b) A type error: 3.5 is a fractional number and does not fit intoint. The message:incompatible types: possible lossy conversion from double to int. (c) A logic error: the code compiles and runs, but the correct form is2 * (a + b). (d) A runtime error:ArithmeticException: / by zero.Does the statement
System.out.println("C:\temp\new");compile? If it does, what does it print? How is the correct path written?Answer
It compiles, because
\tand\nare valid escape sequences. But the output is wrong:\tbecomes a tab and\na newline. The screen shows "C:", a tab's worth of space, and "emp", and "ew" on the next line:C: emp ewThe correct way to write it is
"C:\\temp\\new"or"C:/temp/new".For the
mainmethod of the following program, what are the first eight instructions in thejavap -coutput? Why does the order of theiloadinstructions matter?public class Subtract { public static void main(String[] args) { int a = 2; int b = 5; int c = b - a; System.out.println(c); } }Answer
public static void main(java.lang.String[]); Code: 0: iconst_2 1: istore_1 2: iconst_5 3: istore_2 4: iload_2 5: iload_1 6: isub 7: istore_3 8: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream; 11: iload_3 12: invokevirtual #13 // Method java/io/PrintStream.println:(I)V 15: returnais in slot 1 andbin slot 2. Forb - a, firstb(iload_2) and thena(iload_1) are pushed onto the stack.isubsubtracts the top value from the value below it: 5 − 2 = 3. In addition the order does not change the result, but in subtraction it does; the loading order follows the order of the operands in the source code. The program prints 3.Hello.javahas been compiled and aHello.classthat printsHellohas been produced. Then in the source"Hello"is changed to"Hi"and saved, and without recompiling, the commandsjava Hello,java Hello.java,java Helloare run in turn. What does each command print?Answer
> java Hello Hello > java Hello.java Hi > java Hello Hellojava Helloruns the old bytecode in the.classfile and printsHello.java Hello.java, however, compiles the source file in memory on the spot and runs it, printingHi; it does not touch the.classfile on disk. So the last command again printsHello. The.classis renewed only byjavac.The following program is compiled. How many compilations are needed for the program to compile without errors? What message is received in each compilation?
public class Two { public static void main(String[] args) { System.out.println("A") system.out.println("B"); } }Answer
Three compilations are needed. The first compilation reports only the syntax error; the lowercase mistake on line 4 is not visible yet:
Iki.java:3: error: ';' expected System.out.println("A") ^ 1 errorWhen
;is added to line 3, the second compilation moves on to semantic checking and reports line 4:Iki.java:4: error: package system does not exist system.out.println("B"); ^ 1 errorWhen
systemis changed toSystem, the third compilation succeeds. There were two errors, but the compiler showed only one each time.A program is to be written that takes the side lengths of a rectangle and prints its area. Which sample inputs and expected outputs should be written in a table before coding?
Answer
A sample table: typical case, 3 and 4 → 12. A square, 5 and 5 → 25 (it must work when the two sides are equal too). A boundary case, 0 and 7 → 0 or the message "a side cannot be 0"; which of the two is wanted must be decided beforehand. Invalid input, −2 and 4 → an error message (a length cannot be negative). These last two rows bring out, before coding, decisions that were left missing in the problem definition.
5.16Further reading
- Oracle, The Java Tutorials, "Getting Started" and "A Closer Look at the 'Hello World!' Application": explain every part of the first program, the
mainsignature, and the compile-and-run steps from the official source, with short examples. - R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), 1.1 Your First Program: covers the edit-compile-run cycle, command-line arguments, and common error messages; the book's website (introcs.cs.princeton.edu) has a chapter summary and exercises.
- A. B. Downey, C. Mayfield, Think Java (2nd ed., O'Reilly, 2019), Chapter 1: explains programs, compilation, kinds of errors, and escape sequences in plain language for beginners; the book has a free online version.
- Oracle, The Java Language Specification, Java SE 21 Edition, Chapter 3 "Lexical Structure": gives the precise definition of tokens, identifiers, comments, and escape sequences. Chapters 2 and 6 of The Java Virtual Machine Specification explain the operand stack and instructions such as
iloadandiaddin detail.
5.17References
- P. Deitel, H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
- Y. D. Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, The Java Tutorials: A Closer Look at the "Hello World!" Application.
- Oracle, The Java Language Specification, Java SE 21 Edition: Chapter 3. Lexical Structure.
- Oracle, The Java Virtual Machine Specification, Java SE 21 Edition: online version.
- R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.1 Your First Program.
- A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online version).
- OpenJDK, JEP 330: Launch Single-File Source-Code Programs (Java 11); JEP 400: UTF-8 by Default (Java 18); JEP 512: Compact Source Files and Instance Main Methods (Java 25).
Related pages: Chapter 5 slides · Study questions · Java Compile and Run simulator · Glossary · © Sercan Külcü. All rights reserved.