First Program of Java : SECTION 1
Since we have successfully installed java in our system, let’s move further and write our first java program.
Step 1:
Create a file with file name followed by .java extension.
Let’s create a file with the name “HelloWorld.java”
Step 2:
Open this file with a notepad and start writing the following code.
class HelloWorld {
public static void main(String args[]){
System.out.println("Hello World, This is First Java Program!");
}
}
Step 3:
Once the code is completed save the file. Open a command prompt and go to the location where your HelloWorld.java file is saved. To go to that file path enter the following command on the cmd window. Where replace <path-to-java-file> with the actual path where your file is saved.
cd <path-to-java-file>
Step 4:
Once you are at the location where your java file is saved, let’s compile and run our java class.
To compile our java lass we must execute the command :
javac HelloWorld.java
Once our compilation is successful we can see .class file gets created in the same folder.
The name of the class file created is the same as the class name given in the program followed by the .class extension.
If there is an error in our java file then compilation will get failed and the error will be shown in the command prompt.
Step 5:
Once our java code is compiled successfully, let’s run our code and see the output.
To run our java code we need to run the following command :
java HelloWorld
This HelloWorld is the name of the class file without .class extension.
Once code is run successfully we will get the output printed :
Hello World, This is First Java Program!
Refer to the following image from the command prompt for Steps 3, 4, and 5.
Note that for compiling our java code we are using the File Name with .java extension and to run the code we are using Class Name without .class extension. If our class name is different from HelloWorld like
class HelloPrint{
}
Then our .class file will be generated as HelloPrint.class and to run the code we should call.
java HelloPrint
This means we can give different names to the java file and class. But keeping the same names for both preferred.
Since we can write our first java program and successfully run it. Next, we will see what is the meaning of each word in our first program in detail.