Writing Your First Java Program


Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 1.  Introduction to Java

You can never escape the first chapter of a book without writing the traditional "Hello, World" application. Back in the early 1980s there was a book written by Brian Kernighan and Dennis Ritchie called The C Programming Language that was and is the de facto standard for C programming. In their book they defined the first example that all computer programming books should have: A program that writes the words "Hello, World" on the screen. Therefore, you will find a standard "Hello, World" example in almost every programming book you encounter. So, as not to break tradition, Listing 1.1 is "Hello, World" a la Java.

Listing 1.1 HelloWorld.java
 1: public class HelloWorld  2: {  3:     public static void main( String[] args )  4:     {  5:         System.out.println( "Hello, World!" );  6:     }  7: } 

Compiling Your First Java Program

Create a new file on your computer in a specific folder of your choice. For example, you might create a new file using Windows Notepad in the following folder:


Enter the complete text of Listing 1.1 into your editor and save it with the following filename (note that case is important capital "H" and "W" and all the rest of the letters are lowercase):


If you are using Notepad, be sure to either enclose the filename in quotes ("HelloWorld.java") or check the filename when you are done, in some cases it likes to append a .txt to the end of the filename. If the filename is not correct, please correct it.

Open a command prompt and navigate to the folder where you saved your HelloWorld.java file. Using Windows as an example, open a command prompt, or MS-DOS prompt if you are using Windows 95, and enter the following command:

 c:  cd \java 

This will ensure that you are on the C: drive and change directory (cd) to the java subdirectory. Note that in this example you must have saved the file in this directory. Now you are ready to compile.

Compilation of Java programs is done at the command prompt using a tool that is packaged with the Java 2 SDK: javac read java see for Java Compiler. You compile a Java program by passing javac the name of the file you want to compile, for example:

 javac HelloWorld.java 

Upon executing the command you will see one of two possible responses: a new command prompt or a set of one or more errors. The most common error that my readers and students have when compiling Java programs has to do with an environment variable that Java depends on called CLASSPATH. The Java CLASSPATH is an interesting concept that often confuses not only new Java programmers, but experienced ones as well. The Java CLASSPATH is a list of folders that contain Java classes that you might want to include in your program, these define where your dependencies are located. If there is no CLASSPATH environment variable defined, the default value is the current folder. If there is one defined, the value must explicitly have the current folder in it if you want to compile from the current folder. To check the value of the CLASSPATH environment variable on your computer do the following:

 Windows:  echo %CLASSPATH%  Unix:  echo $CLASSPATH 

If the result is blank, then any errors you are receiving are not related to your CLASSPATH. If there is a value associated with the CLASSPATH environment variable, you must ensure that it includes the current folder. The CLASSPATH is simply a list of folders delimited by semicolons (;) on Windows and colons (:) on Unix. The current folder is specified by a period (.), which must appear in the CLASSPATH. To add the current folder to the CLASSPATH, enter the following:

 Windows:  Add the current folder to the CLASSPATH  set CLASSPATH=.;%CLASSPATH%  Or to erase the CLASSPATH's value  set CLASSPATH=  Unix:  CLASSPATH=.:$CLASSPATH; export CLASSPATH 

At this point your CLASSPATH related errors should go away.

If you have other errors, here is a list of things to check:

  • Ensure that your Java code matches Listing 1.1: The case of all words must match identically, for example, class must be lowercase and "HelloWorld" must have a capital "H" and "W" and all remaining characters must be lowercase. Note that the formatting of the document does not affect the compilation, for example, if you want to write the entire program on one line or add 20 spaces between each line it would have no affect on the compiler.

  • Ensure that the name of your file is HelloWorld.java, again check the case of each letter, and if in Windows make sure Notepad did not add a .txt to the end of the filename. That can be accomplished by getting a directory of the folder your file is in by issuing a dir command (or ls in Unix):


  • Ensure that you have the Java 2 SDK installed, and that the version you downloaded is the current version. To do so, execute the following command in the PATH:

     java -version 

Running Your First Java Program

After the HelloWorld.java file is successfully compiled, a new HelloWorld.class file is created. This is the file that contains the byte-code that contains instructions for the Java virtual machine to process. Java applications are run using the command-line tool java. To run HelloWorld, type the following from a command prompt in the folder that holds HelloWorld.class:

 java HelloWorld 

The result should be the following displayed to the screen:

 Hello, World 

If you receive an error, look at your CLASSPATH environment variable (see the discussion in the previous section for details).

Understanding Your First Java Program

It only took 7 lines to print "Hello, World" to the screen, and most of them have only one character each! Let's look at this program line-by-line and see what is happening.

 1: public class HelloWorld 

In Java programs, .java files are compiled into byte-code with a .class extension. .class files can be thought of as the program itself. In this first line, a new class called HelloWorld is being defined. You can create new classes by using the keyword class followed by a name for the class.

Lines 2 and 7, the brace pair { and }, define the body of the HelloWorld class. Everything that is included between Lines 2 and 7 is part of the HelloWorld class.

 3:     public static void main( String[] arguments ) 

Line 3 defines a method, or function if you would prefer, that is a member of the HelloWorld class called main. main is a very special function in Java, specifically for applications. main is the entry point that the Java Runtime Engine (JRE), or java.exe, processes when it starts. When you launch the application later by typing

 java HelloWorld 

you are telling the Java Runtime Engine to open the class file HelloWorld.class and process the main function. Let's break down this function prototype further:


The keyword public is known as an access modifier; an access modifier defines who can and cannot see this function (or variable.) There are three possible values for access modifiers:

public, protected, and private, each having their own restrictions, which we will cover later in the book. In this case, it is saying that this function, main, is publicly available to anyone who wants to call it. This is essential for the main function; otherwise the Java Runtime Engine would not be able to access the function, and hence could not launch our application.


The static keyword tells the compiler that there is one and only one method (or variable) to be used for all instances of the class. For example, if you have 100 different copies of the HelloWorld class running, there will be only one main function. This functionality will be explained more later when you get a little more Java under your belt, but for now remember that main functions have to be static in a class.


The term void refers to the return type. Functions can return values; for example, integers, floating-point values, characters, strings, and more. If a function does not return any value, it is said to return void. In this declaration it is saying that the main function does not return a value.


The word main is the name of the function. As previously mentioned, main is a special function that must be defined when writing a Java application. It is the entry-point into your class that the Java Runtime Engine processes when it starts; it will control the flow of your program.

 ( String[] arguments ) 

Enclosed in parentheses next to the function name is the parameter list passed to the function. When you write a function, you can pass any type of data for that function to work with. In this case, the main function accepts an array (a collection or set of items) of String objects (text) that represent the command-line arguments the user entered when he launched the application.

 java HelloWorld one two three four 

The command line then would have four items sent to it: one, two, three, and four. The variable arguments would contain an array of these four strings. Here is how that would be listed:

 arguments[0] = "one"  arguments[1] = "two"  arguments[2] = "three"  arguments[3] = "four" 

Note that the indexes (0, 1, 2, and 3) start at zero and climb up to one, minus the total number of elements. This zero indexing is common to many programming languages such as C and C++ and programmers refer to the first element in an array as the "0-th element." This book will address arrays in detail a bit later.

Command-line arguments are beneficial because they can give a program additional infor-mation about what tasks to perform. For example, if you wanted to create an application that added two numbers and printed the result, you could take the two numbers to add from the command line, for example:

 java AddApp 5 10 

In the main function you would read in the numbers 5 and 10, and then print their sum to the screen.

Lines 4 and 6, the brace pair, denote the body of the main function; everything that is written between these braces is part of the main function.

 5:         System.out.println( "Hello, World" ); 

Now this statement looks a little scary, but don't fret, it is not nearly as intimidating as it looks. Let's break apart this statement a bit:


System is actually a class that the Java language provides for you. This class is the focal point that you will use to access the standard input (keyboard), standard output (monitor), and standard error (usually a monitor unless you have a separate error output defined).



Whenever you have questions about a class, you can always refer to the Java SDK documentation. Here is what the Java 2 SDK documentation has to say about the System class:

"The System class contains several useful class fields and methods. It cannot be instantiated."

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined "properties;" a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

The System class has a collection of public attributes, or data members, and a collection of public methods, or functions, that you can access in your program. You access these properties and methods by placing a period (.) after the class name System, and then appending to it the method or property name. The "." denotes a hierarchical movement through the object; the object to the left of the dot is the parent of the object to the right. In this example, we are going to access the System class's out property.


The System class's out property is defined as follows:

 public static final PrintStream out 

As with the main function, it is both public, meaning that everyone can access it, and static, meaning that there is only one copy of it for all instances of the System class. The final keyword says that this variable cannot change in value.

As I already mentioned, the out variable represents the standard output device, typically the monitor. Note that the out variable is of type PrintStream.

The PrintSteam class contains a collection of print, println, and write functions that know how to print different types of variables: Booleans, ints, floats, and so on. This is how println can print out so many different types of values.



Here is what the Java 2 SDK documentation has to say about the out member variable:

"The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user."


Okay, finally we are down to the function that actually does all the work for us! println has multiple definitions, one for each of the native data types (int, Boolean, float, double, String, and so on). The one that we are concerned with is declared as follows:

 public void println(String x) 

This version of the println function prints a String called x, which is what you send it, to an output stream.



Here is what the Java 2 SDK documentation has to say about the println member variable:

"Print a String and then terminate the line. This method behaves as though it invokes print(String) and then println()."

You might have noticed that the PrintSteam class has both print and println member functions. The only difference here has to do with the line termination. print simply prints text to the screen, whereas println prints text to the screen followed by a new line.

 "Hello, World" 

Finally, you have the text String that you are telling println to print to the standard output device. The text string is enclosed in parentheses and delimited by double quotes ("").

Note that a semicolon terminates the very end of the statement. This is very important in the Java programming language. A semicolon terminates all statements; this is how the Java compiler knows where one statement ends and the next begins.


    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    Similar book on Amazon

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