Monday, October 22, 2007

Start in java programe

You have downloaded and installed the J2SDK. You have run the demo applications. Now you are ready to write, compile, and execute your first Java program. Writing a Hello World! program is the traditional first step taken when learning a new language. It allows you to take the new language and its development tools through a test-drive, stepping through the complete install, edit, compile, and run cycle without getting bogged down in language details (plenty of that later).

In your favorite editor, enter the following code and save it in a file named HelloWorld.java. Also, I will assume you are working on a Microsoft Windows PC and that you save HelloWorld.java into the c:\src directory.


/**
* The HelloWorld class is an application that
* displays "Hello World!" to the standard output.
*/
public class HelloWorld {

// Display "Hello World!"
public static void main(String args[]) {
System.out.println("Hello World!");
}
}

Open a DOS or command window and change to the directory where you saved HelloWorld.java.


C:\>cd c:\src

The Java tool set consists of a set of command line programs located in the bin directory of your Java installation. For instance, if your Java installation is in C:\j2sdk1.4.2 then the programs you need will be located in C:\j2sdk1.4.2\bin. Make sure you have modified your PATH environment variable to include this bin directory. You can modify your PATH through the control panel or temporarily on the DOS command line (see your operating system help). You should test the Java command before making any PATH changes. The following command should output version information. If it throws an error, set your PATH before continuing.


C:\src>java -version

The "javac" command is used to compile .java files into intermediate bytecode files known as class files. Class files have a .class extension. The "java" command instantiates a JVM (Java Virtual Machine) instance and loads a Java class file that has a main method. The main method is the first code that is executed in your program.

Now compile HelloWorld.java into Java bytecode with the javac command.


C:\src>javac HelloWorld.java

If you do a dir command and see "HelloWorld.class" in the directory, then your compilation was successful.

No comments: