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:
- Java program to check if a number is a composite number or not
- Java next() vs nextLine() differences with examples
- Java program to check for disjoint sets in two ways
- 4 different Java programs to convert a list to set
- Java program to convert an image to Base64 in 2 different ways
- Java program to print odd numbers from 1 to 100
- Java program to print an upper triangular matrix
- How to remove all white spaces from a file in Java