Java - Fist Program - Hello World

To write and run a Java program, you will need to follow these steps:

  • Open a text editor, such as Notepad or Sublime Text, to write your Java code.
  • Type the following code into the text editor:
public class HelloWorld {
   public static void main(String[] args) {
      System.out.println("Hello, World!");
   }
}

  • Save the file with a ".java" extension, such as "HelloWorld.java". Note the name of the file must match the name of the public class in the code.
  • Open a command prompt or terminal window and navigate to the directory where you saved the Java file.
  • Compile the Java program by typing the following command and pressing enter:
javac HelloWorld.java
  • If there are no errors, you will see a new file called "HelloWorld.class" in the same directory.
  • Run the Java program by typing the following command and pressing enter:
java HelloWorld
  • You should see the following output in the command prompt:
Hello, World!

Congratulations, you have just written and run your first Java program!

Now, let's go over the syntax of the program:

  • The line public class HelloWorld declares a public class named "HelloWorld".
  • The code inside the curly braces { } is the body of the class. In this case, it only contains one method named "main".
  • The main method is the entry point of the program. It is where the program starts executing.
  • The line public static void main(String[] args) declares the main method, which takes an array of Strings named "args" as its parameter.
  • The code inside the curly braces { } is the body of the main method. In this case, it only contains one line of code.
  • The line System.out.println("Hello, World!"); prints the string "Hello, World!" to the console.