Here is a simple “Hello, World!” program in Java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Here is a step-by-step explanation of what is happening in this code:
- The first line
public class HelloWorlddeclares a class calledHelloWorld. In Java, all code must be contained within a class. Thepublickeyword means that this class is visible to other parts of the program. - The next line
public static void main(String[] args)is the main method of the program. This is the entry point of the program and the code inside this method will be executed when the program is run. Thepublicandstatickeywords have special meanings in Java, but for now, just think of them as part of the syntax of the main method. Thevoidkeyword indicates that this method does not return any value. Themainmethod takes an array of strings calledargs, which can be used to pass command-line arguments to the program. - The next line
System.out.println("Hello, World!");is a statement that prints the string “Hello, World!” to the console. TheSystem.outobject is a predefined object in Java that represents the standard output stream (usually the console). Theprintlnmethod is a method of this object that prints a line of text to the output stream. - Finally, the last line
}closes the main method and theHelloWorldclass.
To run this program, you will need to save it in a file called HelloWorld.java, then use a Java compiler to compile it into an executable program.
Once the program is compiled, you can run it by typing java HelloWorld at the command prompt. This should print “Hello, World!” to the console.
Don’t worry if you don’t understand the significance of static, public or any other keywords or statements of the above program, you will study that in detail in later tutorials.
For now, just understand that the above Java program is displaying a “Hello World!” text message in the console.