Chapter 2. The Java Programming Environment

In this chapter, you will learn how to install the Java Development Kit (JDK) and how to compile and run various types of programs: console programs, graphical applications, and applets. You can run the JDK tools by typing commands in a terminal window. However, many programmers prefer the comfort of an integrated development environment. You will learn how to use a freely available development environment to compile and run Java programs. Although easier to learn, integrated development environments can be resource-hungry and tedious to use for small programs. Once you have mastered the techniques in this chapter and picked your development tools, you are ready to move on to Chapter 3, where you will begin exploring the Java programming language.

2.1 Installing the Java Development Kit

The most complete and up-to-date versions of the Java Development Kit (JDK) are available from Oracle for Linux, Mac OS X, Solaris, and Windows. Versions in various states of development exist for many other platforms, but those versions are licensed and distributed by the vendors of those platforms.

2.1.1 Downloading the JDK

To download the Java Development Kit, visit the web site at www.oracle.com/technetwork/java/javase/downloads and be prepared to decipher an amazing amount of jargon before you can get the software you need. See Table 2.1 for a summary.

Image

Table 2.1 Java Jargon

You already saw the abbreviation JDK for Java Development Kit. Somewhat confusingly, versions 1.2 through 1.4 of the kit were known as the Java SDK (Software Development Kit). You will still find occasional references to the old term. There is also a Java Runtime Environment (JRE) that contains the virtual machine but not the compiler. That is not what you want as a developer. It is intended for end users who have no need for the compiler.

Next, you’ll see the term Java SE everywhere. That is the Java Standard Edition, in contrast to Java EE (Enterprise Edition) and Java ME (Micro Edition).

You might run into the term Java 2 that was coined in 1998 when the marketing folks at Sun felt that a fractional version number increment did not properly communicate the momentous advances of JDK 1.2. However, because they had that insight only after the release, they decided to keep the version number 1.2 for the development kit. Subsequent releases were numbered 1.3, 1.4, and 5.0. The platform, however, was renamed from Java to Java 2. Thus, we had Java 2 Standard Edition Software Development Kit Version 5.0, or J2SE SDK 5.0.

Fortunately, in 2006, the numbering was simplified. The next version of the Java Standard Edition was called Java SE 6, followed by Java SE 7 and Java SE 8. However, the “internal” version numbers are 1.6.0, 1.7.0, and 1.8.0.

When Oracle makes a minor version change to fix urgent issues, it refers to the change as an update. For example, Java SE 8u31 is the 31st update of Java SE 8, and it has the internal version number 1.8.0_31. An update does not need to be installed over a prior version—it contains the most current version of the whole JDK. Also, not all updates are released to the public, so don’t panic if update 31 isn’t followed by update 32.

With Windows or Linux, you need to choose between the x86 (32-bit) and x64 (64-bit) versions. Pick the one that matches the architecture of your operating system.

With Linux, you have a choice between an RPM file and a .tar.gz file. We recommend the latter—you can simply uncompress it anywhere you like.

Now you know how to pick the right JDK. To summarize:

• You want the JDK (Java SE Development Kit), not the JRE.

• Windows or Linux: Choose x86 for 32 bit, x64 for 64 bit.

• Linux: Pick the .tar.gz version.

Accept the license agreement and download the file.


Image Note

Oracle offers a bundle that contains both the Java Development Kit and the NetBeans integrated development environment. I suggest that you stay away from all bundles and install only the Java Development Kit at this time. If you later decide to use NetBeans, simply download it from http://netbeans.org.


2.1.2 Setting up the JDK

After downloading the JDK, you need to install it and figure out where it was installed—you’ll need that information later.

• Under Windows, launch the setup program. You will be asked where to install the JDK. It is best not to accept a default location with spaces in the path name, such as c:Program FilesJavajdk1.8.0_version. Just take out the Program Files part of the path name.

• On the Mac, run the installer. It installs the software into /Library/Java/JavaVirtualMachines/jdk1.8.0_version.jdk/Contents/Home. Locate it with the Finder.

• On Linux, simply uncompress the .tar.gz file to a location of your choice, such as your home directory or /opt. Or, if you installed from the RPM file, double-check that it is installed in /usr/java/jdk1.8.0_version.

In this book, the installation directory is denoted as jdk. For example, when referring to the jdk/bin directory, I mean the directory with a name such as /opt/jdk1.8.0_31/bin or c:Javajdk1.8.0_31in.

When you install the JDK on Windows or Linux, you need to carry out one additional step: Add the jdk/bin directory to the executable path—the list of directories that the operating system traverses to locate executable files.

• On Linux, add a line such as the following to the end of your ~/.bashrc or ~/.bash_profile file:

export PATH=jdk/bin:$PATH

Be sure to use the correct path to the JDK, such as /opt/jdk1.8.0_31.

• Under Windows, start the Control Panel, select System and Security, select System, then select Advanced System Settings (see Figure 2.1). In the System Properties dialog, click the Advanced tab, then click the Environment button. Scroll through the System Variables list until you find a variable named Path. Click the Edit button (see Figure 2.2). Add the jdkin directory to the beginning of the path, using a semicolon to separate the new entry, like this:

jdkin;other stuff

Image

Figure 2.1 Setting system properties in Windows 7

Image

Figure 2.2 Setting the Path environment variable in Windows 7

Be careful to replace jdk with the actual path to your Java installation, such as c:Javajdk1.8.0_31. If you ignored the advice to drop the Program Files directory, enclose the entire path segment in double quotes: "c:Program FilesJavajdk1.8.0_31in";other stuff.

Save your settings. Any new console windows that you start will have the correct path.

Here is how you test whether you did it right: Start a terminal window. Type the line

javac -version

and press the Enter key. You should get a display such as this one:

javac 1.8.0_31

If instead you get a message such as “javac: command not found” or “The name specified is not recognized as an internal or external command, operable program or batch file”, then you need to go back and double-check your installation.

2.1.3 Installing Source Files and Documentation

The library source files are delivered in the JDK as a compressed file src.zip. Unpack that file to get access to the source code. Simply do the following:

1. Make sure the JDK is installed and that the jdk/bin directory is on the executable path.

2. Make a directory javasrc in your home directory. If you like, you can do this from a terminal window.

mkdir javasrc

3. Inside the jdk directory, locate the file src.zip.

4. Unzip the src.zip file into the javasrc directory. In a terminal window, you can execute the commands

cd javasrc
jar xvf jdk/src.zip
cd ..


Image Tip

The src.zip file contains the source code for all public libraries. To obtain even more source (for the compiler, the virtual machine, the native methods, and the private helper classes), go to http://jdk8.java.net.


The documentation is contained in a compressed file that is separate from the JDK. You can download the documentation from www.oracle.com/technetwork/java/javase/downloads. Simply follow these steps:

1. Download the documentation zip file. It is called jdk-version-docs-all.zip, where version is something like 8u31.

2. Unzip the file and rename the doc directory into something more descriptive, like javadoc. If you like, you can do this from the command line:

jar xvf Downloads/jdk-version-docs-all.zip
mv doc javadoc

where version is the appropriate version number.

3. In your browser, navigate to javadoc/api/index.html and add this page to your bookmarks.

You should also install the Core Java program examples. You can download them from http://horstmann.com/corejava. The programs are packaged into a zip file corejava.zip. Just unzip them into your home directory. They will be located in a directory corejava. If you like, you can do this from the command line:

jar xvf Downloads/corejava.zip

2.2 Using the Command-Line Tools

If your programming experience comes from using a development environment such as Microsoft Visual Studio, you are accustomed to a system with a built-in text editor, menus to compile and launch a program, and a debugger. The JDK contains nothing even remotely similar. You do everything by typing in commands in a terminal window. This sounds cumbersome, but it is nevertheless an essential skill. When you first install Java, you will want to troubleshoot your installation before you install a development environment. Moreover, by executing the basic steps yourself, you gain a better understanding of what a development environment does behind your back.

However, after you have mastered the basic steps of compiling and running Java programs, you will want to use a professional development environment. You will see how to do that in the following section.

Let’s get started the hard way: compiling and launching a Java program from the command line.

1. Open a terminal window.

2. Go to the corejava/v1ch02/Welcome directory. (The corejava directory is the directory into which you installed the source code for the book examples, as explained in Section 2.1.3, “Installing Source Files and Documentation,” on p. 22.)

3. Enter the following commands:

javac Welcome.java
java Welcome

You should see the output shown in Figure 2.3 in the terminal window.

Image

Figure 2.3 Compiling and running Welcome.java

Congratulations! You have just compiled and run your first Java program.

What happened? The javac program is the Java compiler. It compiles the file Welcome.java into the file Welcome.class. The java program launches the Java virtual machine. It executes the bytecodes that the compiler placed in the class file.

The Welcome program is extremely simple. It merely prints a message to the console. You may enjoy looking inside the program, shown in Listing 2.1. You will see how it works in the next chapter.

Listing 2.1 Welcome/Welcome.java


 1   /**
 2    * This program displays a greeting for the reader.
 3    * @version 1.30 2014-02-27
 4    * @author Cay Horstmann
 5    */
 6   public class Welcome
 7   {
 8      public static void main(String[] args)
 9      {
10         String greeting = "Welcome to Core Java!";
11         System.out.println(greeting);
12         for (int i = 0; i < greeting.length(); i++)
13            System.out.print("=");
14         System.out.println();
15      }
16   }


In the age of visual development environments, many programmers are unfamiliar with running programs in a terminal window. Any number of things can go wrong, leading to frustrating results.

Pay attention to the following points:

• If you type in the program by hand, make sure you correctly enter the uppercase and lowercase letters. In particular, the class name is Welcome and not welcome or WELCOME.

• The compiler requires a file name (Welcome.java). When you run the program, you specify a class name (Welcome) without a .java or .class extension.

• If you get a message such as “Bad command or file name” or “javac: command not found”, then go back and double-check your installation, in particular the executable path setting.

• If javac reports that it cannot find the file Welcome.java, then you should check whether that file is present in the directory.

Under Linux, check that you used the correct capitalization for Welcome.java.

Under Windows, use the dir command, not the graphical Explorer tool. Some text editors (in particular Notepad) insist on adding an extension .txt to every file’s name. If you use Notepad to edit Welcome.java, it will actually save it as Welcome.java.txt. Under the default Windows settings, Explorer conspires with Notepad and hides the .txt extension because it belongs to a “known file type.” In that case, you need to rename the file, using the ren command, or save it again, placing quotes around the file name: "Welcome.java".

• If you launch your program and get an error message complaining about a java.lang.NoClassDefFoundError, then carefully check the name of the offending class.

If you get a complaint about welcome (with a lowercase w), then you should reissue the java Welcome command with an uppercase W. As always, case matters in Java.

If you get a complaint about Welcome/java, it means you accidentally typed java Welcome.java. Reissue the command as java Welcome.

• If you typed java Welcome and the virtual machine can’t find the Welcome class, check if someone has set the CLASSPATH environment variable on your system. It is not a good idea to set this variable globally, but some poorly written software installers in Windows do just that. Follow the same procedure as for setting the PATH environment variable, but this time, remove the setting.


Image Tip

The excellent tutorial at http://docs.oracle.com/javase/tutorial/getStarted/cupojava goes into much greater detail about the “gotchas” that beginners can run into.


2.3 Using an Integrated Development Environment

In the preceding section, you saw how to compile and run a Java program from the command line. That is a useful skill, but for most day-to-day work, you should use an integrated development environment. These environments have become so powerful and convenient that it simply doesn’t make much sense to labor on without them. Excellent choices are the freely available Eclipse, NetBeans, and IntelliJ IDEA programs. In this chapter, you will learn how to get started with Eclipse. Of course, if you prefer a different development environment, you can certainly use it with this book.

In this section, you will see how to compile a program with Eclipse, an integrated development environment that is freely available from http://eclipse.org/downloads. Versions exist for Linux, Mac OS X, Solaris, and Windows. When you visit the download site, pick the “Eclipse IDE for Java Developers”. Choose between the 32- or 64-bit versions, matching your operating system.

Simply unzip Eclipse to a location of your choice, and execute the eclipse program inside the zip file.

Here are the steps to write a program with Eclipse.

1. After starting Eclipse, select File → New → Project from the menu.

2. Select “Java Project” from the wizard dialog (see Figure 2.4).

Image

Figure 2.4 The New Project dialog in Eclipse

3. Click the Next button. Uncheck the “Use default location” checkbox. Click on Browse and navigate to the corejava/v1ch02/Welcome directory (see Figure 2.5).

Image

Figure 2.5 Configuring a project in Eclipse

4. Click the Finish button. The project is now created.

5. Click on the triangles in the left pane next to the project until you locate the file Welcome.java, and double-click on it. You should now see a pane with the program code (see Figure 2.6).

Image

Figure 2.6 Editing a source file with Eclipse

6. With the right mouse button, click on the project name (Welcome) in the left pane. Select Run → Run As → Java Application. The program output is displayed in the console pane.

Presumably, this program does not have typos or bugs. (It was only a few lines of code, after all.) Let us suppose, for the sake of argument, that your code occasionally contains a typo (perhaps even a syntax error). Try it out—ruin your file, for example, by changing the capitalization of String as follows:

string greeting = "Welcome to Core Java!";

Note the wiggly line under string. In the tabs below the source code, click on Problems and expand the triangles until you see an error message that complains about an unknown string type (see Figure 2.7). Click on the error message. The cursor moves to the matching line in the edit pane, where you can correct your error. This feature allows you to fix your errors quickly.

Image

Figure 2.7 Error messages in Eclipse


Image Tip

Often, an Eclipse error report is accompanied by a lightbulb icon. Click on the lightbulb to get a list of suggested fixes.


2.4 Running a Graphical Application

The Welcome program was not terribly exciting. Next, try out a graphical application. This program is a simple image file viewer that loads and displays an image. Again, let us first compile and run it from the command line.

1. Open a terminal window.

2. Change to the directory corejava/v1ch02/ImageViewer.

3. Enter the following:

javac ImageViewer.java
java ImageViewer

A new program window pops up with the ImageViewer application (see Figure 2.8).

Image

Figure 2.8 Running the ImageViewer application

Now, select File → Open and look for an image file to open. (There are a couple of sample files in the same directory.) To close the program, click on the Close box in the title bar or select File → Exit from the menu.

Have a quick look at the source code (Listing 2.2). The program is substantially longer than the first program, but it is not too complex if you consider how much code it would take in C or C++ to write a similar application. You’ll learn how to write graphical programs like this in Chapters 10 through 12.

Listing 2.2 ImageViewer/ImageViewer.java


 1   import java.awt.*;
 2   import java.io.*;
 3   import javax.swing.*;
 4
 5   /**
 6    * A program for viewing images.
 7    * @version 1.30 2014-02-27
 8    * @author Cay Horstmann
 9    */
10   public class ImageViewer
11   {
12      public static void main(String[] args)
13      {
14         EventQueue.invokeLater(() -> {
15            JFrame frame = new ImageViewerFrame();
16            frame.setTitle("ImageViewer");
17            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18            frame.setVisible(true);
19         });
20      }
21   }
22
23   /**
24    * A frame with a label to show an image.
25    */
26   class ImageViewerFrame extends JFrame
27   {
28      private JLabel label;
29      private JFileChooser chooser;
30      private static final int DEFAULT_WIDTH = 300;
31      private static final int DEFAULT_HEIGHT = 400;
32
33      public ImageViewerFrame()
34      {
35         setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
36
37         // use a label to display the images
38         label = new JLabel();
39         add(label);
40
41         // set up the file chooser
42         chooser = new JFileChooser();
43         chooser.setCurrentDirectory(new File("."));
44
45         // set up the menu bar
46         JMenuBar menuBar = new JMenuBar();
47         setJMenuBar(menuBar);
48
49         JMenu menu = new JMenu("File");
50         menuBar.add(menu);
51
52         JMenuItem openItem = new JMenuItem("Open");
53         menu.add(openItem);
54         openItem.addActionListener(event -> {
55            // show file chooser dialog
56               int result = chooser.showOpenDialog(null);
57
58               // if file selected, set it as icon of the label
59               if (result == JFileChooser.APPROVE_OPTION)
60               {
61                  String name = chooser.getSelectedFile().getPath();
62                  label.setIcon(new ImageIcon(name));
63               }
64            });
65
66         JMenuItem exitItem = new JMenuItem("Exit");
67         menu.add(exitItem);
68         exitItem.addActionListener(event -> System.exit(0));
69      }
70   }


2.5 Building and Running Applets

The first two programs presented in this book are Java applications—stand-alone programs like any native programs. On the other hand, as mentioned in the previous chapter, most of the early hype about Java came from its ability to run applets inside a web browser.

If you are interested in experiencing a “blast from the past,” follow along to see how to build and run an applet and how to display it in a web browser; if you aren’t interested, by all means, skip this example and move on to Chapter 3.

Open a terminal window and go to the directory corejava/v1ch02/RoadApplet, then enter the following commands:

javac RoadApplet.java
jar cvfm RoadApplet.jar RoadApplet.mf *.class
appletviewer RoadApplet.html

Figure 2.9 shows what you see in the applet viewer window. This applet visualizes how traffic jams can be caused by drivers who randomly slow down. In 1996, applets were a great tool for creating such visualizations.

Image

Figure 2.9 The RoadApplet as viewed by the applet viewer

The first command is the now-familiar command to invoke the Java compiler. This compiles the RoadApplet.java source into the bytecode file RoadApplet.class.

This time, however, you do not run the java program. First, you bundle the class files into a “JAR file,” using the jar utility. Then you invoke the appletviewer program, a tool included with the JDK that lets you quickly test an applet. You need to give this program an HTML file name, rather than the name of a Java class file. The contents of the RoadApplet.html file are shown at the end of this section in Listing 2.3.

If you are familiar with HTML, you will notice standard HTML markup and the applet tag, telling the applet viewer to load the applet whose code is stored in RoadApplet.jar. The applet viewer ignores all HTML tags except for the applet tag.

Of course, applets are meant to be viewed in a browser. Unfortunately, nowadays, many browsers do not have Java support, or make it difficult to enable it. Your best bet is to use Firefox.

If you use Windows or Mac OS X, Firefox should automatically pick up the Java installation on your computer. Under Linux, you need to enable the plug-in with the following commands:

mkdir -p ~/.mozilla/plugins
cd ~/.mozilla/plugins
ln -s jdk/jre/lib/amd64/libnpjp2.so

To double-check, type about:plugins into the address bar and look for the Java Plug-in. Make sure it uses the Java SE 8 version of the plug-in—look for a MIME type of application/x-java-applet;version=1.8.

Next, turn your browser to http://horstmann.com/applets/RoadApplet/RoadApplet.html, agree to all the scary security prompts, and make sure the applet appears.

Unfortunately, that is not enough to test the applet that you just compiled. The applet on the horstmann.com server is digitally signed. I had to expend some effort, getting a certificate issuer that is trusted by the Java virtual machine to trust me and sell me a certificate, which I used to sign the JAR file. The browser plug-in will no longer run untrusted applets. This is a big change from the past, when a simple applet that draws pixels on the screen would have been confined to the “sandbox” and would work without being signed. Sadly, not even Oracle has faith in the security of the sandbox any more.

To overcome this problem, you can temporarily configure Java to trust applets from the local file system. First, open the Java control panel.

• In Windows, look inside the Programs section of the control panel.

• On a Mac, open System Preferences.

• On Linux, run jcontrol.

Then click the Security tab and the Edit Site List button. Click Add and type in file:///. Click OK, accept another security prompt, and click OK again (see Figure 2.10).

Image

Figure 2.10 Configuring Java to trust local applets

Now you should be able to load the file corejava/v1ch02/RoadApplet/RoadApplet.html into your browser and have the applet appear, together with the surrounding text. It will look something like Figure 2.11.

Image

Figure 2.11 Running the RoadApplet in a browser

The code for the applet class is shown in Listing 2.4. At this point, do not give it more than a glance. We will come back to writing applets in Chapter 13.

Listing 2.3 RoadApplet/RoadApplet.html


 1   <html xmlns="http://www.w3.org/1999/xhtml">
 2      <head><title>A Traffic Simulator Applet</title></head>
 3      <body>
 4         <h1>Traffic Simulator Applet</h1>
 5
 6         <p>I wrote this traffic simulation, following the article "Und nun die
 7         Stauvorhersage" of the German Magazine <i>Die Zeit</i>, June 7,
 8         1996. The article describes the work of Professor Michael Schreckenberger
 9         of the University of Duisburg and unnamed collaborators at the University
10         of Cologne and Los Alamos National Laboratory. These researchers model
11         traffic flow according to simple rules, such as the following: </p>
12         <ul>
13            <li>A freeway is modeled as a sequence of grid points. </li>
14            <li>Every car occupies one grid point. Each grid point occupies at most
15            one car. </li>
16            <li>A car can have a speed of 0 - 5 grid points per time interval. </li>
17            <li>A car with speed of less than 5 increases its speed by one unit in
18            each time interval, until it reaches the maximum speed. </li>
19            <li>If a car's distance to the car in front is <i>d</i> grid points, its
20            speed is reduced to <i>d</i>-1 if necessary to avoid crashing into it.
21            </li>
22            <li>With a certain probability, in each time interval some cars slow down
23            one unit for no good reason whatsoever. </li>
24         </ul>
25
26         <p>This applet models these rules. Each line shows an image of the same
27         stretch of road. Each square denotes one car. The first scrollbar lets you
28         adjust the probability that some cars slow down. If the slider is all the
29         way to the left, no car slows down. If it is all the way to the right,
30         every car slows down one unit. A typical setting is that 10% - 20% of the
31         cars slow down. The second slider controls the arrival rate of the cars.
32         When it is all the way to the left, no new cars enter the freeway. If it
33         is all the way to the right, a new car enters the freeway every time
34         interval, provided the freeway entrance is not blocked. </p>
35
36         <p>Try out the following experiments. Decrease the probability of slowdown
37         to 0. Crank up the arrival rate to 1. That means, every time unit, a new
38         car enters the road. Note how the road can carry this load. </p>
39
40         <p>Now increase the probability that some cars slow down. Note how traffic
41         jams occur almost immediately. </p>
42
43         <p>The moral is: If it wasn't for the rubberneckers, the cellular phone
44         users, and the makeup-appliers who can't keep up a constant speed, we'd all
45         get to work more quickly. </p>
46
47         <p>Notice how the traffic jam is stationary or even moves backwards, even
48         though the individual cars are still moving. In fact, the first car
49         causing the jam has long left the scene by the time the jam gets bad.
50         (To make it easier to track cars, every tenth vehicle is colored red.) </p>
51
52         <p><applet code="RoadApplet.class" archive="RoadApplet.jar"
53                    width="400" height="400" alt="Traffic jam visualization">
54         </applet></p>
55
56         <p>For more information about applets, graphics programming and
57         multithreading in Java, see
58         <a href="http://horstmann.com/corejava">Core Java</a>. </p>
59      </body>
60   </html>


Listing 2.4 RoadApplet/RoadApplet.java


 1   import java.awt.*;
 2   import java.applet.*;
 3   import javax.swing.*;
 4
 5   public class RoadApplet extends JApplet
 6   {
 7      private RoadComponent roadComponent;
 8      private JSlider slowdown;
 9      private JSlider arrival;
10
11      public void init()
12      {
13         EventQueue.invokeLater(() ->
14            {
15               roadComponent = new RoadComponent();
16               slowdown = new JSlider(0, 100, 10);
17               arrival = new JSlider(0, 100, 50);
18
19               JPanel p = new JPanel();
20               p.setLayout(new GridLayout(1, 6));
21               p.add(new JLabel("Slowdown"));
22               p.add(slowdown);
23               p.add(new JLabel(""));
24               p.add(new JLabel("Arrival"));
25               p.add(arrival);
26               p.add(new JLabel(""));
27               setLayout(new BorderLayout());
28               add(p, BorderLayout.NORTH);
29               add(roadComponent, BorderLayout.CENTER);
30            });
31      }
32
33      public void start()
34      {
35         new Thread(() ->
36            {
37               for (;;)
38               {
39                  roadComponent.update(
40                     0.01 * slowdown.getValue(),
41                     0.01 * arrival.getValue());
42                  try { Thread.sleep(50); } catch(InterruptedException e) {}
43               }
44            }).start();
45      }
46   }


In this chapter, you learned about the mechanics of compiling and running Java programs. You are now ready to move on to Chapter 3 where you will start learning the Java language.

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

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