ptg7068951
When you run a Java application, the Java Virtual Machine (JVM) looks for a main()block and starts handling Java statements within that block. If your LISTING 4.1 The Full Text of Root.java
1: class Root {
2: public static void main(String[] arguments) { 3: int number = 225;
4: System.out.println(“The square root of “ 5: + number
6: + “ is “
7: + Math.sqrt(number) 8: );
9: } 10: }
The Rootapplication accomplishes the following tasks:
. Line 3: An integer value of 225 is stored in a variable named number. . Lines 4–8: This integer and its square root are displayed. The
Math.sqrt(number)statement in Line 7 displays the square root.
If you have entered Listing 4.1 without any typos, including all punctua- tion and every word capitalized as shown, you can run the file in NetBeans by choosing Run, Run File. The output of the program appears in the out- put pane, as shown in Figure 4.1.
Output Pane FIGURE 4.1
The output of the Rootapplication.
ptg7068951
Sending Arguments to Applications 41
Sending Arguments to Applications
You can run Java applications from a command line using java, a program that invokes the JVM. NetBeans uses this program behind the scenes when you run programs. When a Java program is run as a command, the JVM loads the application. The command can include extra items of informa- tion, as in this example:
java TextDisplayer readme.txt /p
Extra information sent to a program is called an argument. The first argu- ment, if there is one, is provided one space after the name of the applica- tion. Each additional argument also is separated by a space. In the preced- ing example, the arguments are readme.txtand /p.
If you want to include a space inside an argument, you must put quotation marks around it, as in the following:
java TextDisplayer readme.txt /p “Page Title”
This example runs the TextDisplayer program with three arguments:
readme.txt, /p, and “Page Title”. The quote marks prevent Pageand Titlefrom being treated as separate arguments.
You can send as many arguments as you want to a Java application (within reason). To do something with them, you must write statements in the application to handle them.
To see how arguments work in an application, create a new class in the Java24 project:
1. Choose File, New File.
2. In the New File Wizard, choose the category Javaand file type Empty Java File.
3. Give the class the name BlankFillerand click Finish.
Enter the text of Listing 4.2 in the source code editor and save it when you’re done. Compile the program, correcting any errors that are flagged by the editor as you type.
LISTING 4.2 The Full Text of BlankFiller.java 1: class BlankFiller {
2: public static void main(String[] arguments) { 3: System.out.println(“The “ + arguments[0]
4: + “ “ + arguments[1] + “ fox “
ptg7068951
5: + “jumped over the “ 6: + arguments[2] + “ dog.”
7: );
8: } 9: }
This application compiles successfully and can be run, but if you try it with the menu command Run, Run File, you get a complicated-looking error:
Output▼
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0 at BlankFiller.main(BlankFiller.java:3)
This error occurs because the program expects to receive three arguments when it is run. You can specify arguments by customizing the project in NetBeans:
1. Choose the menu command Run, Set Project Configuration, Customize. The Project Properties dialog opens.
2. Enter BlankFillerin the Main Class text field.
3. In the Arguments field, enter retromingent purple lactose- intolerantand click OK.
Because you’ve customized the project, you must run it a little differently.
Choose the menu command Run, Run Main Project. The application uses the arguments you specified as adjectives to fill out a sentence, as shown in the following output:
Output▼
The retromingent purple fox jumped over the lactose-intolerant dog.
Return to the Project Properties dialog and designate three adjectives of your own choosing as arguments, making sure to always include at least three.
Arguments are a simple way to customize the behavior of a program. The arguments are stored in a type of variable called an array. You learn about arrays during Hour 9, “Storing Information with Arrays.”
Creating an Applet
When the Java language was introduced, the language feature that got the LISTING 4.2 Continued
ptg7068951
Creating an Applet 43
run them in any web browser that handles Java programs and test them with appletviewer, a tool included in the JDK that’s supported in NetBeans.
The structure of applets differs from applications. Unlike applications, applets do not have a main()block. Instead, they have several sections that are handled depending on what is happening in the applet. Two sections are the init()block statement and the paint()block. init()is short for initialization, and it is used to take care of anything that needs to be set up as an applet first runs. The paint()block is used to display anything that should be displayed.
To see an applet version of the Rootapplication, create a new empty Java file with the class name RootApplet. Enter the code in Listing 4.3 and make sure to save it when you’re done.
LISTING 4.3 The Full Text of RootApplet.java 1: import java.awt.*;
2:
3: public class RootApplet extends javax.swing.JApplet { 4: int number;
5:
6: public voidinit() { 7: number = 225;
8: } 9:
10: public voidpaint(Graphics screen) {
11: Graphics2D screen2D = (Graphics2D) screen;
12: screen2D.drawString(“The square root of “ + 13: number +
14: “ is “ +
15: Math.sqrt(number), 5, 50);
16: } 17: }
This program contains many of the same statements as the Rootapplica- tion. The primary difference is in how it is organized. The main()block has been replaced with an init()block and a paint()block.
When you run the program in NetBeans (choose Run, Run File), the applet loads in the appletviewer tool, as shown in Figure 4.2.
Applets are slightly more complicated than applications because they must be able to run on a web page and coexist with other page elements in a browser. You learn how to create them in Hour 17, “Creating Interactive Web Programs.”
NOTE
The sample programs in this hour are provided primarily to introduce you to the way Java programs are structured. The main purpose of this hour is to get the programs to compile and see how they function when you run them. Some aspects of the programs will be introduced fully in the hours to come.
ptg7068951 The appletviewer tool is useful for testing, but it gives the wrong impres-
sion about applets. They don’t run in their own windows as Java applica- tions. Instead, they’re placed on web pages as if they are text, photos, or graphics. The applet is presented seamlessly with the rest of the page.
Figure 4.3 shows RootAppleton a web page. The applet window is the white box that displays the program’s output: the square root of 225. The heading, paragraphs of text and lightbulb photo are ordinary elements of a web page.
Java applets can be static like the output of this project, but that’s a com- plete waste of the language. Applets usually display dynamic content as in a stock ticker, chat room client, or video games.
FIGURE 4.2
TheRootAppletapplet running in appletviewer.
FIGURE 4.3
TheRootAppletapplet on a web page loaded in the Google Chrome browser.
ptg7068951
Summary 45
Summary
During this hour, you had a chance to create both a Java application and an applet. These two types of programs have several important differences in the way they function and the way they are created.
The next several hours continue to focus on applications as you become more experienced as a Java programmer. Applications are quicker to test because they don’t require you to create a web page to view them; they can be easier to create and more powerful as well.
ptg7068951
Q&A
Q. Do all arguments sent to a Java application have to be strings?
A. Java stores all arguments as strings when an application runs. When you want to use one of these arguments as an integer or some other non- string type, you have to convert the value. You learn how to do this dur- ing Hour 11, “Describing What Your Object Is Like.”
Q. If applets run on web pages and applications run everywhere else, what are Java programs launched by Java Web Start?
A. Java Web Start is a way to launch Java applications from a web browser.
A user clicks a link on a web page to run the program, which is easier than downloading it, running an installation wizard, and starting it like any other desktop software.
Although they’re run from a browser, Java Web Start programs are applica- tions instead of applets. The application’s always up-to-date because it’s retrieved over the web from the program’s provider every time it is run.
Google Web Toolkit (GWT), a set of opensource tools for web programming, can convert a Java program into JavaScript, making it run faster and more reliably in web browsers without requiring a Java virtual machine.
Q. Does the line of succession to the British throne run out at some point?
A. Under Parliamentary law that has been in place since 1701, the British monarch must be a Protestant descendant of Sophia of Hanover, a German princess who was the heiress to the crown when the law was passed.
There are a finite number of people who are descendants of Sophia, so there’s always somebody last in the regal line. The British government only lists the first 38, so genealogists have attempted to fill out the rest of the list themselves.
The last person in the line of succession is Karin Vogel, a German pain therapist in her thirties. She was 4,973rd in line as of 2001, genealo- gists determined after an exhaustive search that took years. So if all the people ahead of her drop out of the running (to, say, spend more time learning Java programming), Vogel takes over the mortgage of Buckingham Palace and becomes Her Majesty Karin the First.
Vogel is Sophia’s great-great-great-great-great-great-great-great-grand- daughter. She told the Wall Street Journal that becoming monarch would be “too stressful.”
If by the time you read this Prince William and Princess Kate have pro- duced a Protestant child, Vogel drops to 4,974.
ptg7068951
Workshop 47
Workshop
Test your knowledge of the material covered in this hour by answering the fol- lowing questions.
Quiz
1. Which type of Java program can be run inside a browser?
A. Applets B. Applications C. None
2. What does JVM stand for?
A. Journal of Vacation Marketing B. Jacksonville Veterans Memorial C. Java Virtual Machine
3. If you get into a fight with someone over the way to send information to a Java application, what are you doing?
C. Struggling over strings B. Arguing about arguments C. Feudin’ for functionality
Answers
1. A.Applets run as part of a web page, whereas applications are run everywhere else.
2. A, B, or C.Trick question! The initials stand for all three things, though Java Virtual Machine is the one you need to remember for the next 20 hours.
3. B.Applications receive information in the form of arguments. Can’t we all just get along?
ptg7068951
Activities
If you’d like to apply your acumen of applets and applications, the following activities are suggested:
. Using the Root application as a guide, create a NewRoot application that can display the square root of 625.
. Using the Root application as a guide, create a NewRoot application that can display the square root of a number submitted as an argument.
To see a Java program that implements each of these activities, visit the book’s website at www.java24hours.com.
ptg7068951 WHAT YOU’LL LEARN IN
THIS HOUR:
.Creating variables
.Using the different types of variables
.Storing values into variables
.Using variables in mathe- matical expressions .Storing one variable’s value
into another variable .Increasing and decreasing
a variable’s value In Hour 2, “Writing Your First Program,” you used a variable, a special stor-
age place designed to hold information. The information stored in vari- ables can be changed as a program runs. Your first program stored a string of text in a variable. Strings are only one type of information that can be stored in variables. They also can hold characters, integers, floating-point numbers, and objects.
During this hour, you learn more about using variables in your Java programs.
Statements and Expressions
Computer programs are a set of instructions that tell the computer what to do. Each instruction is called a statement. The following example from a Java program is a statement:
int highScore = 450000;
You can use brackets to group a set of statements together in a Java pro- gram. These groupings are called block statements. Consider the following portion of a program:
1: public static void main(String[] args) { 2: int a = 3;
3: int b = 4;
4: int c = 8 * 5;
5: }
Lines 2–4 of this example are a block statement. The opening bracket on Line 1 denotes the beginning of the block, and the closing bracket on Line 5 denotes the end of the block.
HOUR 5