Chapter 6
HelloWorld! Your First Java Programs

by Joe Weber

When learning to program, it is often useful to jump in head first, learn how to write a short application, and then step back and learn the rest of the fundamentals. In this chapter, you do just that, and by the end you should be able to write your own Java programs.

HelloWorld Application

You have already seen the simplest Java program, HelloWorld, in Chapter 3, "Installing Java and Getting Started: JDK, Netscape, Explorer, HotJava Features." Now, take a closer look at each of the components. Listing 6.1 shows the HelloWorld application.

Listing 6.1 The HelloWorld Application

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

As you can see, there really isn't a lot to this program, which, I suppose, is why we call it the easiest Java application. Nevertheless, take a close look at the program from the inside out. Before you do that, though, let's compile the program and run it.

Create the File

The first step to create the HelloWorld application is to copy the text from Listing 6.1 into a file called HelloWorld.java using your favorite text editor (by choosing Windows, NotePad, or SimpleText on the Macintosh). It is very important to call the file HelloWorld.java, because the compiler expects the file name to match the class identifier (see "Declaring a Class" later in this chapter).


CAUTION:
If you use a program such as Microsoft Word to type the code, make sure that you save the file as text only. If you save it as a Word document, Word adds a lot of information about formatting the text that simply doesn't apply to your situation, and only causes you grief.


Compile the Code

To compile the program, you need to first install the JDK. Then, use the program javac included with the JDK to convert the text in Listing 6.1 to code which the computer can run. To run javac, on a Macintosh drag the source file over the javac icon. On any other computer, type the line:

javac HelloWorld.java

at a command prompt. The javac program creates a file called HelloWorld.class from the HelloWorld.java file. Inside this file (HelloWorld.class) is text known as bytecodes which can be run by the Java interpreter.

See "Installing a Downloaded JDK," Chapter 5

Run the Program

Now that you have compiled the program, you can run it by typing at the command prompt:

java HelloWorld


NOTE: The HelloWorld is not HelloWorld.class or HelloWorld.java, just the name of the class.


After you do this, the computer should print to the screen

Hello World!!

That may not seem very interesting, but then it's a simple program. If you don't see Hello World!! on the screen, go back and make sure you have typed in the file exactly as shown in Listing 6.1, and make sure that you called the file HelloWorld.java.

Understanding HelloWorld

Now that you have seen the results of the HelloWorld program, let's go back to the original source code and see if we can understand how it works. As you should begin to see, there are a lot of parts to the HelloWorld program. Once you understand all of them, you're a long way to being able to write any program.

Declaring a Class

The first task when creating any Java program is to create a class. Take a look at the first line of the HelloWorld application:

public class HelloWorld {

This declares a class called HelloWorld.

See "Classes in Java," Chapter 11

To create any class, simply write a line that looks like:

public class ClassName

Here, ClassName is the name of the program you are writing. In addition, ClassName must correspond to the file name. It's a good idea to make all your class names descriptive so that it's easier to remember what they are used for.


NOTE: It is an accepted practice that class names should always begin with a capital letter. This is not required, but considered good style. There are also a number of limitations on the names you can assign to a class, but you learn more about that later in Chapter 12, "Interfaces."


Next, notice the little curly brace ({) that is located before the class declaration. If you look at the end of the class, there is also a closing brace (}). The braces tell the compiler where your class will begin and end. Any code between those two braces is considered to be in the HelloWorld class.

Don't be confused. Braces are used for a number of things called blocks which are covered in more detail in Chapter 8, "Methods." The braces are matched in a LIFO (Last In, First Out) format. That means that the next closing brace closes the open brace which was closest to it. In the case of the HelloWorld program, there are two open braces so the one that closes the class is the very last one.

The main Method

The next line in the HelloWorld program reads:

public static void main(String args[]){

This line declares what is known as the main method. Methods are essentially mini- programs. Each method performs some of the tasks of a complete program. The main method is the most important one with respect to applications, because it is the place that all Java applications start. For instance, when you run java HelloWorld, the Java interpreter starts at the first line of the main method.

When creating any Java application, you need to create a main method as just shown. Later in Chapter 8, "Methods," you learn more about declaring and using methods.

Writing to the Screen

So how does the text Hello World!! appear when you run the HelloWorld program? The answer (as you have probably already guessed) lies in the next line of the program:

System.out.println("Hello World!!");

You can replace any of the text within the quotation marks ("") with any text that you would like.

The System.out line is run because, when the application starts up, the interpreter looks at the first line of code (namely the printout) and executes it. If you place any other code there, it runs that code instead.

More About System.out and System.in

You have just seen how System.out.println was used to print text to the screen. In fact, System.out.println can be used at any time to print text to what is known as Standard Out. In almost all cases, Standard Out is the screen.

The system.out.println serves approximately the same purpose as the writeln in Pascal. In C, the function is printf, and in C++, count.

println
Versus print
There is one minor variation on println which is also readily used: print("Hello World!!"). The difference between println and print is that print does not add a carriage return at the end of the line, so any subsequent printouts are on the same line. To demonstrate this, let's expand our HelloWorld example a bit by copying Listing 6.2 into a file called HelloWorld2.java and compile it with the line java HelloWorld2.java.

Listing 6.2 AHelloWorld Program with Two Printouts

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

To run the program, type:

java HelloWorld2

You should see output that looks like:

Hello World!
Hello World Again!

Notice that each phrase appears on its own line. Now, try the program again using print instead of println. Copy Listing 6.3 into a file called HelloWorld3, compile, and run it.

Listing 6.3 A HelloWorld Output Using print Statements

public class HelloWorld3 {
  public static void main (String args[]){
    System.out.print ("Hello World!");
    System.out.print ("Hello World Again!");
  }
}

Notice that the output you get looks like this:

Hello World!Hello World Again!

What caused the change? When you use print, the program does not add the extra carriage return.

Extending the String with +: Writing More Than HelloWorld
One of the features Java has inherited from C++ is the ability to add strings together. While this may not seem completely mathematically logical, it is awfully convenient for a programmer. Let's revisit our last HelloWorld program, and get the same output using one println and the + operator (see Listing 6.4).

Listing 6.4HelloWorld Output Adding Two Strings

public class HelloWorld4 {
  public static void main (String Args[]){
    System.out.print ("Hello World!" + "Hello World Again!");
  }
}

When you compile and then run HelloWorld4, you should see exactly the same output that was produced from HelloWorld3. This may not seem too interesting, so let's take a look at one more extension of the ability to add to strings--you can also add numbers. For instance, say you want to add the number 43 to the string. Listing 6.5 shows an example of just such a situation.

Listing 6.5HelloWorld with a Number

public class HelloWorld5 {
  public static void main (String args[]){
    System.out.print ("Hello World! " + 43);
  }
}

Listing 6.5 produces the line:

Hello World! 43

Getting Information from the User with System.in System.out has a convenient partner called System.in. While System.out is used to print information to the screen, System.in is used to get information into the program.

Requesting Input from the User Let's use System.in.read() to get a character from the user. I'm not going to cover this in too much depth because, frankly, System.in isn't really used that often in Java programs primarily because (as you learn in an upcoming section "HelloWorld as an Applet") it really doesn't apply to applets. Nevertheless, Listing 6.6 shows an example of a Java application that reads a letter from the user.

Listing 6.6Read Hello --An Application that Reads Input from the User

public class ReadHello {
  public static void main (String args[]){
    int inChar;
    System.out.println("Enter a Character:");
    try {
       inChar = System.in.read();
       System.out.println("You entered " + inChar);
       } catch (IOException e){
         System.out.println("Error reading from user");
         }
  }
}

You've probably already noticed that there is a lot more to this code than there was to the last one. Before I go into why, first compile the program, and prove to yourself that it works.

Enter a Character:
A
You entered 65

OK, now first things first. The code we are most interested in is the line which reads:

inChar = System.in.read();

System.in.read() is a method that takes a look at the character that the user enters. It then performs what is known as a return on the value. A value that is returned by a method is then able to be used in an expression. In the case of ReadHello, a variable called inChar is set to the value which is returned by the System.in.read() method.

In the next line, the value of the inChar variable is added to the System.out string just as you did in Listing 6.5. By adding the variable into the string, you can see the results of your work. It's not actually necessary to use a variable. If you prefer, you can print it out directly in the second System.out line, by changing it to

System.out.println("You entered "+ System.in.read());

Now, notice that the program displays a number instead of a character for what you entered. This is because the read() method of System.in returns an integer, not an actual character. The number corresponds to what is known as the ASCII character set.

Converting an Integer to a Character
To convert the number that is returned from System.in into a character, you need to do what is known as a cast. Casting effectively converts a given data type to another one. Change ReadHello to look like Listing 6.7.

Listing 6.7Read Hello An Application that Reads in a Character from the User

public class ReadHello {
  public static void main (String args[]){
    char inChar;
    System.out.println("Enter a Character:");
    try {
       inChar =(char) System.in.read();
       System.out.println("You entered " + inChar);
       } catch (IOException e){
         System.out.println("Error reading from user");
         }
  }
}

Notice the characters before System.in.read().The (char) causes the integer to be changed into a character.

The Rest of the Extra Code--try, catch
So what does the rest of all that code do? In this code, there is a sequence there called a try-catch block. In some programming languages, when a problem occurs during execution, there is no way for you as a programmer to catch it and deal with the problem. In some languages, it's a bit complicated. In Java, most problems cause what are known as exceptions.

See "Java's Exceptions," Chapter 19

See "Java's Events," Chapter 19

When a method states that it will throw an exception, it is your responsibility to only try to perform that method, and if it throws the exception, you need to catch it. Do you see the line of code right after the catch phase? If there is an error while reading, an exception called an IOException is thrown. When that happens, the code in the catch block is called.

HelloWorld as an Applet--Running in Netscape

If you are reading this book, odds are you are most interested in using Java to write programs which are called applets. Applets can be run in a browser such as Netscape Navigator.

Several differences exist between applets and applications. The most important of these is that Java applet classes extend an existing class. This class is called java.applet.Applet. For now, it's enough just to say that you have to extend Applet in order for a class to be usable as such.

See "Applets versus Applications," Chapter 21

The New Source Code--Compiling It

One of the simplest applets is the HelloWorld applet, the source code for which is shown in Listing 6.8. Right away you should see that the applet HelloWorld is quite different from the HelloWorld application in Listing 6.1. In a few sections, you break down the source code in order to understand it. For now, copy Listing 6.8 into a file called HelloApplet.java and compile it.

Listing 6.8HelloWorld as an Applet

import java.applet.Applet;
import java.awt.Graphics;
public class HelloApplet extends Applet {
  public void paint (Graphics g) {
     g.drawString ("Hello World!",0,50);
  }
}

Creating an HTML File

When you created the HelloWorld application in Listings 6.1-6.5, you ran them using the Java interpreter. Applets, however, don't run from the command line; they are executed within a browser. But, how do you tell the browser to open the applet?

If you have already written Web pages, you are familiar with HTML or Web pages. HTML pages are what a browser such as Netscape is used to dealing with. To get the applet into the browser, you need to embed what are known as HTML tags into an HTML file. The HTML file can then be read into a browser.

The simplest HTML file for the HelloApplet class is shown in Listing 6.9. Copy this text into a file called HelloApplet.html.

See "Including a Java Applet in an HTML Page," Chapter 14

Take a look at the third line of Listing 6.9. Notice the <APPLET> tag? The <APPLET> tag is a new HTML tag that is used to include Java applets. When creating your own HTML files, don't forget to include the closing </APPLET> tag as well, or your applets won't appear.


NOTE: With Java files, it is necessary that the file name be the same as the class file. This is not necessary with the HTML file. In fact, a single HTML file can contain several <APPLET> tags.


Listing 6.9HelloApp.html--HTML File to use for Applet

<HTML>
<BODY>
<APPLET CODE="HelloApplet.class" WIDTH = 200 HEIGHT=200> </APPLET>
</BODY>
</HTML>

Running the Program in Appletviewer

Now, to run the applet, the JDK includes a very simplified version of a browser called Appletviewer. Appletviewer looks for <APPLET> tags in any given HTML file and opens a new window for each of them.

When you run the HTML file in Appletviewer, you see output such as Figure 6.1. To run the HelloApplet program using Appletviewer, on the command line type:

appletviewer HelloApplet.html


FIG. 6.1
Appletviewer opens a new window and runs HelloApplet in it.

Running HelloWorld in Netscape

Another option for running applets is with Netscape Navigator. You're probably already familiar with using the Navigator. To open the HelloApplet program in Netscape, choose File, Open File, then select the HelloApplet.html file, as shown in Figure 6.2.

FIG. 6.2
HelloApplet can also be run by using Netscape Navigator.

Understanding the Source Code

Now that you have seen how to run the HelloApplet program, let's go back and see how the program works.

Importing Other Classes
The first thing to notice are the top two lines of the code:

import java.applet.Applet;
import java.awt.Graphics;

The import statement is a new one. Often it is necessary or easier to use the contents of a class file which have already been created, rather than try to reproduce that work yourself. The import statement enables you to use these other classes. If you are familiar with the C/C++ #include declaration, the import statement works in somewhat the same way.

In the case of the HelloApplet program, there are two classes that are used other than HelloApplet. The first is the java.applet.Applet class. The Applet class contains all the information that is specific to applets. In fact, in order for any class to be run in a browser as an applet, it must extend java.applet.Applet.

The second class that is imported into HelloApplet is the java.awt.Graphics class. java.awt.Graphics contains all kinds of tools for drawing things to the screen. In fact, the screen is treated as a Graphics object.

Declaring an Applet Class
You may have noticed that there is a slight difference between this class declaration for the HelloApplet class. HelloApplet extends Applet. Remember in the last chapter how you learned about building a class structure? extends is the keyword for saying that a class should be entered into that class hierarchy. In fact, a class that extends another class is placed at the bottom of the existing chain.

public class HelloApplet extends Applet {

See "Super Classes--Extending Another Class," Chapter 11

You may think this is harping the issue, but it's important: all applets must extend java.applet.Applet. However, because you imported the Applet class, you can simply call it Applet. If you had not imported java.applet.Applet, you could still have extended it using the full name:

public class HelloApplet extends java.applet.Applet {

Applet Methods--paint The next item to notice about the HelloApplet class versus HelloWorld is that HelloApplet doesn't have a main method. Instead, this applet only has a paint method. How is this possible? The answer lies in the fact that the applets don't start up themselves. They are being added to an already running program (the browser). The browser has a predefined means for getting each applet to do what it wants. It does this by calling methods that it knows the Applet has. One of these is paint.

public void paint (Graphics g) {

The paint method is called any time the browser needs to display the applet on the screen, so you can use the paint method to display anything. The browser helps out by passing a Graphics object to the paint method. This object gives the paint method a way to display items directly to the screen.

The next line shows an example of using the Graphics object to draw text to the screen:

     g.drawString ("Hello World!",0,50);
  }
}

The Brief Life of an Applet

The paint method is not the only method that the browser calls of the applet. You can override any of these other methods just like you did for the paint method in the HelloWorld example.

When the applet is loaded, the browser calls the init() method. This method is only called once no matter how many times you return to the same Web page.

After the init() method, the browser first calls the paint() method. This means that if you need to initialize some data before you get into the paint() method, you should do so in the init() method.

Next, the start() method is called. The start() method is called every time an applet page is accessed. This means that if you leave a Web page and then click the Back button, the start() method is called again. However, the init() method is not.

When you leave a Web page (say, by clicking a link), the stop() method is called.

Finally, when the browser exits all together the destroy() method is called.


NOTE: Notice that unlike the paint(Graphics g) method, the init(), start(), stop(), and destroy() methods do not take any parameters between the parentheses.


Keywords

Before you set off on a more in-depth exploration of each of the topics discussed in this chapter, there are a few other housekeeping matters you need to learn.

The most important of these is the use of keywords in Java. There are certain sequences of characters that have special meaning in Java; these sequences are called keywords. Some of them are like verbs, some like adjectives, some like pronouns. Some of them are tokens that are saved for later versions of the language, and one (goto) is a vile oath from ancient procedural tongues that may never be uttered in polite Java.

The following is a list of the 56 keywords you can use in Java. When you know the meanings of all these terms, you will be well on your way to being a Java programmer.
abstract boolean break byte
case cast catch char
class const continue default
do double else extends
final finally float for
future generic goto if
implements import inner instanceof
int interface long native
new null operator outer
package private protected public
rest return short static
super switch synchronized this
throw throws transient try
var void volatile while
The keywords byvalue, cast, const, future, generic, goto, inner, operator, outer, rest, and var are the reserved words that have no meaning in Java. Programmers experienced with other languages such as C, C++, Pascal, or SQL may know what these terms might eventually be used for. For the time being, you won't use these terms, and Java is much simpler and easier to maintain without them.

The tokens true and false are not on this list; technically, they are literal values for Boolean variables or constants.

The reason that you even care about keywords is that, because these terms have specific meaning in Java, you can't use them as identifiers for something else. This means that you can't create classes with any of these names. So if HelloApplet had been on the list, the compiler never would have compiled that program for you. In addition, they cannot be used as variables, constants, and so on. However, they can be used as part of a longer token, for example:

public int abstract_int;


NOTE: Because Java is case-sensitive, if you are bent on using one of these words as an identifier of some sort, you can use an initial uppercase letter. While this is possible, it is a very bad idea in terms of human readability, and it results in wasted manhours when the code must be improved later to this:

public short Long;




It can be done, but for the sake of clarity and mankind's future condition, please don't do it.


In addition, there are numerous Classes defined in the standard packages. While their names are not keywords, the overuse of these names may make your meaning unclear to future people working on your application or applet.

Using the API

In this chapter, you learned how to use several classes other than the one you were writing. The most important of these was java.applet.Applet.

How did I know to tell you what methods were in java.applet.Applet? The answer is that all the classes in what is known as the Java API are well documented. While it's unlikely that you will have great success understanding the API until you have finished reading several more chapters, it's important to start looking at it now.

As you progress as a Java programmer, the API will probably become one of your best friends. In fact, it may well be that Java's rich API is one of the reasons for its success.

You can access a hyperlink version of the API documentation on Sun's site at:

http://www.javasoft.com/products/JDK/CurrentRelease/api/

When exploring the API, you should begin to notice how various classes inherit from other ones using the extends keyword. Notice that Sun has done a great deal of work making it so you don't have to write nearly as much code if you learn to make good use of the classes.