Java Hello World

Facebooktwitterredditpinterestlinkedinmailby feather

Let’s start by writing a simple program that prints “Hello World” to the output window.

  • Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the .java extension.
  • You can compile the file by typing “javac <filename.java>” in the command prompt or terminal in Linux OR if you were using any IDE, click the play button on the toolbar.
  • In terminal/command prompt, run your program by typing “java <filename>”.

Source code is written in Eclipse:

Java Hello World

Source code written in Notepad, compiled and executed in command prompt.

Java Hello World 1

Output:

Java Hello World 2

In Java every line of code that runs required to write inside the class. In our example, we wrote the code inside the class name as MyClass.

The main method inside the above program is the entry point or starting point. Let see the explanation of the keywords used in the main method below:

  • public- anyone has access to this method
  • static- Without creating an instance of the class containing the main method, the method can run.
  • void- method doesn’t return any value.
  • main- main is the name of the method.
  • String[]- The method accepts a single argument: an array of elements of type String.

We write the body of the main method, enclosed in curly braces:

System.out.println()

  • The println method prints a line of text to the output window.
  • The System class and out stream are used to access the println method.

Note: In Java, each statement must end with a semicolon. But do not use semicolons after methods and class declarations.

Comments :There can be two ways to write comments in the program. It can be defined as single line or multiline comment.

Single line comment : It is defined by the double forward slash ( // ) at the beginning of any line.

Multiline Comment: It is defined by the single forward slash and an asterisk (/* comment */) at both the ends of the pargraph.

Facebooktwitterredditpinterestlinkedinmailby feather