Friday, September 22, 2006

Let's Java 1

import java.lang.String;

public class HelloWorld{

String Hellostring = "Hello World";

public void main(String args[]){
system.out.println(Hellostring);
}

}

The piece of text in pencil color above, represents a simple "Hello World" program in the Java programming language. The first line requests the java compiler (1) to include the class
(2) String situated in the java.lang package (3) in your class files when it compiles it. The next line, public class HelloWorld declares the beginning of a class definition which spans the text area from the first curly bracket and the last one.

Within the class definition is the main() method which is called when the class is first loaded by the Java Virtual Machine (see also runtime environment). Note that this method is declared as 'public void' which means that it can be accessed by other classes and that it does not return any value after execution is completed. In this simple program, the only thing we do is print the text that has been stored in the variable Hellostring to the command prompt.

The variable Hellostring is declared on the first line in the class String Hellostring = "Hello World"; and initialised to the text string "Hello World".

To run this piece of code, copy it and save it as HelloWorld.java (make sure that it does not have a txt extension) then from the command line navigate to the directory in you have saved your file and enter the following command:

>javac HelloWorld.java

This tells the java compiler to compile the code and generate a java class file HelloWorld.class. You can now run the class with the java tool as follows:

>java HelloWorld

This will load your class and execute it . You should see the following on the command line:

>javac HelloWorld.java
>java HelloWorld
>Hello World

The last line here displays the output from your program.

Guday