Bonus Chapter 1: Using Eclipse

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Bonus Chapter 1: Using Eclipse

In This Chapter
✓ Understanding Eclipse projects and Workbenches
✓ Creating a Java project
✓ Compiling, running, and debugging with Eclipse
✓ Refactoring with Eclipse

E clipse is a development environment that includes many powerful


features for creating Java programs. Because Eclipse is free and very
powerful, it has become popular among Java developers. In this chapter,
you discover the basics of using Eclipse for simple Java development.

Because Eclipse is such a powerful tool, it has a steep learning curve.


If you’re brand new to Java, I suggest that you start out using a simpler
environment, such as TextPad (described in Book I, Chapter 3) and turn to
Eclipse only after you have your mind around some of Java’s programming
fundamentals. That way, you start by concentrating on Java programming
rather than on mastering Eclipse.

When you’re ready to get started with Eclipse, go to www.eclipse.org,


click the Download Eclipse button, and download the current version of
Eclipse IDE for Java Developers. Unlike most programs, Eclipse doesn’t have
a complicated setup program. You just download the Zip file, extract all the
files, and then run the Eclipse executable file (eclipse.exe) directly from
the folder you extracted it to.

If you’re using Windows, you may want to add a desktop shortcut for Eclipse
to make it more convenient to start. To do that, open the folder that contains
the eclipse.exe file, right-click the file and drag it to the desktop, release the
mouse button, and choose Create Shortcut from the menu that appears.
Then you can start Eclipse by double-clicking this desktop shortcut.

Many of the techniques that I describe in this chapter won’t make much
sense to you until you know how to use the Java programming features to
which they apply. (The information about how to create a new Java class
file, for example, won’t make much sense until you read about creating Java
classes in Book III.) As you find out about Java programming features in
later chapters, you may want to refer to this chapter to read about related
Eclipse features.

9781118408032-bc01.indd 1 3/8/2014 12:53:43 AM


BC1-2 Getting Some Perspective on Eclipse

Getting Some Perspective on Eclipse


Eclipse is designed to be a general purpose integrated development
environment (IDE), which means that it isn’t specifically designed for Java.
It’s like the Seinfeld of IDEs: As its own designers put it, Eclipse is “an IDE for
anything and nothing in particular.” You can easily customize Eclipse with
plug-in components called features that make it useful for specific types of
development tasks. Also, because Eclipse is most commonly used for Java
program development, it comes preconfigured with features designed for
developing Java programs.

Eclipse uses some unusual terminology to describe its basic operation.


These terms, in particular, are worth a look:

✦ Workbench: The Workbench is the basic Eclipse desktop environment.


When you run Eclipse, the Workbench opens in a window like the one
shown in Figure 1-1.
If you can juggle and chew gum at the same time, you may want to open
two Workbench windows so you can work on two projects at the same
time. Those of us who have less-than-superhero abilities of concentration
can work with just one Workbench window at a time.

Figure 1-1:
The Eclipse
Workbench
window.

9781118408032-bc01.indd 2 3/8/2014 12:53:43 AM


Getting Some Perspective on Eclipse BC1-3

✦ Editor: An editor is a Workbench pane that’s designed for editing a


certain type of file. Eclipse comes with a standard text editor that can
edit any kind of text file and a special Java editor that’s specifically
designed for editing Java programs. In Figure 1-1, the Java editor is in the
middle portion of the Workbench window.
The Java editor in this figure looks small because I captured this screen
image with the computer’s monitor set to 800 x 600 pixels. Because
Eclipse puts so much information on the screen, however, running it
on a large monitor (preferably 19 inches or larger) at a resolution of at
least 1,024 x 768 is best. That way, the editor window is large enough
to let you work with your program’s text comfortably while leaving
ample room for the other elements displayed in the Eclipse Workbench
window.
Strictly speaking, an editor is a type of view (covered next in this list).
✦ Views: A view is a pane of the Workbench window that displays
other information that’s useful while you’re working with Eclipse.
Figure 1-1 shows several views in addition to the editor, such as
Package Explorer View, which lets you navigate the various files that
make up an Eclipse project, and Problems View, which displays error
messages.
You can display a view in its own pane or combine it with other views
in a single pane, in which the views are indicated by tabbed dividers
that you can click to call up each view in the pane. Problems View in
Figure 1-1, for example, shares its pane with two other views, called
Javadoc and Declaration.
✦ Perspective: A perspective is a collection of views designed to help
you with a specific type of programming task. The Workbench window
pictured in Figure 1-1 shows the Java perspective, which is designed for
working with Java program files. Figure 1-2 shows a different perspec-
tive, called the Debug perspective. In this perspective, the Java editor
is still present, but a different set of views that are useful for testing
and debugging Java programs is shown. Console View appears at the
bottom of the window so that you can see the output created by the
program, and Variables View lets you monitor the contents of variables
as the program executes. (For more information about the Debug
perspective, see the section “Debugging a Java Program,” later in
this chapter.)

9781118408032-bc01.indd 3 3/8/2014 12:53:43 AM


BC1-4 Understanding Projects

Figure 1-2:
Debugging
a program in
Eclipse.

Understanding Projects
An Eclipse project is a set of Java files that together build a single Java
program. Although some simple Java programs consist of just one file, most
real-world Java programs are made up of more than one Java program file.
In fact, a complicated Java program may require hundreds of Java program
files. When you work on programs that require more than one file, Eclipse
lets you treat those files as a single project.

A project consists not just of Java source files, but also the class files that are
created when you compile the project and any other files that the program
requires. Those files might include data or configuration files, as well as
read-me files, program documentation, image or sound files, and so on.

All the files for a project are stored together in a project folder, which may
include subfolders if necessary. In addition to the files required by the
program, the project folder includes files that are created by Eclipse to
store information about the project itself. A file named .project stores
descriptive information about the project, for example, and a file named
.classpath stores the locations of the classes used by the project.

9781118408032-bc01.indd 4 3/8/2014 12:53:43 AM


Creating a Simple Project BC1-5

All your project folders are stored in a folder called the workspace. Each
time you start Eclipse, a dialog box appears, asking for the location of the
workspace folder. If you want to change to a different workspace, choose
File➪Switch Workspace.

Eclipse lets you create two types of projects:

✦ For simple projects that have just a few Java source files, you can create
a project that stores all the project’s Java files in a single folder. Then,
when those files are compiled, the resulting class files are stored in this
same folder. This type of project is the easiest to work with, and it’s ideal
for small and medium-size projects.
✦ For large projects — those that involve dozens or even hundreds of Java
source files — you can create a project that uses one or more subfolders
to store source files. Then you’re free to create whatever subfolders you
want to help you organize your files. You might create one subfolder for
user interface classes, another for database access classes, and a third
for image files displayed by the application.

Eclipse’s File menu offers an Open File command, but it isn't very useful.
Instead, Package Explorer View (on the left side of the Java perspective; refer
to Figure 1-1) displays a list of all the Java projects in your workspace. When
you start Eclipse, the project you were working on last appears onscreen
automatically. You can switch to a different project by right-clicking the
project in Package Explorer View and then choosing Open Project, and you
can open an individual file in a project by double-clicking the file in Package
Explorer View.

Creating a Simple Project


The following procedure takes you through the process of creating a simple
project based on a slightly more complicated version of the Hello, World!
program from Book I, Chapter 1. Follow these steps to create this application:

1. Start Eclipse, and click OK when the Workspace Launcher dialog box
appears.
The Workspace Launcher dialog box asks for the location of your
workspace folder; in most cases, the default location is acceptable.
When you click OK, Eclipse opens with the Java perspective, with no
projects or files displayed, as shown in Figure 1-3.

9781118408032-bc01.indd 5 3/8/2014 12:53:44 AM


BC1-6 Creating a Simple Project

Figure 1-3:
Eclipse
waits for
you to
create a
project.

2. Choose File➪New➪Java Project.


The New Java Project dialog box appears, as shown in Figure 1-4.

Figure 1-4:
The New
Java Project
dialog box.

9781118408032-bc01.indd 6 3/8/2014 12:53:44 AM


Creating a Simple Project BC1-7

3. Type HelloApp in the Project Name text box.


The other options in this dialog box let you specify whether the project
should be stored in the workspace folder or some other folder and
whether the project should use the project folder for source files or
create separate subfolders for source files. The default settings for these
options are fine for the HelloApp application.
4. Click the Finish button.
When you click Finish, you return to the Java perspective, where HelloApp
now appears in Package Explorer View to indicate that you’ve added a proj-
ect by that name to your workspace.
5. Right-click HelloApp in Package Explorer View and then choose
New➪Class from the shortcut menu that appears.
The New Java Class dialog box opens, as shown in Figure 1-5.

Figure 1-5:
The New
Java Class
dialog box.

6. Set options for the new class.


For this exercise, set the options as follows:
• Enter javaAIO in the Package text field.
• Enter HelloApp in the Name text field.
• Select the Public Static Void main(String[] args) check box.
7. Click Finish.
The HelloApp.java file is created, and Eclipse displays it in the Java
editor, as shown in Figure 1-6.

9781118408032-bc01.indd 7 3/8/2014 12:53:44 AM


BC1-8 Creating a Simple Project

Figure 1-6:
The newly
created
HelloApp
class.

8. Edit the main method.


Move the insertion point to the empty block for the main method and
then edit it to look exactly like this:
public static void main(String[] args) {
String[] w = new String[3];
w[0] = "Hello";
w[1] = ", ";
w[2] = "world!";
for (int i = 0; i<3; i++)
System.out.print(w[i]);
}

9. Choose Run➪Run As➪Java Application.


The program is compiled and run. A console window with the program’s
output appears at the bottom of the Eclipse window, as shown in
Figure 1-7.

Note: If a Save Resources dialog box appears before the program runs,
click OK. Then the program runs.

9781118408032-bc01.indd 8 3/8/2014 12:53:44 AM


Adding a Class File BC1-9

Figure 1-7:
The
HelloApp
program in
Eclipse.

Adding a Class File


In this section, I walk you through the process of adding a second class
file to the HelloApp application. This second class demonstrates some of
Eclipse’s most useful features for speeding Java program development by
generating code for commonly used class features.

Unless you’ve already read Book III, you may get bewildered early on by the
code that’s presented in this procedure. Don’t worry; this code will make
complete sense after you read about creating your own classes.

Follow these steps to add a second class to the HelloApp application:

1. Right-click the JavaAIO branch of the HelloApp project in Package


Explorer View, and choose New➪Class.
The New Java Class dialog box opens; refer to Figure 1-5.
2. Set the options for the new class.
For this class, set the options as follows:
• Leave the Package text field set to JavaAIO.
• Enter HelloSayer in the Name text field.
• If it isn’t already cleared, clear the Public Static Void
main(String[] args) check box.

9781118408032-bc01.indd 9 3/8/2014 12:53:44 AM


BC1-10 Adding a Class File

3. Click Finish.
A new class file named HelloSayer is created, and Eclipse opens it in a
Java editor.
4. Add declarations for two public fields named greeting and addressee.
Add these lines immediately after the line that declares the HelloSayer
class. Then, other than the comments and the package statement that
appears at the beginning of the class, the class looks like this:
public class HelloSayer {

private String greeting;


private String addressee;

5. Use a wizard to add a constructor to the class.


To do that, choose Source➪Generate Constructor Using Fields. The
Generate Constructor Using Fields dialog box appears, as shown in
Figure 1-8.

Figure 1-8:
Eclipse can
create cons-
tructors
for you
auto-
matically.

Check both greeting and addressee in the list of fields to initialize,


choose First Member from the Insertion Point drop-down list, select the
Omit Call to Default Constructor Super() check box, and then click OK.
The following code is inserted into the class:

9781118408032-bc01.indd 10 3/8/2014 12:53:45 AM


Adding a Class File BC1-11

public HelloSayer(String greeting, String addressee) {


this.greeting = greeting;
this.addressee = addressee;
}

6. Add the code for a method named sayHello.


Add the following code after the constructor you created in Step 5,
immediately before the closing brace (}) in the last line of the program:
public void sayHello()
{
System.out.println(greeting + ", " + addressee
+ "!");
}

The entire HelloSayer class file is shown in Listing 4-1.

Listing 4-1: The HelloSayer Class


package JavaAIO;

public class HelloSayer {

private String greeting;


private String addressee;

public HelloSayer(String greeting, String addressee)


{
this.greeting = greeting;
this.addressee = addressee;
}

public void sayHello()


{
System.out.println(greeting + ", " + addressee
+ "!");
}

7. Click the HelloApp.java tab at the top of the Java editor pane.
(Refer to Figure 1-8.) The HelloApp.java file comes to the front so that
you can edit it.
8. Edit the main method so that it uses the new HelloSayer class.
To do so, delete the code that was in the main method and replace it
with this code:
public static void main(String[] args) {
HelloSayer h =
new HelloSayer("Hello", "World!");
h.sayHello();
}

9781118408032-bc01.indd 11 3/8/2014 12:53:45 AM


BC1-12 Running a Program

The entire HelloApp.java class now looks like Listing 4-2. Eclipse
generated all the code except the two lines in the main method.

Listing 4-2: The HelloApp Class


package JavaAIO;

public class HelloApp {

/**
* @param args
*/
public static void main(String[] args) {
HelloSayer h =
new HelloSayer("Hello", "World");
h.sayHello();
}

Running a Program
After you enter the source code for your Eclipse project, you can run it to
see whether it works as expected. Eclipse gives you several ways to run a
Java program:

✦ In Package Explorer View, select the source file for the class you want to
run and then choose Run➪Run As➪Java Application.
✦ Right-click the source file for the class you want to run and then choose
Run➪Java Application from the shortcut menu that appears.
✦ Select the source file in Package Explorer View, click the Run button (shown
in the margin), and choose Run As➪Java Application from the menu that
appears. (If you recently ran the program, you can also choose the program
from the list of recently run programs that appears in this menu.)

When the program runs, its console output is displayed in a Console View
that appears below the Java Editor pane, as shown in Figure 1-9.

Note: If the program uses Swing to create a window, that window is displayed
separately, not within the Eclipse Workbench window. (See Book VI for more
on Swing.)

9781118408032-bc01.indd 12 3/8/2014 12:53:45 AM


Debugging a Java Program BC1-13

Figure 1-9:
Console
View dis-
plays the
program’s
console
output.

Eclipse is designed so that it automatically compiles Java programs as you


work on them. Every time you save a Java source file in Eclipse, the file is
automatically compiled to create a class file. As a result, you don’t have
to compile as a separate step before you can run a program. However, if
the project contains large source files, this feature can become annoying.
To disable automatic compilation, choose Project➪Build Automatically
to clear the check box next to the Build Automatically option. Then you
must build the project manually by choosing Project➪Build All before you
can run it. (To switch back to automatic builds, choose Project➪Build
Automatically again.)

Debugging a Java Program


No matter how carefully you plan your programs, sooner or later you
encounter bugs. You need to watch out for two main kinds of bugs:

✦ Incorrect results, such as a program that’s supposed to calculate test


scores but gives you a C when you score 99 out of 100, or a program
that’s supposed to calculate sales tax of 5 percent but that says the sales
tax on a $29.95 purchase is $149.75 instead of $1.50.

9781118408032-bc01.indd 13 3/8/2014 12:53:45 AM


BC1-14 Debugging a Java Program

✦ Program crashes, such as when a program that’s supposed to divide


one number into another and print the answer instead prints out this
message:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at BugApp.main(BugApp.java:19)

Then the program abruptly stops.

Fortunately, Eclipse has a powerful debugger that can help you find the
cause of either type of bug and fix it. To start the debugger, run your
program by choosing Project➪Debug As➪Java Application instead of
Project➪Run As➪Java Application. Alternatively, click the Debug button
in the Workbench toolbar, shown in the margin. Eclipse switches to Debug
perspective, as shown in Figure 1-10, and runs the program in debug mode.

Figure 1-10:
Debug per-
spective lets
you debug
errant Java
programs.

Note that when you activate the debugger, the Windows firewall may display
a security alert. If so, click Allow Access to let the debugger start. Also
note that you may want to set a breakpoint in your code before starting the
debugger. Otherwise your program may run to completion and never give
you the chance to work in the debugger. You read how to set a breakpoint in
the next section, “Stepping through your programs.”

9781118408032-bc01.indd 14 3/8/2014 12:53:45 AM


Debugging a Java Program BC1-15

The following sections describe some of the key features of the Debug
perspective that are useful for tracking down and correcting bugs in your
Java programs.

Stepping through your programs


One of the most basic skills in debugging is executing program statements
one at a time. This technique, called stepping, can be very useful in debugging.
By stepping through your program one statement at a time, you can view the
effects of each statement and identify the source of errors. Sometimes, just
knowing which statements are being executed is all you need to determine
why your program isn’t working.

In Eclipse, the Debug View section of Debug perspective is where you control
the execution of the program you’re debugging. This view displays a tree
that indicates each of the threads in your program. (If you don’t know what
threads are, don’t worry about it. Most console-based programs, such as the
BugApp program shown in Figure 1-10 earlier in this chapter, use only one
thread apiece anyway. In Book V, you find out how to code programs that
use more than one thread.)

Before you can control the execution of a thread, you must suspend the
thread so that its statements stop executing. In general, you can suspend a
thread for debugging in these ways:

✦ When an unhandled exception occurs, the thread is automatically sus-


pended. In Figure 1-10, the BugApp program’s main method is suspended
because a divide-by-zero exception occurred, and the program didn’t
catch it. If your program is throwing an exception that you don’t expect,
you can simply debug the program and allow the exception to suspend
the thread. Then you can try to track down the cause of the problem.
✦ Before you debug the program, you can set a breakpoint at any state-
ment in the program. Then, when execution reaches that statement,
the thread is suspended. To set a breakpoint, simply double-click the
left margin of the Java editor next to the statement where you want the
thread to be suspended. I define and discuss breakpoints in detail in
the section “Setting breakpoints,” later in this chapter.
If a long-running thread is in a loop, you can suspend it by clicking the
thread in Debug View and then clicking the Suspend button (shown in
the margin).

When you suspend a thread, the statement that will be executed next is
highlighted in the Java editor. Then you can continue the thread’s execution
one or more statements at a time by clicking the buttons at the top of Debug
View. Table 1-1 describes the most commonly used buttons.

9781118408032-bc01.indd 15 3/8/2014 12:53:45 AM


BC1-16 Debugging a Java Program

Table 1-1 Commonly Used Buttons


Button Name Description
Resume Resumes execution with the next statement. The
thread continues executing until it is suspended by
an uncaught exception or a breakpoint.
Terminate Terminates the thread.

Step Into Executes the highlighted statement and then


suspends the thread.

Step Over Skips the highlighted statement, executes the next


statement, and then suspends the thread.

Run to Executes the highlighted statement, continues


Return executing statements until reaching the end of the
current method, and then suspends the thread.

Examining variables
When a thread is suspended, you can examine its variables to see whether
they’re set to the values you expect. In many cases, you can discover pro-
gramming errors. If you think that a variable named customerFirstName
should contain a customer’s first name, for example, and it instead contains
the name of the state in which the customer lives, you can conclude that
you didn’t assign the variable’s value properly. (This situation might be
ambiguous if the customer happens to be named Indiana Jones, of course.)

The easiest way to examine the value of a variable is simply to point the
mouse at the variable in the Java editor. Figure 1-11 shows how the value of
the variable i appears when you hover the mouse pointer over it. Here the
pop-up message indicates that the variable i has a value of 0. (This message
might be a clue as to why the program has thrown a divide-by-zero exception.)

9781118408032-bc01.indd 16 3/8/2014 12:53:45 AM


Debugging a Java Program BC1-17

Figure 1-11:
Displaying
a variable
value.

You can also inspect variables by using Variables View, as shown in Figure 1-12.
Each variable is listed on a separate line in the top part of Variables View. In
addition, the bottom part (called the Detail pane) displays the value of the cur-
rently selected variable. Note that as you step through the various statements
in your program, variables appear in Variables View as they are declared and
disappear from view when they go out of scope.

Figure 1-12:
Variables
View shows
the value
of each
variable.

Setting breakpoints
A breakpoint is a line in your program where you want the program to be
suspended. Setting a breakpoint allows you to efficiently execute the portions
of your program that are working properly and stop the program when it
reaches the lines that you believe to be in error.

All the breakpoints in your program are listed in Breakpoints View, shown in
Figure 1-13.

9781118408032-bc01.indd 17 3/8/2014 12:53:46 AM


BC1-18 Refactoring Your Code

Figure 1-13:
Breakpoints
View is
where you
control
breakpoints.

The following paragraphs describe some of the ways you can work with
breakpoints in this view:

✦ To create a new breakpoint, right-click the vertical bar at the extreme


left edge of the code editor window next to the line you want to create
the breakpoint for. Then choose Toggle Breakpoint from the shortcut
menu that appears.
✦ The check box next to each breakpoint indicates whether the breakpoint is
enabled. Execution is suspended at a breakpoint only if the breakpoint
is enabled.
✦ You can delete a checkpoint by clicking the breakpoint to select it and
then pressing the Delete key or clicking the Remove Selected button
(shown in the margin).
✦ You can remove all the breakpoints you’ve set by clicking the Remove
All Breakpoints button (shown in the margin).
✦ If you double-click a breakpoint in Breakpoint View, the Java editor
window scrolls to the line at which the breakpoint is set.
✦ If you want the program to be suspended only after it has hit the break-
point a certain number of times, right-click the breakpoint and choose
Hit Count from the shortcut menu that appears. Then enter the number
of times you want the statement to execute before suspending the
program, and click OK.

Refactoring Your Code


Refactoring refers to the task of making mass changes in a project. Suppose
you decide that a class name you created when you started the project
doesn’t accurately describe the purpose of the class, so you want to change
it. Simple text editors such as TextPad (see Book I, Chapter 3) include a
Replace command that lets you change occurrences of text strings within a
file, but changing the name of a class requires that you change the name in
all the files in a project.

9781118408032-bc01.indd 18 3/8/2014 12:53:46 AM


Refactoring Your Code BC1-19

Eclipse includes a whole menu of refactoring options — called, as you


might guess, the Refactor menu. This menu contains more than 20 types of
refactoring commands. If you’re just starting to use Java, however, most of
these commands won’t make any sense to you. The Refactor menu contains
commands that let you do things like change an anonymous inner class to a
nested class, push members down to a subclass, or introduce a factory.

A few Refactor menu commands are especially useful as you work your way
through the basics of Java:

✦ Rename: This command lets you rename a variable, method, or other


symbol. First, select the symbol you want to rename. Then choose
Refactor➪Rename, type the new name, and click OK.
✦ Extract Method: This command lets you create a separate method from
one or more statements. Select the statements you want to place in the
method and then choose Refactor➪Extract Method. In the dialog box
that appears, type the name you want to use for the method, and then
click OK. Eclipse creates a method with the statements you selected and
replaces the original selection with a call to the new method.
✦ Inline: This command is pretty much the opposite of the Extract Method
command. It replaces a call to a method with the statements that are
defined in the body of that method. This command is most useful when
you thought a method was going to be more complicated than it turned
out to be, or you thought that you’d call it from more locations than you
ended up calling it from.
✦ Extract Local Variable: This one is weird. Sometimes, you discover
that you have a whole string of statements in a row that use a particu-
lar expression (say, x + 1). Wouldn’t it be better if you just created a
separate variable to hold the value x + 1 and then used that variable
instead of repeatedly recalculating the expression? The Extract Local
Variable command can do this for you.
To use this command, highlight the first occurrence of the expression,
and choose Refactor➪Extract Local Variable. Eclipse creates a local
variable, adds an assignment statement that assigns the expression to
the new local variable, and replaces all occurrences of the expression
with the local variable.

9781118408032-bc01.indd 19 3/8/2014 12:53:46 AM


BC1-20 Java All-in-One For Dummies, 4th Edition

9781118408032-bc01.indd 20 3/8/2014 12:53:46 AM

You might also like