Saturday, 5 January 2013

Creating First Java Application

Java Simple Hello World! Program

A program to print the Hello World! message on the Computer screen.

You can use the notepad as an editor to write your first program. Read the below codes and carefully write on your editor as Java is case sensitive.

Hello World! code

class HelloWorld {
    public static void main (String args[]) {
System.out.println(“Hello World!”);

This is the simple base program of Java. I will explain you line by line to get an idea about the unique features that constitute a Java Program. 

Class Declaration: class HelloWorld

This line declares a class, which is an object oriented construct. We must place all codes inside a class in Java. class is a keyword and declares that a new class definition follows. HelloWorld is the Java identifier that specifies the name of the class to be defined. 

Opening and Closing Braces :{  }

Every class definition in Java begins wih an opening brace "{" and ends with a matching closing brace "}", appearing in the last line in the example.

The Main Line: public static void main (String args[])

This line defines a method named main. Conceptually, this is similar to the main() fuctnion in C and C++; Every Java application program must include main() method. This is the starting point for the interpreter to begin the execution of the program. 

public : The keyword public is an access specifier that declares the main method as unprotected and therefore making it accessible to all other classes.
static:  Static declares this method as one that belongs to the entire class and not a part of any objects of the class. The main method must always be declared as static since the interpreter uses this method before any objects are created. 
void: The type modifier void states that the main method does not return any value.

The Output Line: System.out.println(“Hello World!”);

This is similar to a printf() statement in C++. Since Java is Object Oriented, every method must be part of an object. The println() method is member of the out object, which is a static data member of System class. 

Every Java statement must end with a semicolon.

Note: We must save this program in a file called ensuring that the file name contains class name properly. This file is called the source file. If the program contains multiple classes, the file name must be the class name of the class containing the main method. 

Compiling the Program

To compile the Program, we should run the Java Compiler javac with the name of then source file on the command line as shown below:

Running the Program

We need to use the Java interpreter to run stand alone program. See the below line. 

java Helloworld




No comments :

Post a comment