Write a Java Program

Category: Java   Tags: Java, Java Basic

Here we will write a very basic java program that will give you an idea of how to write a java program.

Writing a Java Program


                          package com.tutorial.javabasic;

                          public class HelloWorld {

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


Let's walk deeper to our very basic java program:

                          package com.tutorial.javabasic;

Here we have specified package name (in this case its com.tutorial.javabasic)

Packages are containers for classes. They are used to keep the class name space compartmentalized. e.g. a package allows you to create a class named Employee, which you can store in your own package without concern that it will collide with some other class named Employee stored elsewhere. To know more about package see Java Packages and Interfaces.
                          public class HelloWorld {

public is access modifier, which allows the programmer to control the visibility of class members.

The keyword class is used to say that a new class is being is being defined.

Example is an identifier that is the name of the class. In java a class name should start with capital letter e.g. Employee, EmployeeContact are some valid class name.

One .java file can have maximum one public class.

The name of this source code file is HelloWorld.java because it has a public class named Helloworld. All java source code should be saved in .java file.

                          public static void main(String[] args)

This is the line at which the program will begin executing. All Java applications begin execution by calling
main( ).

The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java Virtual Machine (JVM) before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value.

                          System.out.println("Hello World!");

This will simply print Hello World! on console.

Compiling a Java Program

To compile a java program execute the compiler, javac, specifying the name of the source file on the command line (in our case source file is HelloWorld.java):

                          javac HelloWorld.java

The javac compiler creates a file called HelloWorld.class that contains the bytecode version of the program.

bytecode is the intermediate representation of a .java program that contains instructions the Java Virtual Machine(JVM) will execute.

Running a Java Program

To run a java program, use java interpreter. It will find the file HelloWorld.class and execute the code written inside:

                          java HelloWorld

Running this command should show this on your console:

                          Hello World!