Java – Basic Program

 

 Three things need to be done to make a java program work. They are

1. Create,
2. Compile, and
3. Run

  • A source file with .java extension is created and is compiled by java compiler which yields a class file with .class extension
  • This class file is run by the JVM and gives the result.
  • A class file, if it is created in a windows environment can run and gives the same result in linux environment and so on. That is why, java is platform independent.

Java Hello World Example Program:

HelloWorld.java

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

Output:

C:> javac HelloWorld.java
C:> java HelloWorld
Hello World

Creating a source file:

Type the above program in a notepad and save the file with the name that should match exactly the class name and with .java extension. That is HelloWorld.java

Compiling the source file:

2.Open command prompt and go to the directory where HelloWorld.java is located and type the command

javac HelloWorld.java

The program will be compiled by javac compiler and HelloWorld.class file is created and ready to be executed.

Run the program:

3. Then type the command

java HelloWorld

This command will execute the class file and displays the output ‘Hello World’ .

Prev                                                                                                                                         Next