Thuta Learning
Java
BasicProgrammingBeginner

Syntax & Hello World

JavaLesson 420 min

What you'll walk away with

  • Identify the layers of a source file: package, imports, class, methods, statements
  • Explain each word of `public static void main(String[] args)`
  • Read and fix compile errors such as a missing semicolon, an unclosed brace or `string` instead of `String`
  • Control output layout with `print`, `println`, `\n` and `\t`

Explain it simply

Java syntax in plain words

Syntax is a language's grammar. In Java every program lives inside a class, and code is split into blocks with curly braces `{ }`. Each statement ends with a semicolon `;`, the way a sentence ends with a full stop.

Java cares about upper and lower case exactly. `Main` and `main` are different names, and so are `String` and `string`. Think of the compiler as an exam invigilator who never stops watching.

Problem → Why → Solution

The problem: four tiny slips, a wall of errors

The program below has four small slips: `Public` with a capital P, `string` instead of `String`, a missing semicolon and a missing closing brace. At a glance it looks almost like Hello World, but the compiler rejects it immediately.

More confusing still, the compiler does not report all four slips at once. The first compile shows three errors, and only after you fix them and compile again does it complain about `string`.

Main.java
Public class Main {
    public static void main(string[] args) {
        System.out.println("Hello World")
    }
// javac reports, in order:
//   error: class, interface, enum, or record expected   (Public)
//   error: ';' expected                                  (println line)
//   error: reached end of file while parsing             (missing })
// and after those are fixed: error: cannot find symbol  class string

Why it works this way

The compiler reads in two stages. The first checks grammar (parsing), and only the second checks whether names such as `string` actually exist. While a grammar error remains, the second stage never runs. So the fastest way through is to fix the first error and recompile, again and again.

Core concept: the layers of a source file

You can read a Java source file in layers, from the outside in. Outermost is an optional `package` line saying which group of classes this one belongs to. Next come `import` lines, which let you use classes from other packages by their short names. Then the class declaration; inside it, methods; inside methods, statements; and inside statements, expressions such as `2 + 3` that produce a value. The programs in this lesson need no package or imports, so they start at the class.

Now take the `main` signature apart word by word. `public` means it can be called from anywhere, including by the JVM. `static` means it can be called on the class itself, without creating an object. `void` says the method returns no value, and `main` is the name the JVM searches for. `String[] args` is an array that receives any text typed after the class name on the command line.

RuleExample
Every statement ends with `;``System.out.println("Hi");`
A block opens with `{` and closes with `}`a class body, a method body
Names are case-sensitive`String` ≠ `string`, `Main` ≠ `main`
Class names use PascalCase`HelloWorld`, `StudentReport`
Methods and variables use camelCase`printReport`, `totalScore`

Spaces and line breaks carry no meaning for Java; you can even split one statement across two lines. Good indentation is there for human readers. Newer JDKs (finalized in Java 25) also accept a shorter form without the class wrapper, but in Java 21 that was only a preview feature, so this course uses the full class form that works on every version.

How to read a file
  1. package and imports (optional)
  2. class { ... }
  3. method { ... }
  4. statement; statement;

Type the matching `}` as soon as you open a `{` and you will rarely see an unclosed-brace error.

General pattern: a source file

java
package com.example.app;          // optional: the class's package
import java.util.List;            // optional: types from other packages

public class ClassName {          // file must be ClassName.java
    public static void main(String[] args) {
        statement;                // every statement ends with ;
        // a one-line comment
        /* a block comment */
    }
}

If present, `package` and `import` go at the very top, in that order. A file can hold only one public class, and its name must match the file name. The compiler ignores comments entirely.

Reading Hello World layer by layer

You have seen this program before. This time, count where each pair of braces opens and closes and how many statements there are. The answer: two pairs of braces, one statement and one comment.

java
public class Main {
  public static void main(String[] args) {
    // Program starts here
    System.out.println("Hello World");
  }
}

Code breakdown

  1. Class declaration, outer blockpublic class Main {

    Declares the class and opens the outer block. The last `}` in the file closes this `{`.

  2. The main method, inner blockpublic static void main(String[] args) {

    The method the JVM runs first. `String` is a class, so it takes a capital S. This `{` opens the method body.

  3. A comment// Program starts here

    A note for developers. The compiler skips this line, so it adds nothing to the output.

  4. The only statementSystem.out.println("Hello World");

    Calls the `println` method of `out` (console output) inside the `System` class. It prints the text in double quotes and then moves to a new line. The semicolon ends the statement.

You should see
Hello World

`print`, `println` and escape sequences

`println` prints and then moves to a new line, while `print` leaves the cursor where it is. Inside a String you can also use escape sequences, which start with a backslash: `\n` for a new line, `\t` for a tab, and `\"` to put a double quote inside the text.

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.print("Loading");
        System.out.print("...");
        System.out.println(" done");
        System.out.println("Name:\tAung\nCity:\tYangon");
        System.out.println("She said \"hi\"");
    }
}
// Loading... done
// Name:   Aung
// City:   Yangon
// She said "hi"

How to read a compiler error message

Every `javac` error message has the same shape. Once you know its four parts, a long message stops being scary.

File name and line number

`Main.java:3:` means line 3 of `Main.java`. Jump straight to that line in your editor.

The error text

Text such as `error: ';' expected` says what the compiler wanted. 'Expected' usually means something is missing; 'cannot find symbol' usually means a name is misspelled or has the wrong case.

The code line and the caret `^`

The compiler reprints the offending line and points at the spot with `^`. For a missing semicolon, the `^` sits at the end of the line.

The error count

The last line is a count such as `3 errors`. A high count does not mean many mistakes; one slip can trigger several errors.

In real projects

In real codebases

In real projects, almost every file starts with a package line such as `package com.company.billing;` followed by ten or so imports. The package name must match the folder structure: a class in `com.company.billing` lives in the `com/company/billing/` folder. When you read framework code like Spring Boot, knowing the layers from this lesson helps you quickly see which block is responsible for what.

Instead of arguing over naming and formatting, teams pick a style guide such as Google Java Style and let a formatter apply it automatically. Code reviews can then focus on logic rather than indentation. Public methods usually carry `/** ... */` Javadoc comments, because the `javadoc` tool turns them into HTML documentation.

Common mistakes

Common syntax mistakes

Writing `Main` instead of `main`

`public static void Main(String[] args)` compiles, because it is just an ordinary method with a capitalized name. When you run it, though, the JVM cannot find `main` and fails with 'can't find main(String[]) method'. The compiler does not catch this one, so watch for it.

Counting braces by eye

Once you have several methods and blocks, a missing `}` is reported on the last line of the file as 'reached end of file while parsing', not where the real slip is. Use your editor's auto-format and look at the indentation; where it looks wrong is where a brace went missing.

Pasting smart quotes

Code copied from a Word document or a chat app often brings curly quotes (“ ”) instead of `"`, and the compiler reports 'illegal character'. Write code in a plain-text editor.

Mini challenge

Mini challenge: print a bus ticket

Write a `Ticket` program that prints a small bus ticket to the console using `print`, `println`, `\t` and `\"`.

  • Print the header line `=== Bus Ticket ===`
  • Print From and To on one line, using `print` once and `println` once
  • Use `\t` in the Seat line
  • Put quoted text in the Note line with `\"`
  • Add one comment
Ticket.java
public class Ticket {
    public static void main(String[] args) {
        // TODO: print the header "=== Bus Ticket ==="
        // TODO: print "From: Yangon" WITHOUT a line break, then " -> To: Mandalay"
        // TODO: print "Seat:" and "12A" separated by a tab (\t)
        // TODO: print Note: "Arrive 15 minutes early" with the quotes visible
    }
}

Expected: Four lines: `=== Bus Ticket ===`, `From: Yangon -> To: Mandalay`, `Seat:` and `12A` separated by a tab, and `Note: "Arrive 15 minutes early"`.

Show hint

Use `System.out.print(...)` where you do not want a line break. Inside a String, write `\"` to include a quote.

Show solution
Ticket.java
public class Ticket {
    public static void main(String[] args) {
        // A tiny ticket printed with print, println and escape sequences
        System.out.println("=== Bus Ticket ===");
        System.out.print("From: Yangon");
        System.out.println(" -> To: Mandalay");
        System.out.println("Seat:\t12A");
        System.out.println("Note: \"Arrive 15 minutes early\"");
    }
}

Quick quiz 1 / 3

Which `main` signature both compiles and lets the JVM start the program?

Quick quiz 2 / 3

What does `System.out.print("A"); System.out.println("B"); System.out.print("C");` print?

Quick quiz 3 / 3

The compiler shows three errors: the first is 'class, interface, enum, or record expected' on line 1, the last is 'reached end of file while parsing'. What should you do first?

What to remember

  • Read a source file in layers: package → imports → class → methods → statements
  • Every statement ends with `;` and every block has a matching pair of `{ }`
  • Java is case-sensitive: write `String`, `System` and `main` exactly
  • `println` breaks the line and `print` does not; shape output with `\n`, `\t` and `\"`

Java Language Changes, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Syntax & Hello World | Thuta Learning