Chapter 5: Getting Started with Java
Introduction
Learning Outcomes
Describe a program as data plus operations.
Relate source code, bytecode and the JVM.
Write, compile and run a Java file.
Tell syntax, runtime and logic errors apart.
Basics
What Is a Program?
- A set of instructions the computer executes to carry out a task.
- It takes input, processes data, keeps state (values in memory) and produces output.
- Its behavior is set by the language's rules and the algorithm.
- Example: the average of two grades → input 70, 90; output 80.
Basics
Aspects of a Programming Language
- Syntax defines the valid form; semantics defines what happens when it runs.
- The type system restricts operations; the execution model defines how memory and instructions behave.
- The compiler checks syntax and types before the program runs.
Source Code
A Plain-Text Source File
- A .java file is plain text; Notepad, VS Code or an IDE can open it.
- Version control systems can track line-by-line changes.
- Character encoding (UTF-8), line endings and the file name must be consistent: non-ASCII characters break under the wrong encoding.
Source Code
Programming Tools
Writing source code.
Projects, completion, compiling and debugging.
Compiling source code to bytecode.
Running a class on the JVM.
Generating API documentation.
Change history.
Java
The Birth of Java and Its Versions
- James Gosling and his team began the work at Sun Microsystems in 1991; the language was released as Java in 1995. Oracle has developed it since 2010, and the open-source code lives in OpenJDK.
- The design goal: write once, run anywhere. The same bytecode runs on every platform's JVM.
- Other features: object-oriented, strong type checking, automatic memory management (garbage collection) and a large class library.
- Since 2018 a new release appears every six months; LTS (long-term support) releases get updates for years, so companies and courses prefer them.
Java
Where Is Java Used?
The back end of banking, e-commerce and government systems; the Spring and Jakarta EE frameworks.
Apps are written in Java or Kotlin; the bytecode is converted into a form for the phone's Android Runtime (ART).
Data processing tools such as Hadoop and Kafka run on the JVM.
IDEs such as IntelliJ IDEA, Eclipse and NetBeans are themselves written in Java.
Small programs on SIM and bank cards run with Java Card.
Minecraft: Java Edition; desktop games and simulations.
The JVM runs not only Java but other languages that compile to the same bytecode, such as Kotlin, Scala and Groovy.
Java
JDK, JRE and JVM
- The JVM (Java Virtual Machine) is the virtual machine that executes bytecode.
- JRE = JVM + class library: what you need to run a program.
- JDK = JRE + development tools (javac, jar, javadoc…). Developers install the JDK.
- Since Java 11, Oracle ships no separate JRE; even someone who only runs programs installs a JDK (some vendors still offer a JRE).
Java
The First Java Program
accessible from anywhere
called without creating an object
returns no value
command-line arguments
Java
The Signature of main
| Written (all compile) | 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, … |
- To the compiler, each is an ordinary method, so the error shows up at launch, not at compile time. The JVM looks for the entry point by name, parameter and return type.
- The parameter name is free (
String[] a);String args[]is also valid.mainis lowercase: Java is case-sensitive. - The messages come from JDK 21. From Java 25 on, a
mainthat is not public or not static can also be launched; this course uses the classic signature.
Java · Run the code step by step
Code Trace: Hello
The command java Hello starts the JVM, which loads the Hello class (Hello.class) into memory.
The JVM calls the main method: a main frame is pushed on the stack. No command-line arguments were given, so args is empty.
The statement runs: the text "Hello" is passed to System.out.println.
println prints the text and adds a line break: the cursor moves down a line. The method ends and control returns to main.
We reach the } of the main block: main ends and its frame is popped.
No code is left to run: the JVM shuts down and the program terminates. One statement ran and printed one line.
public class Hello { public static void main(String[] args) { System.out.println("Hello"); } }
Java · Run the code step by step
Code Trace: Command-Line Arguments
Words written after the class name are command-line arguments. The JVM puts them in a String array and passes it to main.
args.length is the number of arguments: 2.
The first argument is in args[0] (indices start at 0): Hi Ali.
args[1] → Veli. main ends and the program terminates.
Second run: the same .class, this time with one argument. The code did not change, so no recompiling is needed.
args.length = 1.
args[0] exists: Hi Ali.
There is no args[1]: the JVM throws ArrayIndexOutOfBoundsException and the program stops. The compiler could not have known; the error arose at run time and depends on the input.
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]); } }
Java · Run the code step by step
Code Trace: print and println
The JVM calls main; the console is still empty and the cursor sits at the start of line 1.
print writes "Hello " but adds no line break: the cursor stays on the same line, right after the space.
println writes "World" and adds a line break: the next output starts on the line below.
println writes "Java" and adds a line break: the next output starts on the line below.
main ends; the console has 2 lines: there were 3 calls, but only println ends a line.
public class Greeting { public static void main(String[] args) { System.out.print("Hello "); System.out.println("World"); System.out.println("Java"); } }
Java
Escape Sequences
| Sequence | Meaning | Example | Output |
|---|---|---|---|
\n | new line | "A\nB" | A, then B on the next line |
\t | tab | "Name\tGrade" | Name Grade |
\" | double quote | "\"Java\"" | "Java" |
\\ | backslash | "C:\\docs" | C:\docs |
\' | single quote (inside a char) | '\'' | ' |
- Characters that cannot be typed in a string, or that have a special meaning, are written as sequences starting with
\. - A
"inside the quotes ends the text; if it belongs to the text, write\".
Java · Run the code step by step
Code Trace: Escape Sequences
main starts; the console is empty.
\t moves the cursor to the next tab stop (column 9).
Thanks to the tab, 85 lines up under the Grade heading: a simple table.
\" writes a double quote without ending the text.
One print produced two lines: \n is the line-break character; println adds a line break too (\r\n on Windows).
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"); } }
Java
Escape Sequence Pitfalls
| Statement | Result |
|---|---|
System.out.println("C:\data"); | compile error: illegal escape character; there is no \d escape sequence |
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: inside a string, a single quote needs no escape |
System.out.println("Caf\u00E9"); | Café: \u plus four hex digits gives a Unicode character |
The most common mistake in Windows file paths is a single backslash; Java file operations also accept the form "C:/data".
Java
String Concatenation: + Does Two Jobs
- Between two numbers,
+adds; if either operand is a String, it concatenates: the number is converted to text and appended. - Operators of equal precedence go left to right;
*and/always come before+.
| Expression | Output | Why? |
|---|---|---|
40 + 45 + " points" | 85 points | the two ints are added first, then the text is appended |
"Score: " + 40 + 45 | Score: 4045 | the leftmost is a String; both numbers are appended as text |
"Score: " + (40 + 45) | Score: 85 | the parentheses are evaluated first |
"Avg: " + 85 / 2 | Avg: 42 | / first; dividing two ints drops the fraction |
Source Code
Structure of a Java File
package school; import java.util.Scanner; public class Program { public static void main(String[] args) { System.out.println("Hello"); } }
- package and import declarations come before the class; the public class name matches the file name.
package school;→ the file lives in theschool/folder; run it withjava school.Program.
Running
The Build Pipeline Step by Step
1. Write: save the source code as Hello.java. The file name must match the public class name.
2. Compile: javac (the compiler in the JDK) checks the whole file before anything runs.
3. Bytecode: if compilation succeeds, Hello.class appears in the same folder. This file is identical on Windows, Linux and macOS.
4. Run: java Hello starts the JVM. Give the class name; do not write the .class extension.
5. Output: Hello appears on the console. After any change, you must compile again.
If there is an error: javac reports it with a line number and produces no .class. Fix compile errors first.
Running
Installing the JDK and Commands
| Command | What does it do? |
|---|---|
java -version | shows the installed Java version |
javac -version | shows the compiler version (javac comes only with the JDK) |
javac Hello.java | compiles: produces Hello.class |
java Hello | runs it (no extension) |
java Hello.java | Java 11+: compile and run in one step, leaving no .class |
If the commands are not found, add the JDK's bin folder to the PATH environment variable. JAVA_HOME points to the JDK folder; tools rely on it.
Compile with javac -encoding UTF-8 Hello.java. If letters come out garbled, run chcp 65001 in the console first.
Running · Run the commands step by step
Console Session: Compile, Edit, Recompile
When compilation succeeds, javac prints nothing; Hello.class quietly appears.
The JVM loads Hello.class and runs it.
The source was edited and saved, but the .class file does not update itself.
The output is still Hello: the java command ignores the source and runs only the bytecode in the .class.
Recompiling refreshes the .class file.
The change is now visible: Hi.
java was given a file name: the JVM looks for a class named "Hello.class" and cannot find it. Leave out the extension.
> javac Hello.java
> java Hello
(in the editor "Hello" → "Hi", save)
> java Hello
> javac Hello.java
> java Hello
> java Hello.classRunning
Working in an IDE
- The ▶ Run button does the compile and run steps behind the scenes; a changed file is recompiled first, so there is no stale .class problem.
- Compile errors are underlined in red as you type; hovering shows the compiler's message.
- IDEs offer code completion, auto-indentation, renaming and a debugger with breakpoints. Common Java IDEs: IntelliJ IDEA, Eclipse, NetBeans, and VS Code with Java extensions.
- An IDE makes life easier, but knowing what happens behind the scenes lets you understand error messages where there is no IDE (servers, remote sessions).
Running
Bytecode and the JVM
- The compiler produces bytecode instead of CPU-specific machine code.
- Each platform's own JVM interprets the bytecode and JIT-compiles hot parts into that CPU's machine code.
- Class loading, verification and memory management (garbage collection) are part of the runtime.
Running
Inside Bytecode: javap
> javap -c Hello ... public static void main(java.lang.String[]); Code: 0: getstatic // System.out 3: ldc // "Hello" 5: invokevirtual // println 8: return
javap also prints constant-pool references; they are trimmed here.
javap -cships with the JDK; it lists the instructions in a .class file in readable form.- getstatic pushes the System.out object and ldc pushes the constant "Hello" onto the operand stack.
- invokevirtual pops both and calls println; return ends main.
- Each instruction's opcode is one byte, hence the name "bytecode". The numbers on the left are byte offsets.
Running · Run the code step by step
Code Trace: The JVM Executes Bytecode
The four source lines compiled to the 12 instructions javap -c shows. iconst_3 pushes 3; istore_1 pops it into local variable 1 (a).
The same pair for b: 4 onto the stack, then into slot 2.
iload_1 copies a's value onto the stack: [3].
iload_2: [3, 4]. The two values to add are on top of the stack.
iadd pops the top two values, adds them and pushes the result: [7].
istore_3: 7 is popped and stored in c. The stack is empty again.
getstatic pushes a reference to the System.out object.
iload_3: the value to print (7) is on the stack too.
invokevirtual pops both values and calls println(int): 7 is printed on the console.
return: main ends and its frame is removed. The local variables and the operand stack disappear with the frame.
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: return
Language Structure
Basic Programming Elements
- The compiler first splits the code into tokens: keywords, identifiers, literals, operators, separators.
- Java is case-sensitive:
numandNumare different names. - Most statements end with a semicolon; blocks are enclosed in braces.
Language Structure
Whitespace, Indentation and Braces
public class One { public static void main(String[] args) { System.out.println("Hello"); } }
public class One { public static void main(String[] args) { System.out.println("Hello"); } }
- Both programs compile to the same bytecode: to the compiler, spaces, tabs and line breaks only separate tokens.
x=1;andx = 1;are the same, butpublicclassis a single word. - Indentation shows the reader how blocks nest: each new block starts 4 spaces in, and the closing
}lines up with the line that opened it. - By Java convention the opening
{goes at the end of the line. Spaces inside a string are part of the text:"Hello "and"Hello"differ.
Language Structure
Expressions and Statements
- An expression produces a value:
2 + 3→ 5,num > 0→ true. - A statement performs an action:
total = 5;orSystem.out.println(total); - A block groups the statements inside braces into one unit.
- A statement can contain one or more expressions.
Language Structure · Run the code step by step
Expression, Statement and Block Step by Step
An int box is set aside for price and 120 is stored in it.
The qty box is created: 3.
The expression on the right is evaluated first: price * qty → 120 * 3 → 360.
The value is assigned to the total box: total = 360.
Condition expression: total > 300 → 360 > 300 → true. Since it is true, we enter the block.
The statement in the block runs: Discount is printed.
The block ends. With qty = 2, total would be 240, the condition false, and the block would never run.
int price = 120; // declaration int qty = 3; // declaration int total = price * qty; // expression + assignment if (total > 300) { // condition + block System.out.println("Discount"); }
Source Code
Comments
//starts a comment that runs to the end of the line./* ... */spans several lines./** ... */is a Javadoc (API documentation) comment.- The compiler skips comments; they never reach the bytecode.
- A comment should explain why, not repeat what the code does.
/** 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"); } }
Source Code
Comment Pitfalls
| Code | What happens? |
|---|---|
/* outer /* inner */ rest */ | compile error: illegal start of expression. The comment ends at the first */, so rest */ is read as code. |
System.out.println("a // b"); | a // b is printed: a // inside quotes is part of the text, not a comment. |
// System.out.println(x); | the line is temporarily disabled; in IDEs, Ctrl+/ comments out the selected lines this way. |
double price = net * 1.20; // VAT 18% | compiles, but the comment contradicts the code: an outdated comment misleads the reader. |
- To disable a section that contains
/* */, commenting out each line with//is safer. - When a comment and the code disagree, the compiler runs the code; the code is always the truth.
Basics
Kinds of Errors
| Error | When? | Example |
|---|---|---|
| Syntax | At compile time | Missing semicolon |
| Type | At compile time | Assigning text to a number |
| Runtime | While the program runs | Division by zero |
| Logic | The program runs but the result is wrong | Wrong condition |
Basics · Step by step
Kinds of Errors by Example
Syntax error
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 points to where the rule was broken, with a line number; no .class is produced. Fix: add ; at the end of the line.
Type error
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 errorA String cannot go into an int box. Types are checked at compile time. Fix: int num = 42;
Runtime error
public class Bug3 { public static void main(String[] args) { int a = 10, b = 0; System.out.println(a / b); } }
Exception in thread "main" java.lang.ArithmeticException: / by zero at Bug3.main(Bug3.java:4)
The code compiles, but at run time an integer is divided by zero: the JVM throws an exception and the program stops.
Logic error
public class Bug4 { public static void main(String[] args) { int a = 70, b = 90; System.out.println(a + b / 2); } }
115
No error message, but the result is wrong: 80 was expected. / goes first: 70 + 45. Fix: (a + b) / 2.
Basics · Real javac / java messages
Common Compile Errors
| Error | Actual message | Fix |
|---|---|---|
| Missing semicolon | Hello.java:3: error: ';' expected | add ; at the end of the previous statement |
| Misspelled method ( System.out.printn) | error: cannot find symbolsymbol: method printn(String)location: variable out of type PrintStream | rename it to println |
| Lowercase ( system.out) | error: package system does not exist | System starts with a capital S |
| Name and file don't match | error: class Greeting is public, should be declared in a file named Greeting.java | file name = public class name |
| Wrong launch ( java Greeting) | Error: Could not find or load main class Greeting | no .class, or wrong name/location; don't type the extension |
The messages come from JDK 21; depending on the version, extra lines may appear (e.g. Caused by: ClassNotFoundException). Always start with the first error.
Basics
Reading an Error Message
- A javac message has the form file:line: error: description; below it come the offending source line and a ^ marking the column where the error was noticed.
- The ^ marks not the error itself but where the compiler noticed it: a missing
;is reported at the end of the line, a missing}at the end of the file (reached end of file while parsing). - For a runtime error, the first line gives the exception's type and detail; the stack trace lines starting with at give the method and line where it happened.
Basics · Fix the code step by step
Code Trace: Fixing Errors in Order
First compile: only one error is reported. While the syntax is broken, javac does not move on to semantic checks; the mistake on line 4 is not visible yet.
Fix the spot the message points to: add ; at the end of the line and save the file.
Recompile: the syntax is now correct, the semantic check runs and cannot find a method named printn.
The symbol: line names what was not found: fix the method name to println.
The third compile quietly succeeds, Score.class appears and the program runs. The error count may not drop after a fix; it can even grow. Always start with the first error.
public class Score { public static void main(String[] args) { int score = 85 System.out.printn("Score: " + score); } }
Design
A Program Is a Recipe
- For each step, state its precondition and the value it produces.
- Large recipes split into subtasks (in Java these will later become methods).
Design
Before Coding
- Write a sample input and the expected output.
- Break the solution into steps in plain language or pseudocode.
- Decide on the boundary cases and the error behavior.
- Then turn the steps into Java constructs.
| Sample input | Expected output | Why? |
|---|---|---|
| 70, 90 | 80 | typical case |
| 0, 0 | 0 | lower bound |
| 101, 50 | error message | invalid input |
Summary
Chapter Summary
- A program is a set of instructions the computer executes to carry out a task.
- A Java source file is compiled to bytecode with javac and runs on the JVM.
- The public class name matches the file name; main is the program's entry point.
- Expressions produce values, statements perform actions, blocks group statements.
- Before coding, settle the sample input, the expected output and the boundary cases.
Summary
Review Questions
- How are the JDK, bytecode and the JVM related?
- Which commands compile and run Hello.java?
- What is the role of the main method?
- What is the difference between an expression and a statement?
- How do you tell a syntax error from a logic error?
- If the source is changed but not recompiled, what does the
javacommand run? - Why does
"Score: " + 40 + 45giveScore: 4045? - How do command-line arguments reach the program?
Summary
Exercises
- Write an
AboutMeprogram that prints your name, department and student number on three separate lines; compile and run it. - Produce the same output with a single
printlnand\n. - Print a three-line course–credit table using
\t. - Delete the
;inSystem.out.println("Hello")and compile; interpret the line number and the ^ in the error message. - Name the class
Helloand the filehello.java, then compile. What happens, and why? - Predict the output of
System.out.println(5 + 3);andSystem.out.println("5 + 3");; run them to check.
Summary
References
- Deitel and Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
- 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.
- Sedgewick and Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 1.1 Your First Program.
- Downey and Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online edition).