A Simple Java Application


The following steps describe how to create, compile, and execute a simple Java application. The sample application will be called Hello. When you run it, it will print the string “Hello, world”.

Create the Source File

You can use any text editor to create your source files. Start with a new file named Hello.java, and copy the following lines into the file:

 class Hello{   public static void main (String args []) {     System.out.println("Hello, world");   } }

The first line in this code declares a class named Hello.

The second line declares a method named main() in that class. The method accepts an array of String objects as its argument. Three keywords precede the method name. The public keyword indicates that the method can be invoked by code in any other class. The static keyword indicates that the method is associated with the class, not a specific instance of the class. The void keyword indicates the method does not return a value. All Java applications begin execution with the method main().

The third line displays the string “Hello, world”. This is done by invoking the method named println() in the object System.out. The method accepts one argument, a string, and sends its output to standard output. println() automatically appends a newline to its output. (There is also a method named print() that does not append a newline.)

Note that, as in C/C++, Java uses curly braces to group blocks of code, and semicolons to end statements.

Compile the Source File

You must now compile your file. The Java compiler included in the JDK is called javac. Enter the following command to compile Hello.java:

 javac Hello.java

If you get a “javac: command not found” error, the directory with javac might not be in your path. Check to make sure that you have installed the JDK, and that you have added the directory containing javac to your path. On some systems, this directory is in /usr/java.

If all goes well, javac will create a file named Hello.class in the current directory Hello.class contains the bytecode for your application.

Invoke the Java Interpreter

You can execute a Java application by invoking the Java interpreter, which is the command java. The java interpreter uses a JVM to run the bytecode in your .class file.

To run the bytecode in Hello.class, enter the following command line:

 java Hello

Note that you do not enter the extension .class. The program will generate the following output:

 Hello, world

If you have more than one class definition in your .java file, the compiler will generate multiple .class files. In this case, you must run the one that contains the main() method.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net