Java “Hello, World!” Program

Code Example

  public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
  

Explanation

  1. Class Definition

      public class HelloWorld {
      
    • public: An access modifier that makes the class accessible from any other class.
    • class: A keyword used to define a class in Java.
    • HelloWorld: The name of the class. It must match the file name (HelloWorld.java).
  2. Main Method

      public static void main(String[] args) {
      
    • public: An access modifier that makes the method accessible from any other class.
    • static: A keyword that allows the method to be called without creating an instance of the class.
    • void: The return type of the method, indicating it does not return any value.
    • main: The name of the method. It is the entry point of the program.
    • String[] args: The parameter of the main method. It is an array of String objects that can store command-line arguments.
  3. Print Statement

      System.out.println("Hello, World!");
      
    • System: A built-in class that contains several useful methods and fields, including out.
    • out: A static member of the System class, which is an instance of PrintStream. It is connected to the console.
    • println: A method of PrintStream that prints the argument passed to it, followed by a new line.

Steps to Run the Program

  1. Write the Code

    • Create a file named HelloWorld.java and write the code shown above.
  2. Compile the Code

    • Open a terminal or command prompt.
    • Navigate to the directory where the file is saved.
    • Run the command:
      javac HelloWorld.java
      
    • This will compile the Java file and create a HelloWorld.class file.
  3. Run the Program

    • In the same terminal or command prompt, run the command:
      java HelloWorld
      
    • This will execute the compiled bytecode and print Hello, World! to the console.