Running and compiling your first program, yes, it is HelloWorld. At least once almost every new programmer executed HelloWorld program in their development journey. Let’s continue that tradition.

HelloWorld program in Java.

In this program, you will learn the structure of Java program. To write below program, open an editor and save below program with filename HelloWorld and extension .java .

To type this program, you can use gedit editor if you are using Linux or Notepad / Notepad++ if you are using windows.

Open cmd (for windows users) or terminal (for Linux users) to compile and execute the following program.

Note : Make sure your class name and filename should be same and must begin with Capital letter.

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

To compile Java program, type following command on your prompt or terminal

javac <filename>.java

To execute Java program, type following command on your prompt or terminal

java filename

Output :

ujwal@ujwal-SVE15135CNB:~$ javac HelloWorld.java
ujwal@ujwal-SVE15135CNB:~$ java HelloWorld
Hello World, I am learning Java

Explanation of above program

Java is a pure object-oriented language, everything in Java is an object.  All the variables and methods are declared and defined within a class.

As you can see definition of our main method is within HelloWorld class.

By default, every Java program import classes in java.lang package. Don’t worry if you don’t know about importing a class and packages.

In C or CPP we include header files to use predefined functions.

In Java, packages contain a number of classes for a particular purpose.

To print anything on the console, we use following method.

System.out.println("Your message here");

The System is a predefined class in java.lang package. This class consist of various methods and members.

In above statement, out is a static member of System class. The out is an instance of the java.io.PrintStream class.

The println method is from PrintStream class. This method prints string on every new line.

The main method in our program is accepting String array as a parameter.

The keyword public is an access modifier, the void is return type and static is used to make the single copy of that method main is method name.

As this is our first program, you might be wondering what is access modifier? What is static? .

Don’t worry, you will learn all these stuff in next tutorials. I hope you enjoyed this tutorial.

Every successful programmer in the world was once a beginner.

Learn something, make mistakes, correct it and never do the same mistake again. Making mistakes and learning something from that mistake is way better than doing nothing.

All the best for all the errors which will come while learning to programme. Happy coding. 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *