3 ways in Java to print Hello World without semicolon

Java program to print hello world without semicolon in 3 different ways:

All statements in Java needs to end with a semicolon. Otherwise, it will throw a compile time error. In Java, we can also treat the statements as expressions. We can take advantage of this to print the hello world statement without semicolon.

Let me show you different ways to print the hello world statement in Java without using semicolon.

Example 1: Java program to print hello world without semicolon by using if-else statements:

Let’s take a look at the below program:

class Main {
    public static void main(String[] args) {
        if (System.out.printf("Hello World") == null) {

        }
    }
}

If you run this program, it will print:

Hello World

Example 2: By using StringBuilder append method:

We can also use the append method as System.out.append with one if-else block to get the same output.

class Main {
    public static void main(String[] args) {
        if (System.out.append("Hello World") == null) {

        }
    }
}

Example 3: Java program to print hello world without semicolon using a for loop:

We can use a for loop to print the hello world statement. We have to pass the print statement as the third statement of the for loop. This statement runs at the end of each execution of the for loop.

class Main {
    public static void main(String[] args) {
        for (int i = 1; i < 2; System.out.println("Hello World")) {
            i++;
        }
    }
}

The for loop of this program runs only for one time and it executes the System.out.println statement at the end of its iteration. So, if you run this program, it will print the Hello World statement.

You might also like: