Hello Program in Java

The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways to create and display the word Hello on the console.

Using print() Method

Filename: HelloExample.java

Output:

Explanation: In Java, we use the print() method to print on the console. We have used out object, which is of the class PrintStream, to invoke the print() method. System is the class name.

There are different variations of print() method like println(), printf(). Let us discuss them.

Using println() Method

Filename: HelloExample1.java

Output:

Explanation: Instead of the print() method, we have used the println() method. The extra letters ln, moves the cursor to the next line. Therefore, the following snippet of code

Output

Using printf() Method

Filename: HelloExample2.java

Output:

Explanation: In the character array, we have stored every character of the word Hello. Then using the Java for-loop, we are iterating over each element of the given character array. In the above-written code, we have used the method printf() to display the word Hello on the console. This method is similar to the printf() function that is used in the C language.

Using Command Line Argument

String argvs[] mentioned as an argument of the main method (main()) is the command-line argument. We can easily pass values to the command-line argument. The following program illustrates the same.

Filename: HelloExample3.java

Hello

Explanation: We can compile the above program using the javac command. During the execution time, we have passed the word Hello as a command-line argument. Finally, we are iterating over the command-line arguments (which is a String array) and displaying the string elements.

By Taking Input From User

Filename: HelloExample4.java

Output:

Explanation: Using the Scanner class, we are taking input from the user. Then we are displaying the input using the println() method. If the user has input Hello, then the program displays the word Hello on the console.

source