Part 1 · The core language
1How Java runs
Before you write a real program you need an accurate picture of what happens between typing text into a file and seeing something appear on screen. This lesson builds that picture, then uses it to explain every word of the smallest Java program and the errors you will meet most often.
By the end you will be able to
- explain what
javacandjavaeach do, and what a.classfile is - write, compile and run a program from the terminal
- say what each word of
public static void main(String[] args)is for - print text that contains quotes, tabs, new lines and backslashes
- read a compiler error, and tell compile-time, launch and run-time failures apart
A program is a text file
A computer's processor understands only machine instructions: numbers that mean things like add these two values
, copy this value over there
or jump to that instruction
. Nobody writes those numbers by hand. A programming language lets you describe what you want in a readable form, and a tool translates your description into something the machine can carry out.
What you write is called source code. Java source code is plain text saved in a file whose name ends in .java. Plain text means the file contains only the characters you typed: no fonts, no bold, nothing hidden. That is why you write code in a code editor such as VS Code and never in a word processor.
The readable form has strict rules, called the language's syntax. A human reader fills in a missing full stop without noticing. The translator does not guess: one missing semicolon and it stops and tells you. That strictness is what lets a program mean exactly one thing.
Two steps: compile, then run
Getting from a Java source file to a running program takes two steps, compiling and running. Normally each is done by its own tool.
Step 1, compile. The tool javac (the Java compiler) reads your .java file and checks it against the rules of the language. If it finds a problem it reports it and produces nothing. If the file passes, javac writes a new file ending in .class that contains bytecode.
Bytecode is a compact set of instructions. It is not written for the processor in your computer. It is written for an imaginary computer called the Java Virtual Machine, or JVM.
Step 2, run. The tool java starts a JVM: a real program on your computer that plays the part of that imaginary machine. It loads your .class file and carries out the bytecode instructions one after another, translating them into real instructions for your actual processor as it goes.
Why two steps?
- Problems are caught before anything runs. The compiler examines the whole file first. A whole category of mistakes, such as misspelt names and missing punctuation, can never reach a running program.
- The same
.classfile runs everywhere. Windows, macOS and Linux each have their own JVM, and they all understand the same bytecode. You compile once, and the result runs on any of them, provided the JVM there is at least as new as the compiler you used.
Three names you will keep seeing
| Name | What it is |
|---|---|
| JVM | The program that runs bytecode. You start one each time you type java. |
| JDK | The Java Development Kit: what is installed on your computer. It contains a JVM, the standard library (thousands of ready-made classes, including the one that prints text), and the developer tools: javac, plus others: javadoc, which lesson 29 covers, and javap, which the section Looking inside a class file uses. |
| JRE | The Java Runtime Environment: a JVM and the standard library without the developer tools. It is enough to run programs but not to compile them. You will see the term in older articles; to write Java you want a JDK. |
Check your tools
In VS Code, choose File › Open Folder and open your course folder, the one you unzipped the course kit into (for example java-course). Then open a terminal with Ctrl+` (the key above Tab), or Terminal › New Terminal.
A terminal is a window where you type a command, press Enter, and read the reply. On Windows it runs a program called PowerShell. The text to the left of your cursor is the prompt; it shows which folder you are currently in
, and commands act on that folder. Three commands are enough to get around:
| Command | What it does |
|---|---|
cd name | Moves into the folder called name. Press Tab after the first few letters and the terminal completes the name for you. |
cd .. | Moves up to the folder that contains the current one. |
ls | Lists what is in the current folder. ls -Name lists the names only. |
Now ask both tools for their version numbers. On this page, lines starting with > are what you type (without the >); the other lines are the computer's reply.
> java -version java version "27.0.1.0.3" 2026-10-25 Java(TM) SE Runtime Environment (build 27.0.1.0.3+1-2) Java HotSpot(TM) 64-Bit Server VM (build 27.0.1.0.3+1-2, mixed mode, sharing) > javac -version javac 27.0.1.0.3
That output was captured on the computer this course was tested on, and this course was built and tested with that version. If either command answers that it is not recognized
or command not found
, the JDK is missing or the terminal cannot find it. Go back to the installation steps in Start here, which explain how the terminal finds the JDK, and check them again before going on.
Your first program
Do these steps yourself as you read.
- In VS Code's file explorer, find
work/m01-how-java-runsin your course kit and create a new folder inside it calledhello. - Inside
hello, create a new file calledHelloWorld.java. The capital H and capital W matter, and there are no spaces. - Type the following into the file, exactly. Type it; do not paste it. Then save with Ctrl+S.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}In the terminal, move into the folder with cd work\m01-how-java-runs\hello. Then compile, look at what appeared, and run:
> javac HelloWorld.java > ls -Name HelloWorld.class HelloWorld.java > java HelloWorld Hello, world!
Three things to notice.
javacprinted nothing. For the compiler, silence means success. It only speaks when something is wrong.- A new file appeared:
HelloWorld.class. That is the bytecode. You never edit it and rarely look at it; it exists for the JVM. - You ran
java HelloWorld, with no.classon the end. To run a compiled program, you givejavathe name of a class, not the name of a file. The JVM works out for itself which file holds that class.
You change the text in HelloWorld.java to "Hello again!" and save the file. Then, without compiling, you type java HelloWorld. What is printed?
Reveal the answer
The old text: Hello, world! The java tool runs the .class file, and the .class file is only as new as the last time you ran javac. Your edit exists in the source file but not yet in the bytecode.
The cycle is always edit, save, compile, run. Skipping save
or compile
is the most common reason for my change did nothing
. Try it now and see it happen.
Every word of HelloWorld
The program is five lines long, and nothing in it is decoration. Some words can only be fully explained later in the course; for those you get an accurate short version now and the lesson where the full story comes.
Line 1: the class
public class HelloWorld {class HelloWorld declares a class and gives it the name HelloWorld. In Java, all code lives inside a class. For now, think of a class as a named container for code. From lesson 8 onwards a class becomes much more than that, but the container picture is correct as far as it goes. Class names are written with a capital letter at the start of each word and no spaces.
public means the class may be used from anywhere. It has one consequence that matters today: a public class must be saved in a file with exactly the same name, plus .java. The class HelloWorld lives in HelloWorld.java, capital letters included.
{ opens the body of the class, and the } on line 5 closes it. Braces always come in pairs, and everything between a pair is inside
.
Line 2: the main method
public static void main(String[] args) {This line declares a method: a named block of instructions. When you type java HelloWorld, the JVM loads the class and looks inside it for a method called main. That method is where the program starts, so it is called the entry point. The line above is its standard form, and each word in it has a job:
| Word | Its job | Full story |
|---|---|---|
public | Makes the method usable from outside the class. The JVM, which calls it, is outside. | Lesson 9 |
static | The method belongs to the class itself, not to an object made from the class. That lets the JVM call it straight away, without creating anything first. | Lessons 8 and 11 |
void | The method hands no result back to whoever called it. | Lesson 5 |
main | The method's name. The JVM looks for this name specifically; Main or start will not do. | |
(String[] args) | The method's parameter: a list of pieces of text. It receives any extra words typed after the class name, so java HelloWorld red blue would deliver red and blue. This program ignores it. | Lessons 5 and 7 |
It is fine to treat this line as a fixed formula for a few lessons. The point of the table is that the formula is not magic. Each word is an ordinary part of the language, and each will be explained properly.
Line 3: the statement
System.out.println("Hello, world!");This is the only line that does something you can see. It is a statement: one complete instruction. Take it apart from the inside out:
"Hello, world!"is a string literal: text written directly into the program between double quotes. (String
is the programming word for a piece of text.) The quotes mark where the text begins and ends. They are not part of the text and are not printed.printlnis a method that prints the text it is given and then ends the line. The parentheses hold what you are giving it, which is called the argument.System.outsays whereprintlnis to be found.Systemis a class from the standard library.outis something inside that class which stands forstandard output
, normally your terminal. A dot meansthe thing on the right belongs to the thing on the left
. Read the whole line as: inSystem, findout; onout, callprintlnwith this text.;ends the statement, as a full stop ends a sentence. Every statement needs one. Lines 1 and 2 have none because they are not statements; they open a block with{.
Lines 4 and 5 are the closing braces of the method and of the class.
Three rules that apply everywhere
- Java is case-sensitive.
Systemandsystemare different names. So aremainandMain. - Layout is for humans. Outside string literals, the compiler does not care about extra spaces, blank lines or indentation; this whole program could legally sit on one line. People care a great deal. The convention is to indent four spaces for each brace you are inside, which makes the structure visible and a missing brace easy to spot.
- Braces, parentheses and quotes come in pairs. Most beginners' errors are an unpaired one of these or a missing semicolon.
Statements run in order
A method can hold any number of statements. The JVM carries them out one at a time, starting at the top of main and working down. When it reaches the closing brace of main, the program ends.
// Prints the steps for making a cup of tea.
// Statements run one at a time, from the top of main to the bottom.
public class TeaTime {
public static void main(String[] args) {
System.out.println("1. Boil the water.");
System.out.println("2. Add the tea bag.");
// print does NOT end the line, so the next output continues on it.
System.out.print("3. Wait");
System.out.print("...");
System.out.println(" three minutes.");
System.out.println(); // prints an empty line
System.out.println("Enjoy!");
}
}> javac TeaTime.java > java TeaTime 1. Boil the water. 2. Add the tea bag. 3. Wait... three minutes. Enjoy!
Compare the code with its output and three new things appear.
print and println are different. println prints its text and then ends the line, so the next output starts on a fresh line. print prints its text and stays where it is. Lines 9 to 11 are three separate statements that together produce one line of output.
println() with nothing in the parentheses prints no text and ends the line. The result is an empty line.
Comments. Everything from // to the end of that line is a comment. The compiler ignores it completely; it is a note for whoever reads the code, including you next month. A longer comment can start with /* and run across several lines until */. A good comment says why something is done, since the code already shows what.
Write down exactly what these five statements print, line by line.
System.out.print("A");
System.out.println("B");
System.out.print("C");
System.out.println();
System.out.println("D");Reveal the answer
> javac Mixed.java > java Mixed AB C D
A is printed and the line stays open, so B lands next to it and then the line ends. C is printed and the line stays open; the empty println() ends it. D gets a line of its own. There is no blank line anywhere, because every end the line
came after some text on that line.
Special characters inside text
A string literal starts and ends with a double quote. So how do you print a double quote? If you simply type one, the compiler takes it as the end of the text. And how do you put a line break inside a text, when a string literal is not allowed to run past the end of a line of source code?
The answer is an escape sequence: a backslash followed by one character. The pair is written as two characters in your source but stands for a single special character in the text.
| You write | It stands for |
|---|---|
\n | a new line |
\t | a tab: a jump to the next tab stop |
\" | a double quote that does not end the text |
\\ | one backslash |
public class Postcard {
public static void main(String[] args) {
// \n starts a new line inside a single piece of text.
System.out.println("Dear Sam,\nThe weather is lovely.");
// \t jumps to the next tab stop, which lines text up in columns.
System.out.println("Mon\tsunny");
System.out.println("Friday\train");
// \" puts a double quote inside the text without ending it.
System.out.println("The guide said \"mind the step\" twice.");
// \\ prints one backslash.
System.out.println("Photos are in D:\\holiday\\day1");
}
}> javac Postcard.java > java Postcard Dear Sam, The weather is lovely. Mon sunny Friday rain The guide said "mind the step" twice. Photos are in D:\holiday\day1
Read "Friday\train" carefully. The escape sequence is \t and the word after it is rain. An escape sequence is always exactly two characters, the backslash and the one character after it, even when more letters follow.
The last row of the table follows from the others. Because a backslash announces an escape sequence, a backslash that you actually want printed has to be escaped itself. That matters on Windows, where folder paths are full of them.
A tab does not mean eight spaces
. It means move to the next tab stop
, and terminals normally place a tab stop every eight columns. That is why sunny and rain start in the same column even though Mon and Friday are different lengths.
These two statements differ by one backslash. What does each print?
System.out.println("one\ntwo");
System.out.println("one\\ntwo");Reveal the answer
> javac Slashes.java > java Slashes one two one\ntwo
The first statement prints two lines, because \n is an escape sequence and breaks the text. The second prints the single line one\ntwo. There the compiler reads \\ first: an escaped backslash, which stands for one ordinary backslash. The n after it is then just the letter n.
When it goes wrong: three kinds of failure
Errors are a normal part of programming, and experienced programmers see dozens a day. The two-step picture tells you when a problem can show itself, and knowing when is half of knowing what to do about it.
| Kind | Who reports it | When | What it means |
|---|---|---|---|
| Compile-time error | javac | Step 1 | The source breaks a rule of the language. No .class file is written. |
| Launch error | java | Step 2, before your code starts | The JVM could not find the class you named, or could not find a usable main in it. |
| Run-time error | The JVM | Step 2, while your code runs | A statement asked for something impossible. Everything before it has already happened. |
Reading a compiler error
This file is missing one character.
public class MissingSemicolon {
public static void main(String[] args) {
System.out.println("Almost right")
}
}> javac MissingSemicolon.java
MissingSemicolon.java:3: error: ';' expected
System.out.println("Almost right")
^
1 errorAn error in your code is reported in these four parts. Some errors add a line or two of extra detail, as you will see below.
MissingSemicolon.java:3:gives the file and the line number.error: ';' expectedis the message. It nearly always describes what the compiler expected to find or could not find.- The source line, with a caret (
^) under the exact spot. 1 error, the total.
Look closely at where the caret is: at the very end of the line, after the closing parenthesis. The compiler reports the place where it noticed that something was wrong. Often, as here, that is exactly where the fix belongs. Sometimes it is a long way from it:
public class Unclosed {
public static void main(String[] args) {
System.out.println("Where does the class end?");
}> javac Unclosed.java
Unclosed.java:4: error: reached end of file while parsing
}
^
1 errorReached end of file while parsing
means the compiler arrived at the end of the file still waiting for a closing brace. The class was opened on line 1 and never closed. The compiler cannot know where you meant the brace to go, so it can only point at where the file ran out. This is the practical reason to indent consistently: with every block indented, the brace that is missing shows in the shape of the code.
Messages that need translating
Some messages are accurate but do not say what you would expect. These two are the ones beginners meet most.
public class Typo {
public static void main(String[] args) {
System.out.printn("One letter short");
}
}> javac Typo.java
Typo.java:3: error: cannot find symbol
System.out.printn("One letter short");
^
symbol: method printn(String)
location: variable out of type PrintStream
1 errorCannot find symbol
is one of the most common compiler errors. A symbol is simply a name. The message means: you used a name, and I can find nothing with that name here. The two extra lines say which name (method printn(String)) and where the compiler looked for it. With what you know so far, the cause will be a spelling mistake or wrong capitalisation.
public class WrongCase {
public static void main(String[] args) {
system.out.println("Capital letters matter");
}
}> javac WrongCase.java
WrongCase.java:3: error: package system does not exist
system.out.println("Capital letters matter");
^
1 errorThere is no package involved here; the mistake is a lower-case s. The compiler could find nothing called system, and for a lower-case name followed by a dot its best guess was a package, which is a named group of classes (lesson 12). The guess about what is wrong is poor. The line number and the caret are exactly right. When a message makes no sense, trust the location and look at the code there.
One message looks different from all of these, because it is not about your code at all:
> javac HelloWord.java
error: file not found: HelloWord.java
Usage: javac <options> <source files>
use --help for a list of possible optionsFile not found
means javac could not find a file with the name you typed. Either the name is misspelt or you are in the wrong folder. Use ls to see what is actually there.
A method for any compiler error
- Read only the first error. Later ones are often side effects of the first.
- Go to the line number. Look at that line and at the line before it.
- Read the message literally. What did the compiler expect, or fail to find?
- Fix one thing, save, and compile again.
Launch errors
This file compiles, because nothing in the language forbids a method called Main.
public class WrongMain {
// Capital M: to Java this is a different name from "main".
public static void Main(String[] args) {
System.out.println("Will this run?");
}
}> javac WrongMain.java > java WrongMain Error: Main method not found in class WrongMain, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
The compiler was satisfied and wrote a .class file. The failure came from java, which looked in the class for an entry point and found none. The message even shows you the line it wanted. (Its last line mentions JavaFX, the graphics library you will use in Part 7. Ignore it until then.)
Two more launch errors come from what you type after java:
> javac HelloWorld.java > java HelloWorld.class Error: Could not find or load main class HelloWorld.class Caused by: java.lang.ClassNotFoundException: HelloWorld.class > java helloworld Error: Could not find or load main class helloworld Caused by: java.lang.NoClassDefFoundError: helloworld (wrong name: HelloWorld)
In the first, java was given a file name where it wanted a class name, so it went looking for a class literally called HelloWorld.class. In the second, the capitalisation is wrong. Windows does not distinguish upper and lower case in file names, so the file was found; the JVM then opened it, saw that the class inside is called HelloWorld, and refused: wrong name
.
Run-time errors
public class Crash {
public static void main(String[] args) {
System.out.println("Sharing 10 sweets...");
System.out.println(10 / 0);
System.out.println("Done.");
}
}> javac Crash.java > java Crash Sharing 10 sweets... Exception in thread "main" java.lang.ArithmeticException: / by zero at Crash.main(Crash.java:4)
Follow what happened.
- It compiled. Dividing by zero is perfectly good grammar. The compiler checks that code is well formed; it does not carry out the arithmetic.
- The first statement ran.
Sharing 10 sweets...is on the screen. - Line 4 failed. A whole number cannot be divided by zero, so the JVM stopped the program at that statement and printed a report.
java.lang.ArithmeticException: / by zerosays what went wrong.at Crash.main(Crash.java:4)says where: classCrash, methodmain, fileCrash.java, line 4. Done.was never printed. The statement on line 5 was never reached.
A failure of this kind is called an exception, and the report is a stack trace. Lesson 17 is about exceptions. Until then, read the first line for what and the at line for where.
A file called Party.java contains the following. Which of the three kinds of failure occurs, and what will the message say is wrong?
public class party {
public static void main(String[] args) {
System.out.println("Everyone is invited");
}
}Reveal the answer
> javac Party.java
Party.java:1: error: class party is public, should be declared in a file named party.java
public class party {
^
1 errorA compile-time error. The class is public, so its name must match the file name exactly, and party is not Party. You can fix it either by renaming the class to Party or by renaming the file. Renaming the class is right here, because class names start with a capital letter.
Two shortcuts you will see elsewhere
Recent versions of Java offer shorter ways to write and run small programs. You should recognise both, and know why this course does not rely on them.
Running a source file directly
> java HelloWorld.java Hello, world! > ls -Name HelloWorld.java
This is the one case where java accepts a file name. Given a name ending in .java, it compiles that file in memory and runs it straight away. Both steps still happen, inside one tool, and no .class file is written to disk: the listing shows only the source file. It is handy for a quick experiment. This course uses the two separate commands, because real programs are made of many files and are always compiled first, and because seeing both steps keeps the picture clear.
Compact source files
Since Java 25, a small program can leave out most of the ceremony:
void main() {
IO.println("Hello from a compact source file!");
}> java Modern.java
Hello from a compact source file!There is no class declaration, no public static, no String[] args, and IO.println replaces System.out.println. The compiler wraps the code in a class for you, and this shorter main is one of the forms the JVM has accepted since Java 25. This form exists to make first programs and small scripts less intimidating.
This course uses the full form throughout. Nearly all existing Java code uses it, and programs made of several classes are written in it. You also now know what each word of the full form is for, which is the reason the short form could be invented.
Looking inside a class file
This section is optional. The JDK includes a tool called javap that shows the contents of a .class file in readable form.
> javac HelloWorld.java > javap -c HelloWorld Compiled from "HelloWorld.java" public class HelloWorld { public HelloWorld(); 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, world! 5: invokevirtual #15 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: return }
Look at the four lines under main. That is your one statement, as the JVM sees it: getstatic fetches System.out, ldc loads the text Hello, world!, invokevirtual calls println, and return ends the method. The first block, public HelloWorld(), is something the compiler added that you did not write; lesson 8 explains what it is.
You will never need to read bytecode in order to write Java. The point is only that a .class file is not mysterious. It is your program, translated into smaller steps.
Exercises
Each exercise has a folder waiting in work/m01-how-java-runs/ in your course kit. Compile and run from the terminal, inside the exercise's folder. Open a hint only after a real attempt.
Exercise 1.1 · Business card
Work in work/m01-how-java-runs/ex1-business-card/ in your course kit
Starting from an empty file, write a program Card.java that prints a business card for yourself or for an invented person. Type the whole file yourself, including the first two lines.
- The class is called
Card. - The card has a border drawn with
+,-and|, and every line of the card is the same width. - Inside are at least four lines: a name, a role, an empty line, and a motto.
- The motto is printed with double quotes around it.
Here is the output of one possible card. Yours should have your own content.
+----------------------------+ | Robin Okafor | | Apprentice Java programmer | | | | "Compile early, run often" | +----------------------------+
Hint 1
Each line of the card is one println. Write the top border first and run the program before going further.
Hint 2
A \" takes two characters in your source but prints as one. A line containing two of them looks two characters too long in the editor, and that is correct. Judge the widths from the output, not from the source.
To check it, run python check.py m01 ex1 in your course kit folder.
Exercise 1.2 · Exact output
Work in work/m01-how-java-runs/ex2-escape-sequences/ in your course kit
Write Escapes.java (class Escapes) so that its output is exactly these five lines, character for character. The gap in the third line and the gap in the fourth line are each a single tab character.
She said, "Java is not JavaScript." Folder: C:\courses\java\module01 Name Role Ada Author Tabs are written \t and new lines \n.
One constraint: the third and fourth lines (the ones starting Name and Ada) must both come from a single println statement.
Hint 1
Go through the required output and mark every character that cannot be typed plainly inside a string literal. There are four different kinds.
Hint 2
The last line has to show a backslash followed by the letter t. Look again at the predict box at the end of the section Special characters inside text.
To check it, run python check.py m01 ex2 in your course kit folder.
Exercise 1.3 · Bug hunt
Work in work/m01-how-java-runs/ex3-bug-hunt/ in your course kit
Your folder contains Itinerary.java, which has six mistakes in it, and a file bug-log.md. Get the program to compile and print the four-line itinerary below, following these rules:
- Compile first. Read the first error, fix that one mistake, and compile again. Repeat.
- For every mistake, add an entry to
bug-log.md: the compiler's message, the line it pointed at, what was actually wrong, and what you changed. - Do not rename the file.
public class itinerary {
public static void main(String[] args) {
System.out.println("Day 1: Lisbon")
system.out.println("Day 2: Porto");
System.out.println("Day 3: Coimbra);
System.out.printn("Day 4: Faro");
}Day 1: Lisbon Day 2: Porto Day 3: Coimbra Day 4: Faro
At the end of bug-log.md, answer one question in your own words: the compiler did not report all six mistakes the first time. Why not?
Hint 1
If a message seems to make no sense, trust the line number and the caret, and compare that line character by character with a line that works.
Hint 2
For the final question, reread the Going deeper
box in the section When it goes wrong.
To check it, run python check.py m01 ex3 in your course kit folder.
Exercise 1.4 · Break it on purpose
Work in work/m01-how-java-runs/ex4-break-it-on-purpose/ in your course kit
Your folder contains a working program, Signal.java, and a notes file to fill in, lab-notes.md. Compile and run the program once to confirm it works. Then carry out the seven experiments below. Before each one, write your prediction in the notes file. After each one, undo the change so the next experiment starts from the working program.
- Delete
Signal.class(right-click it in VS Code's file explorer and choose Delete), then runjava Signal. Compile again afterwards to get the file back. - Change
String[] argstoString args. - Remove the word
static. - Change
printlntoPrintlnon one line. - Move one of the
printlnstatements up, so that it sits directly inside the class but outsidemain. - Leave the file alone, compile it, and run
java signal. - Remove the word
publicin front ofclass.
For each experiment record: what you predicted; what happened (compile-time error, launch error, run-time error, or it works); the key line of any message; and one sentence, in your own words, explaining why. Two of the seven hold a surprise. Finish with Signal.java back in its original working state.
Hint
For every experiment ask the same two questions. Does javac still accept the file? If it does, can java still find a class with the right name and an entry point in it?
To check it, run python check.py m01 ex4 in your course kit folder.
Exercise 1.5 · Two classes, one file
Work in work/m01-how-java-runs/ex5-two-classes-one-file/ in your course kit
So far every file has held exactly one class. Find out what happens with two. Write a single file Orchestra.java containing:
- a public class
OrchestrawhosemainprintsThe orchestra tunes up. - below it, a second class
Violin, declared without the wordpublic, whose ownmainprintsA violin plays alone.
Compile the file, list the folder, and try to run each class. Then answer the three questions in answers.md:
- How many
.classfiles did one.javafile produce, and what does that tell you about what a.classfile holds? - Add
publicin front ofclass Violinand compile. Quote the error and explain the rule behind it. (Then takepublicout again.) - To run a compiled program,
javatakes the name of a class and not the name of a file. What did you see in this exercise that proves it?
Hint
The second class goes after the closing brace of the first, not inside it. Each class has its own pair of braces and its own complete main.
To check it, run python check.py m01 ex5 in your course kit folder.
Summary
- Java source code is plain text in a
.javafile.javacchecks it and translates it into bytecode in a.classfile.javastarts a JVM, which runs the bytecode. - The cycle is edit, save, compile, run.
javaruns whatever the last successful compilation produced. - All code lives in a class. A public class must be in a file of the same name. A program starts at its
mainmethod, whose standard form ispublic static void main(String[] args). - Statements end with a semicolon and run from top to bottom.
printlnends the line after printing;printdoes not. - Inside a string literal,
\n,\t,\"and\\stand for a new line, a tab, a double quote and a backslash. - Failures come in three kinds: compile-time (from
javac), launch (fromjava, before your code starts) and run-time (while your code runs). For compiler errors, fix the first one and compile again.
Words introduced in this lesson
| Term | Meaning |
|---|---|
| Source code | The text of a program, as written by a person. |
| Compiler | A tool that checks source code and translates it into another form. Java's is javac. |
| Bytecode | The instructions in a .class file, written for the JVM. |
| JVM | Java Virtual Machine: the program that runs bytecode. |
| JDK | Java Development Kit: the JVM, the standard library and the developer tools. |
| Class | For now, a named container for code. All Java code is inside one. |
| Method | A named block of statements. main is the one where a program starts. |
| Statement | One complete instruction, ending in a semicolon. |
| String literal | Text written directly in the source between double quotes. |
| Argument | A value handed to a method between its parentheses. |
| Escape sequence | A backslash and a character that together stand for one special character. |
| Comment | A note in the source that the compiler ignores. |
| Exception | A failure while the program is running. |
| Stack trace | The report printed for an exception, saying what failed and where. |