Java Hello World Program

Whenever we start to learn a programming language, the first program is always to print the Hello World. In the last article, we learned how to install Java on Windows 10. Now we are ready to write and run our first Hello World Java program.

Java Hello World Program

To keep things simple and working for a new user, here is the sample hello world program that you can use.

public class JavaHelloWorldProgram {

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

Save above program as JavaHelloWorldProgram.java in any directory.

1. Compile and Run Java Hello World Program

Open Command Prompt and go to the directory where the hello world program file is saved. Then execute the below commands in order.

$javac JavaHelloWorldProgram.java

$java JavaHelloWorldProgram
Hello World

java hello world program

If you are using Java 11 or higher, then you can simply execute java JavaHelloWorldProgram.java and it will compile and execute the program for you. No need to explicitly compile and then run the java program.

2. Java Program important points

  1. A Java source file can have multiple classes but only one public class is allowed.
  2. The java source file name should be same as the public class name. That’s why the file name of our program is JavaHelloWorldProgram.java
  3. When we compile the code, it generates byte code and save it as Class_Name.class extension. If you look at the directory where we compiled the java file, you will notice a new file created JavaHelloWorldProgram.class
  4. When we execute the class file, we don’t need to provide complete file name. We need to use only the public class name.
  5. When we run the program using java command, it loads the class into JVM and looks for the main method in the class and runs it. The main function syntax should be same as specified in the program, else it won’t run and throw exception as Exception in thread "main" java.lang.NoSuchMethodError: main.

I have recently created a short video for Java Hello World Program using Notepad and then Eclipse. Watch it for a better understanding. https://www.youtube.com/watch?v=ZREpFyjTDho That’s all for this post and you can start playing with your first class. In the next post, I will get into further details of classes, JDK, JVM, and other features provided by the Java programming language. Update: Read this post to know about JDK vs JRE vs JVM in java.

Source:
https://www.digitalocean.com/community/tutorials/java-hello-world-program