Chapter 5: Getting Started with Java

Computer Fundamentals and Introduction to Programming
ProgramsToolsFirst programCompilingErrors
Sercan KÜLCÜ · Giresun University

Introduction

Learning Outcomes

Programs

Describe a program as data plus operations.

Java

Relate source code, bytecode and the JVM.

First program

Write, compile and run a Java file.

Errors

Tell syntax, runtime and logic errors apart.

Basics

What Is a Program?

Input70, 90Programs1. read grades2. add them3. divide by 24. print resultmemory (state)total = 160Output80
  • 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

inttotal=price * qty;Type systemint × int → intwhat a value can doExecution modela total box in memorythe value is kept thereSemanticsmultiply, store in the boxwhat happens when it runs?Syntaxa statement ends with ;the valid written form
  • 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

Hello.javapublic class Hello {public static void...}plain text:no formattingany editorcan open itp70u75b62l6Ci69c63ASCII characters take 1 byte in UTF-8 (hex); letters like ç, ğ, ş take 2
  • 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

Editor

Writing source code.

IDE

Projects, completion, compiling and debugging.

javac

Compiling source code to bytecode.

java

Running a class on the JVM.

Javadoc

Generating API documentation.

Version control

Change history.

The tools along a Java program's journeyEditor / IDEHello.javajavacHello.classjava(JVM)outputHellojavadoc → HTML API docsVersion control: history v1 → v2 → v3

Java

The Birth of Java and Its Versions

1991Green project(first named Oak)1995Java 1.0Sun2006Open sourceOpenJDK2010Oraclebought Sun2014Java 8LTS2018Java 11 LTS6-month cadence2021Java 17LTS2023Java 21LTS2025Java 25LTS
  • 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?

Enterprise servers

The back end 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 into a form for the phone's Android Runtime (ART).

Big data

Data processing tools such as Hadoop and Kafka run on the JVM.

Developer tools

IDEs such as IntelliJ IDEA, Eclipse and NetBeans are themselves written in Java.

Smart cards

Small programs on SIM and bank cards run with Java Card.

Games

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

JDK — development kitjavacjavajarjavadocjshellJRE — runtime environmentJava class libraryjava.lang · java.util · java.io …JVM — virtual machineclass loaderbytecode verifierinterpreter + JITgarbage collector
  • 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

public class Hello {public static void main(String[] args) {System.out.println("Hello");}}class declarationname = file name: Hello.javamain methodthe program's entry pointstatementprint to the console; ends with ;} end of main block} end of class block
public

accessible from anywhere

static

called without creating an object

void

returns no value

String[] args

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. main is lowercase: Java is case-sensitive.
  • The messages come from JDK 21. From Java 25 on, a main that 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

Hello.classbytecodeJVMruns main()System.outoutput streamConsole▌

The command java Hello starts the JVM, which loads the Hello class (Hello.class) into memory.

Hello.classbytecodeJVMruns main()System.outoutput streamConsole▌

The JVM calls the main method: a main frame is pushed on the stack. No command-line arguments were given, so args is empty.

Hello.classbytecodeJVMruns main()System.outoutput streamConsole▌

The statement runs: the text "Hello" is passed to System.out.println.

Hello.classbytecodeJVMruns main()System.outoutput streamConsoleHello▌

println prints the text and adds a line break: the cursor moves down a line. The method ends and control returns to main.

Hello.classbytecodeJVMruns main()System.outoutput streamConsoleHello▌

We reach the } of the main block: main ends and its frame is popped.

Hello.classbytecodeJVMruns main()System.outoutput streamConsoleHello▌

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

> java Greet Ali Veliargs"Ali"args[0]"Veli"args[1]args.length = 2

Words written after the class name are command-line arguments. The JVM puts them in a String array and passes it to main.

> java Greet Ali Veliargs"Ali"args[0]"Veli"args[1]args.length = 2

args.length is the number of arguments: 2.

> java Greet Ali Veliargs"Ali"args[0]"Veli"args[1]args.length = 2

The first argument is in args[0] (indices start at 0): Hi Ali.

> java Greet Ali Veliargs"Ali"args[0]"Veli"args[1]args.length = 2

args[1] → Veli. main ends and the program terminates.

> java Greet Aliargs"Ali"args[0]—args[1]args.length = 1

Second run: the same .class, this time with one argument. The code did not change, so no recompiling is needed.

> java Greet Aliargs"Ali"args[0]—args[1]args.length = 1

args.length = 1.

> java Greet Aliargs"Ali"args[0]—args[1]args.length = 1

args[0] exists: Hi Ali.

> java Greet Aliargs"Ali"args[0]missing!args[1]args.length = 1

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

Console▌cursor: ▌line 1, col 1

The JVM calls main; the console is still empty and the cursor sits at the start of line 1.

ConsoleHello ▌cursor: ▌line 1, col 7

print writes "Hello " but adds no line break: the cursor stays on the same line, right after the space.

ConsoleHello World▌cursor: ▌line 2, col 1

println writes "World" and adds a line break: the next output starts on the line below.

ConsoleHello WorldJava▌cursor: ▌line 3, col 1

println writes "Java" and adds a line break: the next output starts on the line below.

ConsoleHello WorldJava▌cursor: ▌line 3, col 1

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

SequenceMeaningExampleOutput
\nnew line"A\nB"A, then B on the next line
\ttab"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

Console▌

main starts; the console is empty.

ConsoleName    Grade▌

\t moves the cursor to the next tab stop (column 9).

ConsoleName    GradeAli     85▌

Thanks to the tab, 85 lines up under the Grade heading: a simple table.

ConsoleName    GradeAli     85"Java" rocks▌

\" writes a double quote without ending the text.

Console"Java" rocksLine 1Line 2▌

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

in source: "C:\new"C:\nnew lineewon screen:C:ew
StatementResult
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 +.
System.out.println("Score: " + 40 + 45);"Score: " + 401"Score: 40" + 452"Score: 4045"left to right
ExpressionOutputWhy?
40 + 45 + " points"85 pointsthe two ints are added first, then the text is appended
"Score: " + 40 + 45Score: 4045the leftmost is a String; both numbers are appended as text
"Score: " + (40 + 45)Score: 85the parentheses are evaluated first
"Avg: " + 85 / 2Avg: 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");
    }
}
school/Program.java1 · package school;2 · import …;3 · class Program { … }main( … ) { … }statement;statement;
  • package and import declarations come before the class; the public class name matches the file name.
  • package school; → the file lives in the school/ folder; run it with java school.Program.

Running

The Build Pipeline Step by Step

Hello.javasource codejavaccompilerHello.classbytecodeJVMjava commandConsoleoutputPlain text written in the editor:public class Hello { … println("Hello"); … }C:\code> (file saved: Hello.java)

1. Write: save the source code as Hello.java. The file name must match the public class name.

Hello.javasource codejavaccompilerHello.classbytecodeJVMjava commandConsoleoutputjavac reads the source code and checks syntax and types.If there are no errors, it produces bytecode.C:\code> javac Hello.java

2. Compile: javac (the compiler in the JDK) checks the whole file before anything runs.

Hello.javasource codejavaccompilerHello.classbytecodeJVMjava commandConsoleoutputCPU-independent intermediate code; the file starts with the bytes CA FE BA BE.Hello.class  (binary, not plain text)C:\code> dir   →   Hello.class

3. Bytecode: if compilation succeeds, Hello.class appears in the same folder. This file is identical on Windows, Linux and macOS.

Hello.javasource codejavaccompilerHello.classbytecodeJVMjava commandConsoleoutputThe class loader brings the .class file into memory,the verifier checks the bytecode, then main is called.C:\code> java Hello

4. Run: java Hello starts the JVM. Give the class name; do not write the .class extension.

Hello.javasource codejavaccompilerHello.classbytecodeJVMjava commandConsoleoutputThe JVM interprets the bytecode; hot parts are JIT-compiledto machine code. println writes to the console.Hello

5. Output: Hello appears on the console. After any change, you must compile again.

Hello.javasource codejavaccompilerHello.classbytecodeJVMjava commandConsoleoutput✗Hello.java:3: error: ';' expectedCompile error: no .class is produced, so there is nothing to run.C:\code> javac Hello.java   (1 error)

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

CommandWhat does it do?
java -versionshows the installed Java version
javac -versionshows the compiler version (javac comes only with the JDK)
javac Hello.javacompiles: produces Hello.class
java Helloruns it (no extension)
java Hello.javaJava 11+: compile and run in one step, leaving no .class
PATH and JAVA_HOME

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.

Non-ASCII text on the Windows console

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

working folderHello.javaprintln("Hello")Hello.classbytecode: prints "Hello"currentjavac made a new file

When compilation succeeds, javac prints nothing; Hello.class quietly appears.

working folderHello.javaprintln("Hello")Hello.classbytecode: prints "Hello"current

The JVM loads Hello.class and runs it.

working folderHello.javaprintln("Hi")Hello.classbytecode: prints "Hello"stale!the source changed, the .class did not

The source was edited and saved, but the .class file does not update itself.

working folderHello.javaprintln("Hi")Hello.classbytecode: prints "Hello"stale!

The output is still Hello: the java command ignores the source and runs only the bytecode in the .class.

working folderHello.javaprintln("Hi")Hello.classbytecode: prints "Hi"currentrecompiled

Recompiling refreshes the .class file.

working folderHello.javaprintln("Hi")Hello.classbytecode: prints "Hi"current

The change is now visible: Hi.

working folderHello.javaprintln("Hi")Hello.classbytecode: prints "Hi"currentjava expects a class name, not a file name

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.class

Running

Working in an IDE

Project · Hello.java▶ Runproject▾ srcHello.java1public class Hello {2 public static void main(String[] args) {3 System.out.println("Hello")4 }5}';' expectedConsolefix it and press ▶ Run: javac + java → Hello
  • 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

Hello.classJVMWindowsx86-64machine codeJVMLinuxx86-64machine codeJVMmacOSARM64machine codecompile once, run wherever there is a 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 -c ships 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.
The JVM is a stack machine: instead of registers like a CPU, it puts values on an operand stack and operates on the values at the top.

Running · Run the code step by step

Code Trace: The JVM Executes Bytecode

source:int a = 3;local variablesargs0 args31 a—2 b—3 coperand stackempty

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).

source:int b = 4;local variablesargs0 args31 a42 b—3 coperand stackempty

The same pair for b: 4 onto the stack, then into slot 2.

source:int c = a + b;local variablesargs0 args31 a42 b—3 coperand stack3

iload_1 copies a's value onto the stack: [3].

source:int c = a + b;local variablesargs0 args31 a42 b—3 coperand stack34

iload_2: [3, 4]. The two values to add are on top of the stack.

source:int c = a + b;local variablesargs0 args31 a42 b—3 coperand stack7

iadd pops the top two values, adds them and pushes the result: [7].

source:int c = a + b;local variablesargs0 args31 a42 b73 coperand stackempty

istore_3: 7 is popped and stored in c. The stack is empty again.

source:System.out.println(c);local variablesargs0 args31 a42 b73 coperand stackSystem.out

getstatic pushes a reference to the System.out object.

source:System.out.println(c);local variablesargs0 args31 a42 b73 coperand stackSystem.out7

iload_3: the value to print (7) is on the stack too.

source:System.out.println(c);local variablesargs0 args31 a42 b73 coperand stackempty

invokevirtual pops both values and calls println(int): 7 is printed on the console.

source:}local variablesargs0 args31 a42 b73 coperand stackempty

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

inttotal=price*3;keywordidentifieroperatoridentifieroperatorliteralseparator
  • The compiler first splits the code into tokens: keywords, identifiers, literals, operators, separators.
  • Java is case-sensitive: num and Num are 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; and x = 1; are the same, but publicclass is 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; or System.out.println(total);
  • A block groups the statements inside braces into one unit.
  • A statement can contain one or more expressions.
block { … }statement (assignment)total=price * qty;expression → 360statement (assignment)discount=total > 300;expression → true

Language Structure · Run the code step by step

Expression, Statement and Block Step by Step

Memory (variables)price120intqty?inttotal?int

An int box is set aside for price and 120 is stored in it.

Memory (variables)price120intqty3inttotal?int

The qty box is created: 3.

Memory (variables)price120intqty3inttotal?intExpressionprice * qty120 * 3→ 360

The expression on the right is evaluated first: price * qty → 120 * 3 → 360.

Memory (variables)price120intqty3inttotal360int

The value is assigned to the total box: total = 360.

Memory (variables)price120intqty3inttotal360intExpressiontotal > 300360 > 300→ true

Condition expression: total > 300 → 360 > 300 → true. Since it is true, we enter the block.

Memory (variables)price120intqty3inttotal360int

The statement in the block runs: Discount is printed.

Memory (variables)price120intqty3inttotal360int

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");
    }
}
// print the greetingSystem.out.println("Hello");/* comment */javacskips commentsgetstatic System.outldc "Hello"invokevirtual printlnreturnHello.java (source)Hello.class (bytecode): no comments

Source Code

Comment Pitfalls

CodeWhat 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

Write codeCompile (javac)syntax · type errorRun (JVM)runtime errorCheck the resultlogic error
ErrorWhen?Example
SyntaxAt compile timeMissing semicolon
TypeAt compile timeAssigning text to a number
RuntimeWhile the program runsDivision by zero
LogicThe program runs but the result is wrongWrong condition

Basics · Step by step

Kinds of Errors by Example

Syntax error

Write codeCompile (javac)Run (JVM)Check the result
public class Bug1 {
    public static void main(String[] args) {
        System.out.println("Hello")
    }
}
Bug1.java:3: error: ';' expected
        System.out.println("Hello")
                                   ^
1 error

The 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

Write codeCompile (javac)Run (JVM)Check the result
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 error

A String cannot go into an int box. Types are checked at compile time. Fix: int num = 42;

Runtime error

Write codeCompile (javac)Run (JVM)Check the result
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

Write codeCompile (javac)Run (JVM)Check the result
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

ErrorActual messageFix
Missing semicolonHello.java:3: error: ';' expectedadd ; at the end of the previous statement
Misspelled method
(System.out.printn)
error: cannot find symbol
symbol:   method printn(String)
location: variable out of type PrintStream
rename it to println
Lowercase
(system.out)
error: package system does not existSystem starts with a capital S
Name and file don't matcherror: class Greeting is public, should be declared in a file named Greeting.javafile name = public class name
Wrong launch
(java Greeting)
Error: Could not find or load main class Greetingno .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

Score.java:3: error: ';' expected int score = 85 ^1 errorfilelinekinddescription← ^ where the error was noticedException in thread "main" java.lang.ArithmeticException: / by zero at Bug3.main(Bug3.java:4)← stack trace: which method, which file and line
  • 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

3int score = 85✗ reported4System.out.printn("Score: " + score);? not reported yetScore.class: none

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.

3int score = 85;✓ fixed4System.out.printn("Score: " + score);? not reported yetScore.class: none

Fix the spot the message points to: add ; at the end of the line and save the file.

3int score = 85;✓ fixed4System.out.printn("Score: " + score);✗ reported nowScore.class: none

Recompile: the syntax is now correct, the semantic check runs and cannot find a method named printn.

3int score = 85;✓ fixed4System.out.println("Score: " + score);✓ fixedScore.class: none

The symbol: line names what was not found: fix the method name to println.

3int score = 85;✓ fixed4System.out.println("Score: " + score);✓ fixedScore.class: created

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

Get inputg1 = 70, g2 = 90Validate0 ≤ g ≤ 100 ?Process(70 + 90) / 2 = 80Produce result"Average: 80"
  • For each step, state its precondition and the value it produces.
  • Large recipes split into subtasks (in Java these will later become methods).
Test the recipe by hand before coding: tracing the steps for 70 and 90, do you get 80? If 101 is entered, which step stops it?

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 values for the grade input on a number line (not to scale)07090100lower bound (0, 0)typical (70, 90)invalid (101)101invalidvalid grade range: 0–100invalid
Sample inputExpected outputWhy?
70, 9080typical case
0, 00lower bound
101, 50error messageinvalid 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.
Hello.javapublic class HellojavacHello.classbytecodeJVMoutputFile name = public class name; the JVM starts execution at the main method.

Summary

Review Questions

  1. How are the JDK, bytecode and the JVM related?
  2. Which commands compile and run Hello.java?
  3. What is the role of the main method?
  4. What is the difference between an expression and a statement?
  5. How do you tell a syntax error from a logic error?
  6. If the source is changed but not recompiled, what does the java command run?
  7. Why does "Score: " + 40 + 45 give Score: 4045?
  8. How do command-line arguments reach the program?

Summary

Exercises

  1. Write an AboutMe program that prints your name, department and student number on three separate lines; compile and run it.
  2. Produce the same output with a single println and \n.
  3. Print a three-line course–credit table using \t.
  4. Delete the ; in System.out.println("Hello") and compile; interpret the line number and the ^ in the error message.
  5. Name the class Hello and the file hello.java, then compile. What happens, and why?
  6. Predict the output of System.out.println(5 + 3); and System.out.println("5 + 3");; run them to check.

Summary

References

The End

Chapter 5: Getting Started with Java
Previous: Chapter 4.3: Introduction to Programming · Next: Chapter 6: Variables, Data Types and Operators
1 / 1Sercan KÜLCÜ. All rights reserved.