Chapter 3

Running Programs

In This Chapter

arrow Compiling and running a program

arrow Working with a workspace

arrow Editing your own Java code

If you’re a programming newbie, for you, running a program probably means clicking a mouse. You want to run Internet Explorer, so you double-click the Internet Explorer icon. That’s all there is to it.

When you create your own programs, the situation is a bit different. With a new program, the programmer (or someone from the programmer’s company) creates the program’s icon. Before that process, a perfectly good program may not have an icon at all. So what do you do with a brand-new Java program? How do you get the program to run? This chapter tells you what you need to know.

Running a Canned Java Program

The best way to get to know Java is to do Java. When you’re doing Java, you’re writing, testing, and running your own Java programs. This section prepares you by describing how you run and test a program. Instead of writing your own program, you run a program that I’ve already written for you. The program calculates your monthly payments on a home mortgage loan.

The mortgage-calculating program doesn’t open its own window. Instead, the program runs in Eclipse’s Console view. The Console view is one of the tabs in the lower-right part of the Eclipse workbench (see Figure 3-1). A program that operates completely in this Console view is called a text-based program.

Figure 3-1: A run of this chapter’s text–based mortgage program.

9780470371749-fg0301.tif

tip.eps You may not see a Console tab in the lower-right part of the Eclipse workbench. To coax the Console view out of hiding, choose Window⇒Show View⇒Other. In the resulting Show View dialog box, expand the General branch. Finally, within that General branch, double-click the Console item.

For more information about the Console view (and about Eclipse’s workbench in general), see the “Views and editors” section, later in this chapter.

Actually, as you run the mortgage program, you see two things in Eclipse’s Console view:

check.png Messages and results that the mortgage program sends to you. Messages include things like How much are you borrowing? Results include lines like Your monthly payment is $552.20.

check.png Responses that you give to the mortgage program while it runs. If you type 100000.00 in response to the program’s question about how much you’re borrowing, you see that number echoed in Eclipse’s Console view.

Here’s how you run the mortgage program:

1. Make sure that you’ve followed the instructions in Chapter 2 — instructions for installing Java, for installing and configuring Eclipse, and for getting this book’s sample programs.

Thank goodness! You don’t have to follow those instructions more than once.

2. Launch Eclipse.

The Eclipse Workspace Launcher dialog box appears (see Figure 3-2).

A workspace is a folder on your computer’s hard drive. Eclipse stores your Java programs in one or more workspace folders. Along with these Java programs, each workspace folder contains some Eclipse settings. These settings store things like the version of Java that you’re using, the colors that you prefer for words in the editor, the size of the editor area when you drag the area’s edges, and other things. You can have several workspaces with different programs and different settings in each workspace.

Figure 3-2: The Eclipse Workspace Launcher.

9780470371749-fg0302.eps

By default, the Workspace Launcher offers to open whatever workspace you opened the last time you ran Eclipse. You want to open the workspace that you used in Chapter 2, so don’t modify the stuff in the Launcher’s Workspace field.

3. In the Workspace Launcher dialog box, click OK.

The big Eclipse workbench stares at you from your computer screen (see Figure 3-3).

Figure 3-3: The Eclipse workbench.

9780470371749-fg0303.eps

In Figure 3-3, the leftmost part of the workbench is Eclipse’s Package Explorer, which contains numbers like 03-01, 04-01, and so on. Each number is actually the name of an Eclipse project. Formally, a project is a collection of files and folders inside a workspace. Intuitively, a project is a basic work unit. For example, a self-contained collection of Java program files to manage your CD collection (along with the files containing the data) may constitute a single Eclipse project.

Looking again at the Package Explorer in Figure 3-3, you see projects named 03-01, 04-01, and so on. My project 03-01 holds the first and only example in Chapter 3 (this chapter). Project 06-02 contains the Java program in Listing 6-2 (the second code listing in Chapter 6 of this book). Project names can include letters, digits, blank spaces, and other characters, but for the names of this book’s examples, I stick with digits and dashes.

To read more about things like Eclipse’s Package Explorer, see the upcoming section “What’s All That Stuff in Eclipse’s Window?”

warning_bomb.eps When you launch Eclipse, you may see something different from the stuff in Figure 3-3. You may see Eclipse’s Welcome screen with only a few icons in an otherwise barren window. You may also see a workbench like the one in Figure 3-3, but without a list of numbers (03-01, 04-01, and so on) in the Package Explorer. If so, then you may have missed some instructions on configuring Eclipse in Chapter 2. Alternatively, you may have modified the stuff in the Launcher’s Workspace field in Step 2 of this section’s instructions.

In any case, make sure that you see numbers like 03-01 and 04-01 in the Package Explorer. Seeing these numbers assures you that Eclipse is ready to run the sample programs from this book.

4. In the Package Explorer, click the 03-01 branch.

This chapter’s Java project — the 03-01 project — appears highlighted.

tip.eps You may want to see a sneak preview of some Java code. To see the Java program that you’re running in Project 03-01, expand the 03-01 branch in the Package Explorer. Inside the 03-01 branch, you find a src branch, which in turn contains a (default package) branch. Inside the (default package) branch, you find the Mortgage.java branch. That Mortgage.java branch represents my Java program. Double-clicking the Mortgage.java branch makes my code appear in Eclipse’s editor.

5. Choose RunRun AsJava Application from the main menu, as shown in Figure 3-4.

When you choose Run As⇒Java Application, the computer runs the project’s code. (In this example, the computer runs a Java program that I wrote.) As part of the run, the message How much are you borrowing? appears in Eclipse’s Console view. (The Console view shares the lower-right area of Eclipse’s workbench with the Problems view, the Javadoc view, the Declaration view, and possibly other views. Refer to Figure 3-1.)

Figure 3-4: One of the ways to run the code in Project 03-01.

9780470371749-fg0304.tif

6. Click anywhere inside Eclipse’s Console view and then type a number, like 100000.00, and press Enter.

warning_bomb.eps When you type a number in Step 6, don’t include your country’s currency symbol and don’t group the digits. (U.S. residents, don’t type a dollar sign and don’t use any commas.) Things like $100000.00 and 1,000,000.00 cause the program to crash. You see a NumberFormatException message in the Console view.

After you press Enter, the Java program displays another message (What’s the interest rate?) in the Console view. (Again, refer to Figure 3-1.)

7. In response to the interest rate question, type a number, like 5.25, and press Enter.

After you press Enter, the Java program displays another message (How many years . . . ?) in the Console view.

8. Type a number, like 30, and press Enter.

In response to the numbers that you type, the Java program displays a monthly payment amount. Again, refer to Figure 3-1.

Disclaimer: Your local mortgage company charges more than the amount that my Java program calculates. (A lot more.)

warning_bomb.eps When you type a number in Step 8, don’t include a decimal point. Numbers like 30.0 cause the program to crash. You see a NumberFormatException message in the Console view.

tip.eps Occasionally, you decide in the middle of a program’s run that you’ve made a mistake of some kind. You want to stop the program’s run dead in its tracks. Simply click the little red rectangle above the Console view (see Figure 3-5).

Figure 3-5: How to prematurely terminate a program’s run.

9780470371749-fg0305.tif

If you follow this section’s instructions and you don’t get the results that I describe, you can try three things. I list them in order from best to worst:

check.png Check all the steps to make sure that you did everything correctly.

check.png Send e-mail to me at BeginProg@allmycode.com. If you describe what happened, I can probably figure out what went wrong and tell you how to correct the problem.

check.png Panic.

Typing and Running Your Own Code

The previous section is about running someone else’s Java code (code that you download from this book’s website). But eventually, you’ll write code on your own. This section shows you how to create code with the Eclipse IDE.

Separating your programs from mine

You can separate your code from this book’s examples by creating a separate workspace. Here are two ways to do it:

check.png When you launch Eclipse, type a new folder name in the Workspace field of Eclipse’s Workspace Launcher dialog box.

If the folder doesn’t already exist, Eclipse creates the folder. If the folder already exists, Eclipse’s Package Explorer lists any projects that the folder contains.

check.png In the Eclipse workbench’s main menu, choose FileSwitch Workspace (see Figure 3-6).

When you choose File⇒Switch Workspace, Eclipse offers you a few of your previously opened workspace folders. If your choice of folder isn’t in the list, select the Other option. In response, Eclipse reopens its Workspace Launcher dialog box.

Figure 3-6: Switching to a different Eclipse workspace.

9780470371749-fg0306.tif

Writing and running your program

Here’s how you create a new Java project:

1. Launch Eclipse.

2. From Eclipse’s menu bar, choose FileNewJava Project.

A New Java Project dialog box appears.

3. In the New Java Project dialog box, type a name for your project and then click Finish.

In Figure 3-7, I type the name MyFirstProject.

remember.eps If you click Next instead of Finish, you see some other options that you don’t need right now. So to avoid any confusion, just click Finish.

Clicking Finish brings you back to Eclipse’s workbench, with MyFirstProject in the Package Explorer, as shown in Figure 3-8.

The next step is to create a new Java source code file.

Figure 3-7: Getting Eclipse to create a new project.

9780470371749-fg0307.eps

Figure 3-8: Your project appears in Eclipse’s Package Explorer.

9780470371749-fg0308.tif

4. Select your newly created project in the Package Explorer.

To create Figure 3-8, I selected MyFirstProject instead of SomeOtherProject.

5. In Eclipse’s main menu, choose FileNewClass.

Eclipse’s New Java Class dialog box appears (see Figure 3-9).

Figure 3-9: Getting Eclipse to create a new Java class.

9780470371749-fg0309.eps

technicalstuff.eps Java programmers normally divide their code into one or more packages. A typical package has a name like java.util or com.allmycode.images. In Figure 3-9, Eclipse is warning me that I’m not naming a package to contain my project’s code. So the code goes into a nondescript thing called Java’s default package. Java’s default package is a package with no name — a catchall location for code that isn’t otherwise packaged. Packages are great for managing big programming projects, but Beginning Programming For Dummies contains no big programming projects. So in this example (and in all of this book’s examples), I choose to ignore the warning. For more info about Java packages, see Chapter 18.

tip.eps Like every other windowed environment, Eclipse provides many ways to accomplish the same task. Instead of choosing File⇒New⇒Class, you can right-click MyFirstProject in the Package Explorer in Windows (or control-click MyFirstProject in the Package Explorer on a Mac). In the resulting context menu, choose New⇒Class. You can also start by pressing Alt+Shift+N in Windows (or Option+Cmd+N on a Mac). The choice of clicks and keystrokes is up to you.

6. In the New Java Class dialog box’s Name field, type the name of your new class.

In this example, I use the name MyFirstJavaClass, with no blank spaces between any of the words in the name. (Refer to Figure 3-9.)

warning_bomb.eps The name in the New Java Class dialog box must not have blank spaces. And the only allowable punctuation symbol is the underscore character (_). You can name your class MyFirstJavaClass or My_First_Java_Class, but you can’t name it My First Java Class or JavaClass,MyFirst.

7. Put a check mark in the public static void main(String[] args) check box.

Your check mark tells Eclipse to create some boilerplate Java code.

8. Accept the defaults for everything else in the New Java Class dialog box (in other words, click Finish).

You can even ignore the “default package is discouraged” warning near the top of the dialog box.

Clicking Finish brings you back to Eclipse’s workbench. Now MyFirstProject contains a file named MyFirstJavaClass.java. For your convenience, the MyFirstJavaClass.java file already has some code in it. Eclipse’s editor displays the Java code (see Figure 3-10).

Figure 3-10: Eclipse writes some code in the Editor.

9780470371749-fg0310.tif

9. Replace an existing line of code in your new Java program.

Type a line of code in Eclipse’s Editor. Replace the line

// TODO Auto-generated method stub

with the line

System.out.println(“Chocolate, royalties, sleep”);

Copy the new line of code exactly as you see it in Listing 3-1.

• Spell each word exactly the way I spell it in Listing 3-1.

• Capitalize each word exactly the way I do in Listing 3-1.

• Include all the punctuation symbols — the dots, the quotation marks, the semicolon, everything.

remember.eps • Distinguish between the lowercase letter l and the digit 1. The word println tells the computer to print a whole line. Each character in the word println is a lowercase letter. The word contains no digits.

Listing 3-1: A Program to Display the Things I Like

public class MyFirstJavaClass {

  /**

   * @param args

   */

  public static void main(String[] args) {

    System.out.println(“Chocolate, royalties, sleep”);

  }

}

warning_bomb.eps Java is case-sensitive, which means that system.out.printLn isn’t the same as System.out.println. If yOu tyPe system.out.printLn, your progrAm won’t worK. Be sUre to cAPItalize your codE eXactLy as it is in LiSTIng 3-1.

If you typed everything correctly, you see the stuff in Figure 3-11.

Figure 3-11: A Java program in the Eclipse editor.

9780470371749-fg0311.tif

If you don’t type the code exactly as it’s shown in Listing 3-1, you may see jagged red underlines, tiny rectangles with X-like markings inside them, or other red marks in the Editor (see Figure 3-12).

Figure 3-12: A Java program typed incorrectly.

9780470371749-fg0312.tif

The red marks in Eclipse’s editor refer to compile-time errors in your Java code. A compile-time error (also known as a compiler error) is an error that prevents the computer from translating your code. (See the talk about code translation in Chapter 1.)

tip.eps The error markers in Figure 3-12 appear on line 8 of the Java program. Line numbers appear in the editor’s left margin. To make Eclipse’s editor display line numbers, choose Window⇒Preferences (on Windows) or Eclipse⇒Preferences (on a Mac). Then choose General⇒Editors⇒Text Editors. Finally, put a check mark in the Show Line Numbers check box.

To fix compile-time errors, you must become a dedicated detective. You join an elite squad known as Law & Order: Java Programming Unit. You seldom find easy answers. Instead, you comb the evidence slowly and carefully for clues. You compare everything you see in the editor, character by character, with my code in Listing 3-1. You don’t miss a single detail, including spelling, punctuation, and uppercase versus lowercase.

Eclipse has a few nice features to help you find the source of a compile-time error. For example, you can hover over the jagged red underline. When you do, you see a brief explanation of the error along with some suggestions for repairing the error — some quick fixes (see Figure 3-13).

Figure 3-13: Eclipse offers some helpful suggestions.

9780470371749-fg0313.tif

In Figure 3-13, a popup tells you that Java doesn’t know what the word system means — that is, system cannot be resolved. Near the bottom of the figure, one of the quick fix options is to change system to System.

When you click that Change To ‘System’ (java.lang) option, Eclipse’s editor replaces system with System. The editor’s error markers disappear, and you go from the incorrect code in Figure 3-12 to the correct code in Figure 3-11.

10. Make any changes or corrections to the code in the Eclipse’s editor.

When at last you see no jagged underlines or blotches in the editor, you’re ready to try running the program.

11. Select MyFirstJavaClass either by clicking inside the editor or by clicking the MyFirstProject branch in the Package Explorer.

12. In Eclipse’s main menu, choose RunRun AsJava Application.

That does the trick. Your new Java program runs in Eclipse’s Console view. If you’re running the code in Listing 3-1, you see the Chocolate, royalties, sleep message in Figure 3-14. It’s like being in heaven!

Figure 3-14: Running the program in Listing 3-1.

9780470371749-fg0314.tif

What’s All That Stuff in Eclipse’s Window?

Believe it or not, an editor once rejected one of my book proposals. In the margins, the editor scribbled “This is not a word” next to things like “can’t,” “it’s,” and “I’ve.” To this day, I still do not know what this editor did not like about contractions. My own opinion is that language always needs to expand. Where would we be without a new words — words like dotcom, infomercial, and vaporware?

Even the Oxford English Dictionary (the last word in any argument about words) grows by more than 4,000 entries each year. That’s an increase of more than 1 percent per year. It’s about 11 new words per day!

The fact is, human thought is like a big high-rise building. You can’t build the 50th floor until you’ve built at least part of the 49th. You can’t talk about spam until you have a word like e-mail. With all that goes on these days, you need verbal building blocks. That’s why this section contains a bunch of new terms.

In this section, each newly defined term describes an aspect of the Eclipse IDE. So before your read all this Eclipse terminology, I provide the following disclaimers:

check.png This section is optional reading. Refer to this section if you have trouble understanding some of this book’s instructions. But if have no trouble navigating the Eclipse IDE, don’t complicate things by fussing over the terminology in this section.

check.png This section provides explanations of terms, not formal definitions of terms. Yes, my explanations are fairly precise, but no, they’re not airtight. Almost every description in this section has hidden exceptions, omissions, exemptions, and exclusions. Take the paragraphs in this section to be friendly reminders, not legal contracts.

check.png Eclipse is a very useful tool. But Eclipse isn’t officially part of the Java ecosystem. Although I don’t describe details in this book, you can write Java programs without ever using Eclipse.

Understanding the big picture

Your tour of Eclipse begins with a big Burd’s eye view.

check.png Workbench: The Eclipse desktop (see Figure 3-3). The workbench is the environment in which you develop code.

check.png Area: A section of the workbench. The workbench in Figure 3-3 contains five areas. To illustrate the point, I’ve drawn borders around each of the areas (see Figure 3-15).

check.png Window: A copy of the Eclipse workbench. With Eclipse, you can have several copies of the workbench open at once. Each copy appears in its own window.

tip.eps To open a second window, go to the main Eclipse menu bar and choose Window⇒New Window.

check.png Action: A choice that’s offered to you, typically when you click something. For example, when you choose File⇒New in Eclipse’s main menu bar, you see a list of new things that you can create. The list usually includes Project, Folder, File, and Other, but it may also include things like Package, Class, and Interface. Each of these things (each item in the menu) is called an action.

Views, editors, and other stuff

The next bunch of terms deals with things called views, editors, and tabs.

tip.eps You may have difficulty understanding the difference between views and editors. (A view is like an editor, which is like a view, or something like that.) If views and editors seem the same to you, and you’re not sure you can tell which is which, don’t be upset. As an ordinary Eclipse user, the distinction between views and editors comes naturally as you gain experience using the workbench. You rarely have to decide whether the thing you’re using is a view or an editor.

Figure 3-15: The workbench is divided into areas.

9780470371749-fg0315.eps

If you ever have to decide what a view is as opposed to an editor, here’s what you need to know:

check.png View: A part of the Eclipse workbench that displays information for you to browse. In the simplest case, a view fills up an area in the workbench. For example, in Figure 3-3, the Package Explorer view fills up the leftmost area.

Many views display information as lists or trees. For example, in Figure 3-10, the Package Explorer view contains a tree.

You can use a view to make changes to things. For example, to delete SomeOtherProject in Figure 3-10, right-click the SomeOtherProject branch in the Package Explorer view. (On a Mac, control-click the SomeOtherProject branch.) Then, in the resulting context menu, choose Delete.

remember.eps When you use a view to change something, the change takes place immediately. For example, when you choose Delete in the Package Explorer’s context menu, whatever item you’ve selected is deleted immediately. In a way, this behavior is nothing new. The same kind of thing happens when you recycle a file using Windows Explorer or trash a file using the Macintosh Finder.

check.png Editor: A part of the Eclipse workbench that displays information for you to modify. A typical editor displays information in the form of text. This text can be the contents of a file. For example, an editor in Figure 3-10 displays the contents of the MyFirstJavaClass.java file.

remember.eps When you use an editor to change something, the change doesn’t take place immediately. For example, look at the editor in Figure 3-10. This editor displays the contents of the MyFirstJavaClass.java file. You can type all kinds of things in the editor. Nothing happens to MyFirstJavaClass.java until you choose File⇒Save from Eclipse’s menu bar. Of course, this behavior is nothing new. The same kind of thing happens when you work in Microsoft Word or in any other word processing program.

technicalstuff.eps Like other authors, I occasionally become lazy and use the word “view” when I really mean “view or editor.” When you catch me doing this, just shake your head and move onward. When I’m being very careful, I use the official Eclipse terminology. I refer to views and editors as parts of the Eclipse workbench. Unfortunately, this “parts” terminology doesn’t stick in peoples’ minds very well.

An area of the Eclipse workbench might contain several views or several editors. Most Eclipse users get along fine without giving this “several views” business a second thought (or even a first thought). But if you care about the terminology surrounding tabs and active views, here’s the scoop:

check.png Tab: Something that’s impossible to describe except by calling it a “tab.” That which we call a tab by any other name would move us as well from one view to another or from one editor to another. The important thing is, views can be stacked on top of one another. Eclipse displays stacked views as if they’re pages in a tabbed notebook. For example, Figure 3-14 displays one area of the Eclipse workbench. The area contains five views (the Problems view, the Javadoc view, the Declaration view, the Search view, and the Console view). Each view has its own tab.

A bunch of stacked views is called a tab group. To bring a view in the stack to the forefront, you click that view’s tab.

And, by the way, all this stuff about tabs and views holds true for tabs and editors. The only interesting thing is the way Eclipse uses the word “editor.” In Eclipse, each tabbed page of the editor area is an individual editor. For example, the Editor area in Figure 3-16 contains three editors (not three tabs belonging to a single editor).

check.png Active view or active editor: In a tab group, the view or editor that’s in front.

In Figure 3-16, the MyFirstJavaClass.java editor is the active editor. The Mortgage.java and ThingsILike.java editors are inactive.

Figure 3-16: The Editor area contains three editors.

9780470371749-fg0316.tif

What’s inside a view or an editor?

The next several terms deal with individual views, individual editors, and individual areas.

check.png Toolbar: The bar of buttons (and other little things) at the top of a view (see Figure 3-17).

check.png Menu button: A downward-pointing arrow in the toolbar. When you click the menu button, a drop-down list of actions appears (see Figure 3-18). Which actions you see in the list varies from one view to another.

check.png Close button: A button that gets rid of a particular view or editor (see Figure 3-19).

check.png Chevron: A double arrow indicating that other tabs should appear in a particular area (but that the area isn’t wide enough). The chevron in Figure 3-20 has a little number 2 beside it. The 2 tells you that, in addition to the two visible tabs, two tabs are invisible. Clicking the chevron brings up a hover tip containing the labels of all the tabs (see Figure 3-20).

check.png Marker bar: The vertical ruler on the left edge of the editor area. Eclipse displays tiny alert icons, called markers, inside the marker bar. (For example, see Figure 3-12.)

Figure 3-17: The Package Explorer view’s toolbar.

9780470371749-fg0317.tif

Figure 3-18: Clicking the Package Explorer view’s menu button.

9780470371749-fg0318.tif

Figure 3-19: An editor’s close button.

9780470371749-fg0319.tif

Figure 3-20: The chevron indicates that two editors are hidden.

9780470371749-fg0320.tif

Returning to the big picture

The next two terms deal with Eclipse’s overall look and feel.

check.png Layout: An arrangement of certain views. The layout in Figure 3-3 has seven views, of which four are easily visible:

• At the far left, you see the Package Explorer view.

• On the far right, you have the Task List view and the Outline view.

• Near the bottom, you get the Problems, Javadoc, Declaration, and Console views.

Along with all these views, the layout contains a single editor area. Any and all open editors appear inside this editor area.

check.png Perspective: A very useful layout. If a particular layout is really useful, someone gives that layout a name. And if a layout has a name, you can use the layout whenever you want. For example, the workbench of Figure 3-3 displays Eclipse’s Java perspective. By default, the Java perspective contains six views in an arrangement very much like the arrangement shown in Figure 3-3.

tip.eps The Console view appears in Figure 3-3, but the Console view doesn’t always appear as part of the Java perspective. Normally, the Console view appears automatically when you run a text-based Java program. If you want to force the Console view to appear, choose Window⇒Show View⇒Other. In the resulting Show View dialog box, expand the General branch. Finally, within that General branch, double-click the Console item.

Along with all these views, the Java perspective contains an editor area. (Sure, the editor area has several tabs, but the number of tabs has nothing to do with the Java perspective.)

You can switch among perspectives by choosing Window⇒Open Perspective in Eclipse’s main menu bar. This book focuses almost exclusively on Eclipse’s Java perspective. But if you like poking around, visit some of the other perspectives to get a glimpse of Eclipse’s power and versatility.