SEN1001 · Week 1 · Introduction

How a Java program is compiled and run

From source code to bytecode, from the JVM to the screen: the javac/java chain, the anatomy of a first program and the three kinds of errors. On the midterm it shows up as fill-in-the-blank and short output questions.

source codecompilerjavacbytecodeJVM (Java Virtual Machine)JDKJREclassmain methodstatementescape sequencecommentcompile-time errorruntime errorlogic error

Every program you write in Java goes through two stages: first it is compiled, then it is run. Knowing this distinction earns points in two places: the fill-in-the-blank questions on the midterm (javac, bytecode, JVM) and the “what kind of error is this?” questions. There is also the difference between print and println, which is hidden inside almost every output question.

Golden rules:

  1. .java → javac → .class → java → JVM. Memorize this chain.
  2. The name of a public class = the file name. public class Hello can only live in Hello.java.
  3. The program starts at the main method and lines run from top to bottom in order.
  4. print stays on the line, println moves to the next line.
  5. The compiler only finds syntax and type errors. It can never find a logic error.

From source code to a running program

The computer’s processor does not understand Java code directly. There are two steps in between.

StepWhat happensCommandResult
1. WriteYou write the code into a text file(editor, IDE)Hello.java (source code)
2. CompileThe compiler checks the code and translates itjavac Hello.javaHello.class (bytecode)
3. RunThe JVM loads the bytecode and runs itjava Hellooutput on the screen

Bytecode is not machine code. It is Java’s own intermediate language. That is why the same .class file runs on Windows, macOS and Linux: every system has a JVM (Java Virtual Machine) suited to that system, and it translates the bytecode on the spot. Java’s slogan “write once, run anywhere” comes from this.

Do not mix up the abbreviations:

AbbreviationStands forWhat is inside
JVMJava Virtual Machinethe virtual machine that runs bytecode
JREJava Runtime EnvironmentJVM + standard libraries (enough to run programs)
JDKJava Development KitJRE + javac and development tools (needed to write code)

TIP · running a single file directly. In newer JDKs the command java Hello.java compiles the file in the background and runs it right away. It works fine in practice, but in the exam write the chain as two separate commands: first javac Hello.java, then java Hello.

Anatomy of the first program

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

Line by line:

  • public class Hello defines a class. In Java all code lives inside a class. By convention a class name starts with a capital letter. Because it is public, the file name has to be Hello.java.
  • { and } open and close a block. Every opening curly brace must have a closing one.
  • public static void main(String[] args) is the program’s entry point. When the JVM starts the program, it looks for this method. It is written exactly like this, word for word. Memorize it for now; static and void will make sense in week 5.
  • System.out.println(...) writes what is inside the parentheses to the screen. This line is a statement and it has a ; at the end. In Java every statement ends with a semicolon.

Java is case-sensitive. If you write system.out.println, it does not compile; the compiler says package system does not exist. Main and main are different names.

System.out.print("Bir ");
System.out.print("iki ");
System.out.println("uc");
System.out.println("dort");
Bir iki uc
dort

print writes the text and leaves the cursor where it is. println writes the text and ends the line, so the next output starts on the next line. print adds no spaces; if you want spaces between words, you have to put them inside the text.

To put a special character inside a String, you use an escape sequence. All of them start with a backslash \:

Escape sequenceMeaning
\nnewline
\ttab (horizontal tab)
\"double quote character
\\a single backslash
System.out.println("Ad\tSoyad");
System.out.println("Satir1\nSatir2");
System.out.println("Hoca \"tamam\" dedi");
System.out.println("C:\\Users\\deniz");
Ad	Soyad
Satir1
Satir2
Hoca "tamam" dedi
C:\Users\deniz

PITFALL · single backslash. "C:\Users" does not compile: \U is not a valid escape sequence, and the compiler says illegal escape character. When you write a file path, double every backslash.

Comments

A comment is an explanation that the compiler ignores completely. There are two kinds:

// System.out.println("gizli");      single-line comment
System.out.println("gorunur"); /* System.out.println("bu da gizli"); */
gorunur

// turns everything up to the end of the line into a comment. Everything between /* ... */ is a comment, even if it spans several lines. In a “what is printed?” question, skip the println lines inside comments; treat them as if they were never written.

The three kinds of errors

The classic short exam question: “Is this error compile-time, runtime or logic?” The way to tell them apart is to look at when the error shows up.

Compile-time error

javac finds it while translating the code. The program is never produced, so it never runs. Syntax errors and type errors belong here.

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

Other common examples: an undefined variable (cannot find symbol), a wrong file name (class Greet is public, should be declared in a file named Greet.java), assigning a double to an int (possible lossy conversion), an unclosed curly brace.

Runtime error

The code compiles and the program starts, but while running it crashes on a line that asks for something impossible. Java calls this an exception.

System.out.println("start");
System.out.println(10 / 0);
System.out.println("end");
start
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Div.main(Div.java:4)

The lines before the crash have run (start was printed). Nothing after the crashing line runs (no end). Other examples you will see later: going outside an array (ArrayIndexOutOfBoundsException), typing a letter instead of a number into a Scanner (InputMismatchException).

Logic error

The program compiles, runs and does not crash, but gives a wrong result. This is the sneakiest kind, because nobody warns you.

int x = 4, y = 6;
double avg = x + y / 2;   // intent: the average
System.out.println(avg);
7.0

The average should have been 5.0. The division was done before the addition: 4 + 6 / 2 = 4 + 3. The fix is (x + y) / 2.0. You can only find this kind of error by testing by hand (comparing the result with an example whose answer you know).

Error typeWhen?Does the program run?Example
Compile-timeDuring javacNo, no .class is producedmissing ;, totl typo
RuntimeWhile runningIt starts, crashes on the faulty line10 / 0
LogicNever reports an “error”Yes, to the endwrong formula

Worked example: reading an error message

javac’s message always has the same pattern: FileName.java:line: error: description, with the faulty line and a ^ marker underneath. The program below has two errors:

public class Typo {
    public static void main(String[] args) {
        int total = 5;
        System.out.println(totl);
        system.out.println("x");
    }
}
Typo.java:4: error: cannot find symbol
        System.out.println(totl);
                           ^
  symbol:   variable totl
  location: class Typo
Typo.java:5: error: package system does not exist
        system.out.println("x");
              ^
2 errors

Reading order: first go to the line number (4), look at the word the ^ marker points to (totl), then read the description (cannot find symbol: nothing with this name is defined). The fix is total. The second error is the lowercase system; because Java is case-sensitive, it took that for a package name. Messages are sometimes indirect, but the line number almost always points to the right place. If there are several errors, start with the topmost one: fixing the first error often makes the ones below it disappear too.

Common mistakes

Wrong ideaThe truth
You run it with java Hello.classjava Hello, no extension
javac runs the programjavac only compiles; the JVM (java) runs it
Bytecode is machine codeIt is an intermediate language, and the JVM translates it on every system
The file name does not matterThe public class name and the file name must match exactly
print("a"); print("b"); → a bab, print adds no space
\\ prints two backslashesIt prints a single backslash
A println inside a comment also runsComments are ignored completely
The compiler finds every errorIt cannot find logic errors
Exception = compile-time errorAn exception happens while running: it is a runtime error

Test yourself

Exam-style questions. Solve them on paper first, then reveal the answer.

Question 1easy

What is printed?

System.out.print("Java");
System.out.print("Code");
System.out.println("!");
Show answer
JavaCode!

print writes and leaves the cursor on the same line. Two print calls side by side write next to each other, with no space added. The final println writes the exclamation mark and ends the line.

Question 2easy

What is printed?

System.out.println("A");
System.out.print("B");
System.out.println();
System.out.println("C");
Show answer
A
B
C

println("A") writes and moves to the next line. print("B") writes and stays on the line. The empty println() only ends the line. Then C goes on a new line. Three lines in total, no blank line.

Question 3easy

What is printed?

System.out.println("1\t2\n3");
Show answer
1 2
3

\t is a tab character and \n is the newline character. First 1, a tab and 2 are written; then \n moves to the next line and 3 is written.

Question 4easy

What is printed?

System.out.println("She said \"hi\"");
Show answer
She said "hi"

The \" escape sequence puts a double quote inside the String. The backslash is not printed, only the quote appears.

Question 5medium

What is printed?

System.out.println("C:\\new\\test");
Show answer
C:\new\test

In the code \\ looks like two characters but prints a single backslash. So n and t are ordinary letters here, and no newline or tab is produced. If you had written a single backslash (\n), it really would be a newline.

Question 6easy

What is printed?

System.out.print("x");
// System.out.print("y");
System.out.print("z"); /* System.out.print("w"); */
System.out.println();
Show answer
xz

// turns the rest of the line into a comment, and /* ... */ turns everything in between into a comment. The compiler ignores comments completely, so y and w never run.

Question 7medium

What is printed?

System.out.println("Line 1");
System.out.print("Line 2\n");
System.out.print("Line 3");
System.out.println(" end");
Show answer
Line 1
Line 2
Line 3 end

print("Line 2\n") ends with \n, so it behaves like println. Line 3 stays on the line, and the next println(" end") appends the text with a leading space to the same line.

Question 8easy

Fill in the blanks: A file Hello.java is compiled with the command ____, which produces the file ____ containing bytecode. The bytecode is executed by the ____ using the command java Hello.

Show answer
javac Hello.java · Hello.class · JVM

The chain: source code (.java) → javac compiler → bytecode (.class) → the java command starts the JVM and runs the bytecode. You do not write the .class extension when running: java Hello.

Question 9medium

A file named Main.java contains public class Greet { ... }. What happens when you compile it?

  1. It compiles and runs normally
  2. Compile-time error: class Greet is public, should be declared in a file named Greet.java
  3. Runtime error when the program starts
  4. It compiles but prints nothing
Show answer
b

The name of a public class must match the file name exactly (including upper/lower case). javac catches this at compile time: class Greet is public, should be declared in a file named Greet.java.

Question 10medium

Classify each error as compile-time, runtime or logic error: (a) missing ; at the end of a statement, (b) System.out.println(10 / 0);, (c) writing System.out.println(totl); when the variable is named total, (d) a program that should print the area of a rectangle but prints the perimeter.

Show answer
(a) compile-time · (b) runtime · (c) compile-time · (d) logic

(a) ';' expected, the program never compiles. (b) It compiles, then crashes while running with ArithmeticException: / by zero. (c) cannot find symbol, the compiler catches the name it does not recognize. (d) The program runs and does not crash but gives a wrong result: a logic error. The compiler can never find this.

Question 11hard

What is printed? Is this a compile-time, runtime or logic error?

int x = 4, y = 6;
double avg = x + y / 2;
System.out.println(avg);
Show answer
7.0 (logic error)

/ is done before the addition: y / 2 = 3, then 4 + 3 = 7, which becomes 7.0 when assigned to a double. The average should have been 5.0. Because the program compiles and runs, this is a logic error. The correct version is (x + y) / 2.0.

Question 12medium

The program below prints start and then crashes. What kind of error is it, and does end get printed?

System.out.println("start");
System.out.println(10 / 0);
System.out.println("end");
Show answer
Runtime error (ArithmeticException); end is NOT printed

The code compiles. While running, the first line prints start; on the second line, dividing an integer by zero throws ArithmeticException: / by zero and the program stops there. Lines after the crash point do not run.

Verification: All outputs were run with JDK 26 (verify/SEN1001/W01.java). The compile error messages were obtained by compiling the files under verify/SEN1001/err/ with javac.

Review card

Hello.java --javac--> Hello.class (bytecode) --java--> JVM runs it javac Hello.java compile java Hello run (no .class) JDK = javac + tools + JRE JRE = JVM + libraries public class Name = file name (Hello.java), upper/lower case included The program starts at main: public static void main(String[] args) Every statement ends with ; . { } opens/closes a block. Java is case-sensitive print = write, stay on line println = write + next line println() = just end the line \n newline \t tab \" quote \\ backslash // single-line comment /* ... */ multi-line comment (does not run) Compile-time: missing ;, wrong name, type mismatch → never runs Runtime: compiles, crashes while running (10/0 → ArithmeticException) Logic: runs, no crash, WRONG result (compiler cannot find it)