Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Your first program

In the previous lesson we ran a three-line program. Now let's take it apart and look at the classic way of writing it, which you will find in most existing projects.

The main method

A Java program starts with the main method — a named block of code. Everything between the curly braces { and } is the method's body, and it runs in order, top to bottom:

void main() {
    IO.println("Start");
    IO.println("End");
}

Output:

Start
End

The word void means the method returns nothing. The empty parentheses after main are a place for parameters, which we cover in the chapter on methods.

Statements and semicolons

A single command in a program is called a statement. In Java every statement ends with a semicolon. Code inside a method body is indented by four spaces — that shows it belongs to main.

println and print

IO.println() prints a value and moves the cursor to a new line. IO.print() prints a value without a line break, so the next output continues the same line:

void main() {
    IO.print("Java ");
    IO.print("25");
    IO.println();
    IO.println(2 + 3);
}

Output:

Java 25
5

IO.println() with no arguments just moves to a new line. Numbers are written without quotes, and Java first evaluates the expression 2 + 3, then prints the result.

Comments

A comment is a note for humans that the compiler skips. A single-line comment starts with //, a multi-line one goes between /* and */:

void main() {
    // A single-line comment
    /* A multi-line
       comment */
    IO.println("Comments are not printed");
}

Output:

Comments are not printed

The classic form

Before Java 25 a program always had to be wrapped in a class — a container for code that the OOP chapter explains in detail. You will see this form in books, job interviews and large projects:

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

Output:

Hello, world!

The file name must match the class name: Main.java. System.out.println() does the same as IO.println(). Both forms are valid and run with the same java Main.java command. In this course we use the short one: it has fewer words that we cannot explain yet.

Common mistake

If you forget a semicolon, the program does not compile:

void main() {
    IO.println("Hello")
}

Output:

Main.java:2: error: ';' expected
    IO.println("Hello")
                       ^
1 error
error: compilation failed

The ^ arrow shows where the compiler expected the semicolon.

Thanks for reading!

Donate to the site — we work hard for you.