Writing First Java Program

Java is a powerful, object-oriented programming language that is widely used for building a variety of applications. In this tutorial, we'll walk through the basic steps of creating, compiling, and running a simple Java program.


To write a Java program, we'll need to create a class that contains a main method. The main method is the entry point for our program and is where the execution of our code begins. In the example below, we've created a class called HelloHash that contains a main method that prints a message to the console.


Simple Hello HashCodec Program:

java
// A simple Java program to print "Hello HashCodec!"
import java.io.*;
public class HelloHash {
    public static void main(String[] args) {
        System.out.println("Hello HashCodec!");
        // Prints "Hello HashCodec!" to the console
    }
}

Output :

Hello HashCodec!


Once we've written our program, we'll need to compile it into bytecode that can be executed by the Java Virtual Machine (JVM). To do this, we'll use the javac command followed by the name of your Java source file (e.g. javac HelloHash.java). If our program compiles without errors, the javac compiler will create a .class file containing the bytecode version of your program.

To run the program, we'll use the java command followed by the name of your class (e.g. java HelloHash). This will launch the JVM and execute the bytecode in our .class file. If everything goes as planned, we'll see the output of our program printed to the console.

Steps To Compile And Run Java Program:

  1. Write the program in any of the text editors you like. Eg: notepad.
  2. Save the file with .java extension. The file name should be same as that of the class name which you used in the program(here HelloHash.java).
  3. Write the command javac followed by classname.java (here javac HelloHash.java) to compile the Java Source into ByteCode, which will be executed by Java Virtual Machine.
  4. If there is no error in the code, the compiler will convert java source code into an intermediate code known as Bytecode. If you look in your working folder, you can see that a file named HelloHash.class has been created. This implies that our source code is compiled successfully and ready to run now.
  5. To run the code, write the command java followed by the class name(here java HelloHash).
  6. You will see the output in the command prompt.

Thus our first java program is created and compiled successfully.