Tuesday, December 23, 2008

First Java Program Example

Hello All,

The Java prorgam looks like as follows:

HelloWorld.java
-----------------
public class HelloWorld
{
public static void main(String [] args)
{
System.out.println(" Hi. to all");
}
}
--------------------
Things to note:
1. Java file name must be same as the class name (in above example its HelloWorld) which is defined as public and having main method. This is in case of a stand alone program where you are trying to execute the first program in Java.
2. The Parameter passed in main method i.e. String [] args, is actually the referring to the arguments provided while calling the main method through the console command.

How to Compile & Run.
------------

1. Create a folder such as c:\JavaWorks
2. Save the above file withing the newly create folder with the name as HelloWorld.java
3. go to your start menu, click on run
4. enter text cmd and press enter. It will open up a command prompt.
5. go to the folder location in the console i.e your command prompt should be pointing to c:\JavaWorks
6. Verify Java Development Kit is already installed in your machine. for more details please refer to my earlier article on how to install java on my machine.
7. After installation verification, enter javac HelloWorld.java command console and press enter.
8. By pressing enter , a class file with the name HelloWorld.class will be created in the same folder, where you have placed the Java file.This class file is the compiled code which will be actually executed.
9.Verify, if any error message shown on the prompt, if compiled successfully it will show the prompt again without any message.
10. Now to execute the class file which you have generated in step 8, enter java HelloWorld on your command prompt , where you have compiled you java file, and press enter key.
11. It will show you a message as "Hi. to all" .
12. For your help, i am copy pasting the commands on the console here in sequence.:

==========================
C:\JavaWork>javac HelloWorld.java

C:\JavaWork>java HelloWorld
Hi. to all

C:\JavaWork>
==========================

If you have face any issue, drop a comment here.

No comments:

Post a Comment