Hour 12. Programming with Java

The Java language is a shapeshifter that has been used for three dramatically different purposes in its nearly 20-year history.

First, it was a simple language perfectly suited to run on embedded devices like appliances and as small programs embedded on web pages.

Next, it grew into a sophisticated general-purpose language that ran on web servers, powering websites, relational databases, and other Internet servers behind the scenes.

Finally, it has become a mobile language for creating apps, small programs that run on phones and tablets using the Android operating system. There are a staggering number of devices in the world running Java programs—more than three billion—and many of them are the phones we carry with us all day long.

For this introductory hour, it will be most instructive to go back to Java’s roots and see how it got started as a killer way to add some interactivity to the web.

The world of web pages gained an unexpected boost in capabilities when the Java language was introduced in 1995. Originally designed to be used for such devices as digital TV set-top boxes, Java became the first widely available language used to make web pages dynamic with animation, games, and other constantly updated content. Java almost single-handedly rescued static web pages and turned the web into an interactive medium where users could interact with changing web pages.

Though today there are many other ways to make the web more interactive, including Macromedia Flash and HTML5, Java still can be used to create web pages that run like standalone computer programs. Despite its capabilities, Java is simple to learn. The inventors of Java used C and C++ as their model language. Java is no longer a small language, but it is an extremely robust one for creating programs that work without modification on many different kinds of computers, phones, tablets, and other devices.

The highlights of this hour include

Image Seeing what Java is all about

Image Running Java programs that travel with web pages

Image Understanding the need for small Java programs

Image Comparing Java to other languages

Image Compiling Java programs

Image Extending the built-in Java classes for your Java programs

Introducing Java

Colorful web browsers brought the Internet to the world by taking it out of the exclusive hands of scientific, military, and educational researchers. The new web browsers made the Internet accessible to everybody with simple navigational tools and an appealing graphical nature. Soon, millions of users all over the world were jumping from one website to another in a global medium of text, images, and hyperlinks.

Browsers filled the job requirements better than anyone could have imagined but grew stale due to the static nature of web pages. Despite the colorful and cross-linked pages that browsers made available to the world, the pages did not have enough action in them to keep users occupied. Browser technology was too static to make websites truly come alive.


Note

Think about this: As PCs became faster, became more graphical, and began supporting multimedia, viewing only pictures and text, which was at first unique online, became dull quickly. Users needed more interaction to keep their attention when online.


Users wanted more from the Internet than just a distributed set of interconnected graphical screens. Despite the web’s hypertext nature, those hypertext links simply take you from one page to another without doing any work for you except eliminating the need to type long web page addresses. Users want real computing power coming at them from the websites they visit. For example, instead of reading cooking recipe, you might want to see the food being cooked by an expert or take an introductory, graphical tutorial on the steps required to make that food.

Java, developed by Sun Microsystems in the mid-1990s and managed today by Oracle by virtue of its acquisition of Sun in 2010, changed the way that websites operate. Java is a programming language with language features similar to C++. Fortunately, Java also contains many language features that are similar to JavaScript, such as the for loop, the if statement, and the while loop.


Java’s Overnight Success

Upon its launch in 1995, Java was designed to be a better C++ than C++. Both C++ and Java are efficient programming languages that you can use to write almost any computer application. Java’s initial emphasis, though, was online Internet programming. Java was a small and efficient language with safeguards in place to add security to online programs that C++ simply couldn’t handle.

Today, Java works in many environments; some programmers develop large, complex applications in Java, and those applications have nothing to do with the Internet. Because Java was a lot like the C++ language already in use, this helped to ensure a rapid acceptance and usage within the programming world.


Instead of using web browsers to view data, with Java capabilities, browsers now can seamlessly download programs written in Java and execute those programs on the end user’s computer as opposed to the remote server serving up the web page. When you view a Java-enabled web page, you see not only the usual graphical page, but you also are able to interact with Java programs that run on your own computer, brought to your computer via the web’s connection.

You can write four kinds of Java programs:

Image Java applets are small programs that travel with web page code and execute on the web user’s computer.

Image Java applications are complete standalone programs that don’t require a web browser to execute.

Image Java servlets are programs that run on a web server and are delivered to users as web pages.

Image Java apps are small programs that run on smartphones and other mobile devices that have the Android operating system.

The first Java programs appeared as Java applets. The original goal of Java was to place executable code on web pages so that users could interact with websites in more compelling and attention-getting ways. As Java became more popular, programmers began using Java to write standalone programs that executed without the need for web browsers. For example, if you want to write a rental property management application that runs independently of an Internet connection, you could select Java as the programming language you use to develop the application.

Figure 12.1 shows a web page in which someone has embedded a Java applet. When the user surfs to the web page, the web page appears and a moment or two later the spaceship starts descending toward the surface of the moon. Web page authors create web pages using a formatting language called HTML (HyperText Markup Language). The applet rides from the server to the user’s computer via the web page’s HTML code. The applet actually executes on the user’s computer and not on the serving computer. By executing on the user’s machine, as opposed to the server’s machine, the user can interact with the Java applet and the applet can respond to the user in real time.

Image

FIGURE 12.1 It’s the Java applet that gives the spaceship the fuel needed to move.


Note

This applet by John Donohue recreates the early videogame Lunar Lander, released by Atari in 1979. Gamers today might find it hard to believe, but back then this was the state of the art in arcade games. We’d pump coin after coin into this game trying to fight gravity’s cruel arithmetic and land safely by mastering four movements: tilt left, tilt right, flatten out, and fire the thrusters.

A program that used to require a giant arcade console now can be implemented as a Java applet.

To play the game, visit www.jdonohue.com/java.


Java Provides Executable Content

When working with Java, you’ll often hear and read about executable content. Executable content is what Java is really all about. A web page contains executable content via web commands in the form of a Java applet. Any web page’s content is executable on the target user’s computer. Figure 12.2 shows an overview of a web document with two embedded Java applets. The language behind web pages is called HTML and you’ll learn more about HTML in Hour 16, “HTML5 and CSS3.”

Image

FIGURE 12.2 HTML serves up Java’s executable content.

When the user enters the URL that displays the page shown in Figure 12.2 (or when the user clicks hypertext links to navigate to the page), the user’s web-browsing software loads the HTML code, formats the page’s text according to the HTML commands, displays any graphics images that appear on the page, and loads the executable content (as applets). The executable content executes either immediately or upon a predetermined event, such as a mouse click on the web page.

The best method of running Java applets is not always obvious to the user. When an applet is providing animation, the look of that animation is smooth because the animation program runs on the user’s computer. Because of the applet, the speed of the animation is not dependent on the download time or on Internet traffic.

Before Java-enabled web pages, the user did have some interaction with the remote site. However, that interaction was severely limited. Web page animation was controlled by the user’s animation software. If a computer system had no software that could display animation, that feature of the web page was lost for that system’s user. If the user was to interact with the remote site in a question–answer session, such as order-taking, the user would often have to fill in the form completely before error-checking could be done to any of the user’s responses. The user would have to trigger any and all interactions with the remote site; the response would then be limited to the remote site’s speed and the current traffic flow on the Internet.


Note

The first way that web pages took user input was through simple forms that were transmitted using the CGI (Common Gateway Interface). When you go to a website’s Contact Us page and you use the form to provide your name, email address, and a comment then click a Send button to submit it, there’s a program collecting and transmitting that information with the CGI.

These programs are not usually Java applets. But some of them might be servlets, the programs mentioned earlier that are run by web servers.


Seamless Execution

Surely you have traveled to a website, downloaded software, and then logged off to execute that software. Java applets do this without requiring that you ever leave your browser. When you travel to a remote site, the Java applet runs without you doing anything at all. In addition, the software applet automatically downloads itself to your PC, runs when you trigger its execution, and then goes away when you leave the website without taking up permanent disk space. Think of the possibilities for software developers; users can test-drive your software without running an installation program and without needing to remove the software when the demonstration concludes.

Multi-Platform Executable Content

Now that you’ve seen how Java-enabled websites appear to the user, think about the requirements of such executable content. When you write a Java-based web page, you want the code to work on the user’s computer no matter what kind of computer the user operates.

Whereas most language compilers, such as Visual C++, turn programs into machine-dependent executable programs, Java development tools don’t go quite that far. All Java compilers translate your Java code into a special machine-independent module. The Java compiler first compiles the code into an in-between stage called bytecode. Your Java-enabled web-browsing software then translates this compiled bytecode into instructions that your computer executes.

No computer can directly read bytecode, but each computer’s Java-enabled browser can. In other words, given a Java applet’s bytecode, a PC can run the applet using a web browser, and an Android tablet can run that very same bytecode by using its own Java-enabled browser. All modern browsers can run Java applets with an enhancement offered by Oracle called the Java Plug-in, including Google Chrome, Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari. The Java Plug-in is a computer-within-a-computer called the Java Virtual Machine (JVM) that interprets the machine-dependent bytecode and then translates that bytecode into machine-specific instructions a particular computer can understand (see Figure 12.3).

Image

FIGURE 12.3 Your Java session produces compiled bytecode that a computer’s JVM translates to run the program.


Running Java on the Virtual Machine

Figure 12.3 shows the Java compilation/translation scenario. You’ll use the Java language to produce bytecode for a virtual machine, not a specific machine, because the bytecode is machine independent. The JVM is not a particular kind of computer but is an imaginary computer. Each computer must have a virtual machine interpreter to run Java code. The interpreter translates the compiled bytecode into specific instructions for that computer. Therefore, the Java compiler doesn’t have to compile for any one computer, just bytecode for the virtual machine. The bytecode is sent to the web page that is to contain the applet, and when the user requests that web page, the user’s web browser reads the bytecode and automatically interprets the bytecode into code readable by the user’s computer. The user is unaware that all this took place; the web page is displayed and the executing applet is seen along with the rest of the web page’s content.


The web browser automatically runs the Java applet. Some applets run automatically, and some run in response to a user event such as a mouse click. It’s important that you realize that the user doesn’t necessarily know or care that a small program is running. To the user, the Java-based web page simply does more than one without Java. The page usually responds much more quickly, as fast as the user’s computer can translate the Java bytecode into executable content. All traces of the program then go away when the applet ends, or when the user leaves the web page.

All Java programs are compiled into bytecode and run by a JVM on a user’s computer. If you design a program with Java that must be downloaded and installed by a user, it requires a virtual machine on that computer. Oracle has a website where people can see if they have one installed. Visit www.java.com in a web browser and look for a “Do I Have Java?” link.

Java Usage Summary

As a newcomer to Java technology, you might appreciate a summary of the process one goes through when viewing a Java-enabled web page with a Java-aware web browser. Here are the steps that occur:

1. In a web browser, you enter a Java-enabled website’s URL.

2. The serving computer sends the web page, in HTML format, to your web browser.

3. The HTML-based document’s commands inform your web browser of the web page’s Java-based executable content.

4. Your web browser downloads graphics images from the server if any graphics appear on the web page.

5. Depending on how the Java applet is to be triggered (either automatically or by a user’s event), the server also will send the bytecode to your computer when the time is right.

6. Your browser’s Java Plug-in interprets the bytecode and executes the Java-executable content.

7. When you leave the web page, the executable content goes away. (Some web browsers will keep the Java code in memory for a while in case you return to the page.)

Because the previous steps were based on the user’s perspective, this is also a good time to explain what you, the Java programmer, will go through to create web pages with Java applets. Here are the general steps you’ll follow:

1. Start your Java programming environment.

2. Write the Java applet.

3. Create the HTML web page that will contain the Java applet. Use appropriate HTML commands to indicate the applet and its parameters.

4. Compile the Java applet. Your Java development environment may offer a way to place the applet in its appropriate location for the HTML web page that will contain the applet.

5. If the compiler finds errors, fix them and recompile the file.

6. Test and debug the applet.

7. Store the applet and HTML on your web server, where they await a user’s request.

You’ll Start with Standalone Java

Although up to this point you’ve learned about Java applets rather than for standalone applications, you won’t be learning Java from the applet perspective just yet. You’ll find that it’s easier to learn Java by mastering the standalone Java language first and then moving to applets, which you’ll do in Hour 15, “Applets and Web Pages.” While learning the Java language, the web page information would simply sidetrack you from mastering the language commands.

The Java language wasn’t originally intended to be a competitor to C++ and the other languages people use to write non-web, standalone applications, but Java has surpassed its authors’ hopes and dreams and become a major competitor in the programming language field.

Developers quickly learned that Java is a great language in its own right. Standalone Java applications run from a program window and not from a web browser as Java applets do. A Java application looks and acts just like any application written in any traditional programming language.


When Is Java Not Java?

Although JavaScript and Java have similar names and a few commands and operators overlap, JavaScript is little like Java. Even though both work inside the HTML of web pages, add interactivity to web pages, and share some language elements, JavaScript is deployed differently than Java and generally serves different purposes.

JavaScript began as a small language with which you can cause buttons and other web page elements to move and change as the mouse is clicked and keys are pressed. JavaScript also enables you to create menus and other web page interactive features. It later was put to use creating Asynchronous JavaScript and XML (AJAX) applications that function like static web pages but pull data dynamically in response to user input. But you cannot write JavaScript applications that stand by themselves outside of the web pages encompassing them. Java is a more powerful, complex language that can be used on full-blown standalone applications or applets.


Java’s Interface

Java’s interface elements—items such as check boxes and command buttons—can take on different appearances to match different computer platforms or can look the same on all of them. This is called the program’s look and feel. Programs can look the same on Macs as they do on Windows computers. When other languages are used (such as C++), interface elements typically take on the parent computer’s operating system style. If you really want your Java programs to achieve the specific look of a particular operating system, such as a Microsoft Windows 8 operating system, you can designate a look and feel for your program that takes on the operating system’s style.

Over time, Java has become even more portable across different kinds of hardware. With each major release (eight so far), the Java language grows, adding a richer set of supporting libraries so you code less and get more done faster. Using these libraries, programmers can more easily maintain Java software because less coding means less work when a change must be made to a program. Java includes support a fantastic library called Swing that lets you place windows, dialog boxes, and other graphical user interface elements in a program without much effort. Of course, you could ignore Swing and do it all the hard way and not get any sleep. But by taking advantage of Swing, you’ll put interactive code together faster.

Just look at some of the standard features found in Java that aren’t available in some languages:

Image Drag and drop—Enables users to move items from one screen location or program to another by dragging those items with the mouse.

Image Sound—Adds sound effects to spice up your programs.

Image Network support—Allows access to other computers on a user’s network after getting proper security clearance from the user.

Image Collections—Stores data in advanced data structure repositories such as linked lists.

Image 2D and 3D graphics—Dazzles the audience with eye-catching creations.

Image Database API—An API is an acronym for Application Programming Interface (programmers never use easy words when hard ones sound smarter) and Java supports Java Database Connectivity (JDBC), a heavy-duty database API that enables your code to access, report, and retrieve from a data source such as a company database.

Image Timers—Enables you to drop time-keeping routines into your programs that produce timed input responses, clocks, calendars, and other time-related operations.

Security Issues

Security should always be your concern when writing programs run over the Internet. In practice, Java-enabled applets can be prone to security problems if the proper precautions aren’t in place. After all, when you visit a Java-enabled web page, you aren’t always sure if an applet is running or what exactly an applet is trying to do to your computer’s disk or memory.

Fortunately, Java was designed to be a network-based programming language. Therefore, security is inherent in the language, both for the developer and for the Internet user. What follows are some of the default security-related protections built into the Java language:

Image A Java applet is not allowed to venture into the user’s memory areas where it doesn’t belong.

Image A Java applet cannot create, read, rename, copy, or write files on the user’s file system.

Image A Java applet cannot connect to additional machines on the user’s network.

Image A Java applet cannot call system routines on the user’s system.


Caution

You can locally load and run a Java applet from your own browser by loading an applet from your own disk drive or network. In the case of a locally loaded applet, the applet generally has permission to read and write to the local file system. In addition, some applet viewers do let the user specify a list of files that a web applet can access.


As you can see, Java developers do understand the need for security, and the most obvious security footholds are barred from an applet’s access. As more people write Java applets, additional security concerns are sure to enter into the picture.

Java changes as technology and computers change. Modern Java compilers support all the modern security methods such as digital signatures (signing documents online), public and private keys (encryption of data to hide it from others), and site certificates whereby your web browser checks to ensure the software is valid and certified to be safe.

Give Java a Spin

Now that you know more about Java, you can take a look at a Java-enabled web page. Use a browser to locate this website: www.javaonthebrain.com/java/cars.

When you go to this website, if your browser has the Java Plug-in, you quickly see the splash screen of a puzzle game developed by Karl HImagernell called Autocrazy. Figure 12.4 shows the web page and the puzzle game being played.

Image

FIGURE 12.4 Java applets can enliven a web page.

The game loads automatically, displaying a splash page animation of cars moving around an insanely crowded and disorganized parking lot. Click the Play button to see the cars arranged in a puzzle where a user controls the movement of each vehicle. Click a car to move it in forward (the front half) or reverse (the back), if such movement is possible.

The goal is to clear a path for the white convertible with brown seats to leave the lot in as few moves as possible.

Java is the once and future king of fun little games like this one. In the ‘90s, thousands of games were created as Java applets and presented on web pages like this one. As other game development alternatives such as Flash arose, Java faded as a game programmer’s favorite.

But then Android phones came along, and now millions of Java games are running on those phones and other mobile devices as apps. Every game you play on an Android device was written with Java.

Java Language Specifics

Java is not a difficult language to learn, though becoming proficient requires time to learn how to exploit the huge amount of Java code offered by Oracle and other providers that have been made available so you don’t have to reinvent the wheel on your own program. Java includes several prebuilt procedures that are often used to perform standard operations such as I/O, connecting to web servers, and accessing databases. Java is an OOP (object-oriented programming) language and is similar to C++ in many ways. Both languages have common keywords, comments, and built-in functions. Java’s OOP nature means that you can extend language objects that others write to complete applications faster.


Tip

Given Java’s C++ roots, once you learn Java, you will already know a lot about C++. However, Java’s developers did try to make Java better than C++. For example, Java, unlike C++ (or C) but similar to JavaScript, supports the string data type. Java also leaves out some features of C++ that are difficult to learn and error prone to use, such as pointers.


Java Example

Listing 12.1 shows a very simple Java program so that you can familiarize yourself with the format of the language. This particular program bears little resemblance to JavaScript programs, but you’ll soon see that your knowledge of that language will speed your mastery of Java.

LISTING 12.1 Your first Java program may look cryptic.


// A simple Java applet

import java.applet.*;      // required support files
import java.awt.*;

// Main class
public class Simple extends Applet {

    public void init() {
        resize(320, 240);   // applet's window size
    }

    public void paint(Graphics g) {
        // change subsequent text color to red
        g.setColor(Color.red);
        // write a simple message in the window
        g.drawString("Free the bound periodicals!", 75, 100);
    }
}


When embedded inside a web page as you’ll learn how to do in Hour 15, Listing 12.1 is simple and displays the message “Free the bound periodicals!” in red on the screen’s browser, 75 pixels from the right edge and 100 pixels from the top of the screen. The screen in this case would be whichever Java-enabled web browser is used to view the page with the HTML code that contains this applet.

Before going into the specifics of Listing 12.1, take a moment to consider these points:

Image Comments, the explanatory remarks for programmers, begin with two forward slashes—//.

Image All Java programs are case-sensitive. Therefore, if you initially name a variable intSum, don’t refer to that variable later as INTSUM because Java will not recognize that both are the same.

Image Java is a free-form language. You can indent and include lots of whitespace to make your programs easier to read and maintain (or exclude it, if you like making things harder for yourself later).

Image A semicolon generally follows each complete executable line. No semicolons follow comments or braces, however. Also, a class or procedure’s definition line (the first line in a class or procedure) doesn’t end with a semicolon because these statements define classes and procedures but don’t execute or produce output.

Image A pair of braces encloses a group of lines that Java treats as a single block of code. Generally, a block can appear anywhere that a single statement can appear. The braces also designate start and stop points for procedures.

These Java-coding principles apply to small as well as large standalone Java programs.

Analyzing the Code

Some of the details of Listing 12.1 should be easy to understand. In the listing, comments help divide the sections of the applet from one another as well as document some lines in the code.

The import commands in Listing 12.1 appear in almost every Java program that you’ll write. The import command is somewhat analogous to the C and C++ #include preprocessor directive, but import is a Java command and not a language directive. Another difference is that import does not import code, despite its name. Instead, it makes it easier to refer to existing classes from special class packages provided by your Java compiler. Remember that in OOP, a class defines an object. A package is a collection of classes that are logically grouped together. For example, graphics routines often appear in a package. You can refer to the graphics objects from the class as long as you import that package.

The import command follows these two formats:

import specificPackage.specificClass;

import specificPackage.*;

When you know the name of a class that you want to use, you can specify that name inside the import command. The specificPackage is the name of the class package from which you want to import the class named specificClass. For example, if you want to import a class package file named nu.xom.Builder, you’d do this:

import nu.xom.Builder;

The second format of import uses the * wildcard character to specify that you want to import all classes from a class package. Listing 12.1 uses this import format for its imported classes. The java.applet class package is a necessary class for you to use when the applet is to be embedded in a web page. Therefore, you’ll always import java.applet and all its classes at the top of every applet that you write. The java.awt class package contains many graphics routines that enable you to send output to a web page’s applet window. Instead of printing text onscreen, your applet must draw the text pixel by pixel. Listing 12.1 contains a drawString() function that is a class procedure defined in the java.awt class package.

If you don’t use import, you must refer to classes by their full names all the time, which consists of the package and class name.

The following line from Listing 12.1 defines a class named Simple:

public class Simple extends Applet {

The opening brace in this public statement begins the body of the applet’s Simple class and the class doesn’t terminate until the closing brace. A statement such as this public statement must appear in your applet because your applet is actually an entirely new class, from the predefined Applet class, that you are extending. In this example, the applet is taking the generic class called Applet (defined in the java.applet class package) and extending the class by naming the copy Simple; the code in the body of Simple is the added functionality for this newly extended class. Without the added code, Simple would be no different from the built-in Applet class and the applet would appear in the web page but could do nothing. The new code is what makes the applet perform.

The next few lines in Listing 12.1 define a new method called init(). (Methods act much like functions except that you apply the methods to objects such as the screen window object.) In reality, the listing is redefining a method that already exists. When the subclassed Applet became Simple, a method named init() came with the Applet class but it does nothing except prepare the applet to run. init() is a method that’s applied to the Simple class. Every Java applet programmer must redefine init() and almost every applet includes the resize() function in the body of init() as done here:

public void init() {
    resize(320, 240);   // applet's window size
}

The resize() method simply informs your class of your applet’s window size in the target web page. You also can insert any other code inside init() that you want executed after the initial loading of the applet. resize() requires two arguments: an x and a y coordinate. Enter the coordinates in pixels. In Listing 12.1, the resize() function is defining the Java applet’s window size (the window will appear inside the web page on the user’s machine) as 320 pixels wide by 240 pixels high.

The paint() method should appear in every applet that you create and paint() should follow init(). Your applet executes paint() every time your applet window needs redrawing. If the user hides the applet’s window with another window and then unhides it later, the hidden portion must reappear and it is paint() that determines what happens every time the window is redrawn. As long as you’ve supplied a paint() method—and you must for anything to be displayed—you can be assured that your applet window will reappear properly with the text, colors, and whatever else that paint() puts on the window.

In Listing 12.1, the paint() method looks like this:

public void paint(Graphics g) {
    // change subsequent text color to red
    g.setColor(Color.red);
    // write a simple message in the window
    g.drawString("Free the bound periodicals!", 75, 100);
}


Note

Unlike init(), paint() requires an argument inside its parentheses. The argument is a value that the paint() method operates on. Although Graphics g is a strange argument, the argument represents your web page’s graphical applet window. Whatever paint() does to the value named g happens to your applet’s window.


The setColor() method, therefore, sets the color for all text that will subsequently appear on the output window, g, until another setColor() appears. Although the window’s background remains gray (you can change the background color if you want), text that appears will be red. After the applet sets the text color to red, four red words appear in the applet’s window due to this line:

g.drawString("Free the bound periodicals!", 75, 100);

drawString() is a commonly used Java method that sends text strings to the applet’s window. drawString() respects the color set by setColor() so the text, “Free the bound periodicals!” will appear in red. Notice the g before the method name. You could, if you opened several different windows with an applet, send text to different windows by prefacing drawString() with each window’s designated context name, such as g used here. The two arguments that end the drawString() method indicate how wide and high, in pixels, the text is to appear.

You now know all there is to know about Listing 12.1’s applet. If you’re still somewhat confused, don’t panic because the next few hours cover the language in more detail. Java statements can be tricky due to the object and class situations brought on by OOP.

Get Ready to Begin

The best way to get into Java programming quickly is to install an integrated development environment (IDE) that has been designed for Java programmers. There are several excellent IDEs for Java, some that can be downloaded over the Internet at no cost and others that are commercial products.

One of the best is NetBeans, a free IDE offered by Oracle that began many years ago under the name Forte for Java. NetBeans is available from the website www.netbeans.org.

If you’ve not yet installed NetBeans for Java, see Appendix B, “Using the NetBeans Integrated Development Environment” (available for download after registering this book at informit.com/register), and follow the installation instructions. You will then be ready to write your first Java program in the next hour.

Summary

The goal of this hour was to introduce you to the Java language with a primer on applets, the simplest type of Java programs. Java adds a jolt to web pages by sending these small interactive programs along with web pages. Part of this introduction was a language overview. Unlike more traditional programming languages such as C++, a Java program is sometimes part of something else, most notably a web page. The program travels with the web page to a user’s machine and executes using the user’s own computing power.

You may not understand much of the Java language yet, but you can understand a simple Java program better now that you’ve finished this lesson. An applet is actually a subclass, an inherited version of a predefined class, that comes with the Java compiler. You add functionality to the Java Applet class to make the program your own.

Q&A

Q. Do I embed my Java program code directly inside the HTML code on my web page?

A. No. HTML is only for formatting a web page’s appearance and for placing the applet in the correct location, but your compiled applet, in bytecode, travels along with a web page to the destination computer. HTML always appears and downloads in source code format, whereas a Java program always downloads in bytecode format. Therefore, the two files must travel separately to the user’s computer.

Q. Can a user stop my Java program from executing?

A. Certain web-based security features can keep Java applets that arrive with a web page from executing on the user’s machine. Although the Java language includes built-in security controls to keep Java authors from invading a user’s machine from the Internet, the user can still keep the applet from executing by setting certain browser options.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. True or false: The faster the user’s computer is, the faster the Java applet that appears with the web page runs.

2. True or false: The faster the user’s computer is, the faster the Java applet downloads on the user’s machine.

3. What is the language behind web page formatting called?

4. What is bytecode?

5. Why is the concept of a Java Virtual Machine (JVM) important?

6. How does the Java language provide security support for the end user who views Java-enabled web pages?

7. What is the purpose of the import command?

8. How do you send text to the screen in a Java applet?

9. Why is the paint() method important?

10. What specifies a Java comment in Java programs?

Answers

1. True.

2. False. The bandwidth and size of the Java applet determines how fast the Java applet loads.

3. HTML is the language that formats web pages.

4. Bytecode is the language into which Java compiles Java code.

5. By emulating a virtual machine, any computer in the world can run any compiled Java program.

6. Java handles security in many ways. For example, Java must receive proper security clearance from the user before accessing a network, cannot access memory space that it has no right to, cannot create, read, rename, copy, or write files on the end user’s computer, and Java applets cannot call internal system routines on the end user’s system.

7. The import command brings object libraries into the Java program.

8. The drawString() function writes characters to the screen.

9. The paint() method determines what happens when a window is redrawn.

10. Java comments begin with // or are enclosed inside a /* and */ pair.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.36.38