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.
You have already seen the simplest Java program HelloWorld in Chapter 3, “Installing Java.” Now, take a closer look at each of the components. Listing 7.1 shows the HelloWorld application.
Listing 7.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.
The first step to create the HelloWorld application is to copy the text from listing 7.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).
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 7.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:
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.
Now that you have compiled the program, you can run it by typing at the command prompt:
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 the Hello World!! on the screen, go back and make sure you have typed in the file exactly as shown in listing 7.1, and make sure that you called the file HelloWorld.java.
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.
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.
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.
Next, notice the little curly brace ({) that is located after 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 9, “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 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 9, “Methods,” you learn more about declaring and using methods.
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.
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.
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 7.2 into a file called HelloWorld2.java and compile it with the line java HelloWorld2.java.
Listing 7.2 A HelloWorld 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:
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 7.3 into a file called HelloWorld3, compile, and run it.
Listing 7.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.
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 7.4).
Listing 7.4 HelloWorld 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 7.5 shows an example of just such a situation.
Listing 7.5 HelloWorld with a number.
public class HelloWorld5
{
public static void main
(String args[]){
System.out.print (“Hello
World! ” + 43);
}
}
Listing 7.5 produces the line:
Hello World! 43
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.
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 7.6 shows an example of a Java application that reads a letter from the user.
Listing 7.6 Read 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 7.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 (see Appendix E, “ASCII Character Set”).
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 7.7.
Listing 7.7 Read 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.
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.
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.
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.
One of the simplest applets is the HelloWorld applet, the source code for which is shown in listing 7.8. Right away you should see that the applet HelloWorld is quite different from the HelloWorld application in listing 7.1. In a few sections, you break down the source code in order to understand it. For now, copy listing 7.8 into a file called HelloApplet.java and compile it.
Listing 7.8 HelloWorld 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);
}
}
When you created the HelloWorld application in listings 7.1–7.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 7.10. Copy this text into a file called HelloApplet.html.
Take a look at the third line of listing 7.10. 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.
Listing 7.10 HelloApp.html—HTML file to use
for Applet.
<HTML>
<BODY>
<APPLET CODE=“HelloApplet.class”
WIDTH = 200 HEIGHT=200> </APPLET>
</BODY>
</HTML>
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 7.1. To run the HelloApplet program using Appletviewer, on the command line type:
Appletviewer opens a new window and runs HelloApplet in it.
Another option for running applets is with Netscape Navigator. Your
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 7.2.
HelloApplet can also be run by using Netscape Navigator.
Now that you have seen how to run the HelloApplet program, let’s go back and see how the program works.
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.
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 {
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 {
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 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.
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.
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:
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.
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 a 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:
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.
| Previous Chapter | Next Chapter |
| Que Home Page | Digital Bookshelf | Disclaimer |
To order books from QUE, call us at 800-716-0044 or 317-361-5400.
For comments or technical support for our books and software, select Talk to Us.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.