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 HelloWorld
declares a class calledHelloWorld
. In Java, all code must be contained within a class. Thepublic
keyword 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. Thepublic
andstatic
keywords have special meanings in Java, but for now, just think of them as part of the syntax of the main method. Thevoid
keyword indicates that this method does not return any value. Themain
method 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.out
object is a predefined object in Java that represents the standard output stream (usually the console). Theprintln
method 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 theHelloWorld
class.
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.