Skip to content
Qyubie Learn
Java tutorialLesson 2 of 18 · tap to see all lessons

Java tutorial · Beginner

Java Program Structure and Syntax: Your First Program Line by Line

Understand every line of a first Java program: classes, main, statements, comments, identifiers, keywords, and the three kinds of errors.

  • Qyubie Learn Editorial Team
  • Published
  • 8 min read

Includes 4 quick checks you can do right here.

Java's first program looks long compared with Python's one-liner, but every word has a job. In this lesson we take it apart line by line. Then we cover the rules every Java file follows: statements, comments, names, keywords, and the kinds of errors you'll meet.

By the end of this lesson you will be able to:

  • explain each part of a basic Java program,
  • tell the difference between print and println,
  • write comments and choose valid names, and
  • tell a syntax error from a runtime error and a logic error.

Running the examples: Java can't run on this page, so the practice here is predicting output, a skill exams test constantly. To run Java yourself, use the IDE you set up in lesson 1.

The whole program

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

Output:

Hello, world!

Line by line

public class Hello {: Java code lives inside classes. This declares a class named Hello. Because it is public, the file must be named Hello.java. The { opens the class body; its matching } is the last line.

public static void main(String[] args) {: the main method, where the program starts. You'll write this line in every program for now. The words mean:

WordMeaning (short version)
publiccan be called from outside the class (the JVM needs to call it)
staticbelongs to the class itself, so no object is needed to call it
voidreturns nothing
mainthe special name the JVM looks for to start the program
String[] argscommand-line arguments, as an array of text

System.out.println("Hello, world!");: prints text and then moves to a new line. Text in double quotes is a String. Every statement ends with a semicolon.

} }: close the method, then the class.

Quick check

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

println prints and then ends the line. print prints and stays on the same line.

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

Output:

ABC
D

Quick check

What does this print?
System.out.println("Hi");
System.out.print("there");
System.out.print("!");

Statements and expressions

A statement is one complete instruction, and it ends with ;. An expression is a piece of code that produces a value, such as 2 + 3, price * 2, or "Hi " + name. Statements are often built from expressions:

int price = 50;              // statement: declare and store a value
int total = price * 3 + 10;  // the right side is an expression
System.out.println(total);   // statement: call a method

Output:

160

A block is a group of statements inside { }. Class bodies, method bodies, and (later) if and loop bodies are all blocks.

Comments

Comments are notes for people. The compiler ignores them.

// A single-line comment: everything after // is ignored.

/* A multi-line comment
   can span several lines. */

/**
 * A documentation (Javadoc) comment, placed above classes and methods.
 * Tools turn these into web-page documentation.
 */
public class Notes {
    public static void main(String[] args) {
        System.out.println("Comments don't print"); // they can follow code too
    }
}

Output:

Comments don't print

Good comments explain why, not what. // add 1 to count above count++; adds nothing, but // skip the header row helps.

Identifiers and naming rules

An identifier is a name you choose for a class, method, or variable. The rules:

  • Use letters, digits, _, and $.
  • Don't start with a digit: 2ndPlace is invalid, place2 is fine.
  • Don't use spaces or symbols like - or #.
  • Don't use a keyword (see below).
  • Names are case-sensitive: score, Score, and SCORE are three different names.

The conventions every Java programmer follows (not enforced, but expected):

KindStyleExample
ClassPascalCaseStudentRecord
Variable, methodcamelCasefinalGrade, computeAverage()
ConstantUPPER_SNAKE_CASEMAX_STUDENTS

Quick check

Which of these is a valid Java variable name?

Keywords

Keywords are words with a fixed meaning in Java, so you can't use them as names. You've already seen several: public, class, static, void, int. Others you'll meet in this course include:

if else switch case for while do break continue return new this final private protected extends implements interface abstract try catch finally throw throws import package

true, false, and null aren't technically keywords, but they're reserved values, so you can't use them as names either.

Three kinds of errors

1. Syntax (compile-time) errors. The code breaks Java's grammar, so javac refuses to compile it and nothing runs. Examples: a missing ;, unmatched braces, or a misspelled keyword.

System.out.println("Hello")
error: ';' expected

2. Runtime errors. The code compiles, but something goes wrong while it runs, and Java stops with an exception. For example, dividing an integer by zero:

int students = 0;
int perGroup = 30 / students;
Exception in thread "main" java.lang.ArithmeticException: / by zero

3. Logic errors. The program compiles and runs without crashing but gives the wrong answer. These are the hardest to find, because Java doesn't complain:

int quiz1 = 80;
int quiz2 = 90;
double average = quiz1 + quiz2 / 2;   // meant (quiz1 + quiz2) / 2
System.out.println(average);

Output:

125.0

Division happens before addition, so this computes 80 + 45. Parentheses fix it: (quiz1 + quiz2) / 2.

Quick check

A program compiles, runs, and finishes without any message, but it shows a total of 0 when it should show 450. What kind of error is this?

Common mistakes

  • Missing semicolon at the end of a statement: the compiler reports ';' expected.
  • Wrong capitalization. system.out.println and string won't compile. It's System and String.
  • File name ≠ public class name.
  • Unmatched braces. Every { needs a }. Indenting consistently makes this easy to see.
  • Smart quotes from a word processor (“Hello”): Java needs plain " quotes.

Summary

  • A Java program is a class with a main method, and execution starts in main.
  • println ends the line; print doesn't.
  • Statements end with ;, and blocks are wrapped in { }.
  • Comments: //, /* */, and /** */ for documentation.
  • Identifiers can't start with a digit or be keywords, and they're case-sensitive.
  • Syntax errors stop compiling, runtime errors crash a running program, and logic errors give wrong answers.

Next lesson: variables, constants, and data types.

References and further reading