Monday 6 August 2012

How to compile and run a program in java?

A first simple program

/*
This is a simple java program.
Call this file "Example.java"
*/
class Example   {
       //Your program begins with a call to main( ).
       public static void main( String args[ ] )    
        {
             System.out.println("this is a simple java program.");
         }
  }


Name of the source file

For most computer languages, the name of the file that holds the source code is arbitrary. However, this is not the case with java. In Java the program containing the source code must be saved with the name that is the name of the class containing the main function. Also java is case sensitive, hence capitalisation of the name of the class must be considered while saving the file with same name.
However this is not necessary but  while compiling the code the name of class containing main is used with .java extension and hence if the name of file will be same, this convention makes it easier to maintain and organize your programs.

In the above program the program must be saved with the name of file "Example.java"

Compiling the program

step1: Open command line prompt.

step2: Go to the folder where the program is saved.

step3: Execute the compiler, javac, specifying the name of the source file on command line as shown here:
         
          C:\>javac Example.java

The javac compiler creates a file called Example.class that contains the bytecode version of the program.

Run the program

To actually run the program, you must use the Java interpreter, called java. To do so, pass the class name Example as a command-line argument, as shown here:

C:\>java Example

When the program is run, the following output is displayed:

this is a simple java program.


When java source code is compiled, each individual class is put into its own output file named after the class and using the .class extension. This is why it is a good idea to give your Java source files the same name as the class they contain- the name of the source file will match the name of the .class file. When you execute the Java interpreter as just shown, you are actually specifying the name of the class that you want the interpreter to execute. It will automatically search for a file by that name that has the .class extension. If it finds the file, it will execute the code contained in the specified class.








No comments:

Post a Comment