Understanding How Java Programs Work - Getting Started - Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Part I: Getting Started

Hour 4. Understanding How Java Programs Work

THIS HOUR’S TO-DO LIST:

Image Learn how applications work.

Image Structure an application.

Image Send arguments to an application.

Image Learn how Java programs are organized.

Image Use the Java Class Library.

Image Create an object in an application.

An important distinction to make in Java programming is where your program is supposed to be running. Some programs are intended to work on your computer. Other programs are intended to run as part of a web page.

Java programs that run locally on your own computer are called applications. Programs that run on web pages are called applets, programs that are run by web servers are called servlets, and programs that run on mobile devices are called apps.

During this hour, you will create an application and run it on your computer.

Creating an Application

The Saluton program you wrote during Hour 2, “Writing Your First Program,” is an example of a Java application. The next application you create calculates the square root of a number and displays the value.

With the Java24 project open in NetBeans, begin a new application:

1. Choose File, New File. The New File Wizard opens.

2. Choose the category Java and the file type Empty Java File and then click Next.

3. Enter the class name Root.

4. Enter the package name com.java24hours.

5. Click Finish.

NetBeans creates Root.java and opens the empty file in the source editor so you can begin working on it. Enter everything from Listing 4.1, remembering not to enter the line numbers and colons along the left side of the listing. The numbers are used to make parts of programs easier to describe in the book. When you’re done, save the file by clicking the Save All button on the toolbar.

LISTING 4.1 The Full Text of Root.java


1: package com.java24hours;
2:
3: class Root {
4: public static void main(String[] arguments) {
5: int number = 225;
6: System.out.println("The square root of "
7: + number
8: + " is "
9: + Math.sqrt(number)
10: );
11: }
12: }


The Root application accomplishes the following tasks:

Image Line 1—The application is placed in the com.java24hours package.

Image Line 5—An integer value of 225 is stored in a variable named number.

Image Lines 6–10—This integer and its square root are displayed. The Math.sqrt(number) statement in Line 9 displays the square root.

If you have entered Listing 4.1 without any typos, including all punctuation 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 Output pane, as shown in Figure 4.1.

Image

FIGURE 4.1 The output of the Root application.

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 program does not have a main() block, the JVM responds with an error.

The statement Math.sqrt(number) in line 9 demonstrates a built-in capability of the Java language—the capability to determine the square root of a number. There is a Java program named Math that has a method called sqrt() to find a specified number’s square root.

The Math program is part of the Java Class Library, which you explore later this hour.

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 information, as in this example:

java TextDisplayer readme.txt /p

Any extra information sent to a program is called an argument. The first argument, if there is one, is provided one space after the name of the application. Each additional argument also is separated by a space. In the preceding example, the arguments are readme.txt and /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 quotation marks prevent Page and Title from 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 Java and file type Empty Java File.

3. Give the class the name BlankFiller, the package com.java24hours, and 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: package com.java24hours;
2:
3: class BlankFiller {
4: public static void main(String[] arguments) {
5: System.out.println("The " + arguments[0]
6: + " " + arguments[1] + " fox "
7: + "jumped over the "
8: + arguments[2] + " dog."
9: );
10: }
11: }


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:5)

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 com.java24hours.BlankFiller in the Main Class text field.

3. In the Arguments field, enter retromingent purple lactose-intolerant and 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 Figure 4.2.

Image

FIGURE 4.2 The output of the BlankFiller application.

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.”

The Java Class Library

This book explains how to use the Java language to create your own programs from scratch. You learn all the keywords and operators that form the language and then put them to work writing statements that make a computer do interesting and useful things.

Although this approach is the best way to learn Java, it’s a bit like showing someone how to build a car by making her build every part of the car from scratch first.

A lot of work already is done for you as a Java programmer, provided you know where to look for it.

Java comes with an enormous collection of code called the Java Class Library you can utilize in your own programs. This library is a collection of thousands of classes, many of which can be used in the programs that you write.


Note

There are many more class libraries provided by other companies and organizations. The Apache Project, the creators of the Apache web server, has more than a dozen Java open source projects. One is HttpComponents, a set of classes for creating web servers, clients, and crawlers in Java.

For more information on the project, visit http://hc.apache.org. To see all of Apache’s Java projects, visit http://projects.apache.org.


The classes can be put to work in your programs in a manner somewhat similar to using a variable.

A class is used to create an object, which is like a variable but far more sophisticated. An object can hold data, like a variable does, and also perform tasks, like a program.

Oracle offers comprehensive documentation for the Java Class Library on the Web at http://download.java.net/jdk8/docs/api. This page is shown in Figure 4.3.

Image

FIGURE 4.3 The Java Class Library documentation.

Java classes are organized into packages, which serve a similar function to a file folder on a computer. The programs you have created thus far belong to the com.java24hours package.

The home page for the documentation is divided into frames. The largest frame lists all of the packages that compose the Java Class Library, along with a description of each one.

The names of the packages help describe their purpose. For instance, java.io is a set of classes for input and output from disk drives, Internet servers, and other data sources; java.time contains classes related to times and dates; and java.util collects helpful utility classes.

On the documentation home page, in the largest frame is a list of packages with a short description of each one. Click the name of a package to learn more about it. A page loads listing the classes in the package.

Each class in the Java Class Library has its own page of documentation on this reference site, which consists of more than 26,000 pages. (You don’t have to read all of them now, or ever.)

For this hour’s final project, you will poke around the library and use an existing Java class to do some work for you.

The Dice program uses the Random class in the java.util package, which can be used to create random numbers.

The first thing you do in the program to use this class is import its package with this statement:

import java.util.*;

This makes it possible to refer to the Random class without using its full name, which is java.util.Random. Instead, you can simply refer to it as Random. The asterisk makes it possible to refer to all classes in a package by their shorter names.

The Random class is a template that can be used to create Random objects. To create one, use the new keyword followed by the name of the class and parentheses:

Random generator = new Random();

This creates a variable named generator that holds a new Random object. The object is a random-number generator that can produce one or more random numbers.

For this program, the object’s nextInt() method will be employed to produce a random integer value:

int value = generator.nextInt();

Integers in Java range from –2,147,483,648 to 2,147,483,647. The generator chooses one of these numbers at random and it is assigned to the value variable.

Without the Random class from the Java Class Library, you’d have to create your own program to produce random numbers, which is a highly complex task. Random numbers are useful in games, educational programs, and other programs that must do something randomly.

In NetBeans create a new empty Java file, name it Dice, and put it in the package com.java24hours. When the source code editor opens, enter the text of Listing 4.3 into that window and then click the Save button (or choose the menu command File, Save).

LISTING 4.3 The Full Text of Dice.java


1: package com.java24hours;
2:
3: import java.util.*;
4:
5: class Dice {
6: public static void main(String[] arguments) {
7: Random generator = new Random();
8: int value = generator.nextInt();
9: System.out.println("The random number is "
10: + value);
11: }
12: }


Run the program by choosing Run, Run File. The output is shown in Figure 4.4, although your number will be different. (Actually, there’s a one-in-four billion chance it will be the same number, which is even worse odds than a lottery.)

Image

FIGURE 4.4 The output of the Die program.

You now have a randomly selected integer to call your own. Take good care of it.

The Random class, like all classes in the Java Class Library, has extensive documentation you can read on Oracle’s site. It describes the purpose of the class, the package it belongs to, how to create an object of this class, and what methods it has that can be called to make it do something.

Follow these steps to see this documentation:

1. In your web browser, load the page http://download.java.net/jdk8/docs/api.

2. In the main frame, scroll down until you see the link to the package java.util. Click this link. Documentation for the package is displayed.

3. In the main frame, scroll down and click the Random link.

As a Java programmer with slightly under four hours’ experience, you likely will find the documentation to be mind-bendingly tough to understand. Don’t panic. It’s written for experienced programmers.

But as you read this book and become curious about how Java’s built-in classes are being used, you can get some value from looking at the official documentation for a class. One way to use it is to look up the methods in that class, each of which performs a job.

On the Random documentation, you can scroll down to the explanation for the nextInt() method, which was used on line 8 of Listing 4.3. Figure 4.5 shows this section of the page.

Image

FIGURE 4.5 Oracle’s documentation for the Random class.


Note

All the Java classes this book covers are described within its pages, so the online documentation is not required to progress through these 24 hours and become a Java programmer. Because the classes used in this book have many additional features beyond what an introductory book can cover, the Java Class Library documentation can supplement your learning.


Summary

During this hour, you had a chance to create a Java program, send arguments to a program, and make use of existing programs in the Java Class Library.

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 do any extra work to run them, as you do for the other kinds of programs.

This hour is the first of several that discuss how to make use of objects in a Java program. You will return to this subject in Hour 10, “Creating Your First Object.”

Workshop

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 nonstring type, you have to convert the value. You learn how to do this during 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 applications instead of applets. The application is 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 open source 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 at all.

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 lists only 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, genealogists 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-granddaughter. She told the Wall Street Journal that becoming monarch would be “too stressful.”

With the birth of Prince William and Princess Kate’s son, George, more officially known as His Royal Highness Prince George Alexander Louis of Cambridge, Vogel dropped to 4,974.

Quiz

Test your knowledge of the material covered in this hour by answering the following questions.

1. Which type of Java program can be run by 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?

A. 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?

Activities

If you’d like to apply your acumen of applications, the following activities are suggested:

Image Using the Root application as a guide, create a NewRoot application that can display the square root of 625.

Image Using the Root application as a guide, create a NewRoot application that can display the square root of a number submitted as an argument.

Solutions for the activities in this book are presented on the book’s website at www.java24hours.com.