Monday, 25 May 2009

Running a simple program

Here you would learn how to write and run a simple Java program .
First of all, you have to set your environment. It includes
1 Setting the path variable
Go into the directory where you have installed Java
eg C:\Program Files\Java\jdk1.6.0_07\bin
Copy the corresponding path on your machine
This gives the location of java compiler
Now right click on My computer > Properties > Advanced > Environment variables
Click New in System Variables
Enter path in variable name field
Paste the directory path in Variable value field and click on Ok
Close it
2 Setting classpath

Create a folder which will contain your programs

Copy it's path

Create a new System variable with name as classpath and

value as the path of your new directory

Click Ok and close

3 Sample code

class first

{

public static void main ( String args [] )

{

System.out.println ("First Java program") ;

} // main function ends

} // class ends

You can copy this code in a notepad file with name first and extension .java

and save it in the

folder created above

4 Running the program

Click on Start > Run or Press Windows key and then R

Type cmd and press enter

Type cd path

where path is the location of your folder for programs (same as classpath)

Type javac first.java and press enter

A class file should appear in the directory

Now type java first and press enter

First Java program should get printed on the screen

See Details for explanation of code