Introduction to eclipse

Getting Started with Eclipse for Beginning Programmers :
Contents :

1. Introducing Eclipse
2. Installing and Starting Eclipse
3. Our First Eclipse Project
4. Code Editing Tools
5. Navigating Through Code
6. Java Source Generation
7. Javadoc

Target Audience: this tutorial is geared toward the beginning Java programmer who has some experience with Java programming from the command-line.

When you first learned how to write Java programs, you probably started by writing in a text file, compiling using the javac command, then running your program from the command-line using the java command. This form of programming is what we'll refer to as command-line programming, and follows the practice of edit-compile-execute. While command-line programming has many advantages, it can be quite tedious. After all, your text editor doesn't usually provide much outside of... well... editing. Professional developers, generally speaking, tend to gravitate toward what is called an integrated development environment (IDE) for their programming. The idea of an IDE is to integrate many different tools into a single program (e.g. code editing, compiling, running, file management, code navigation, documenting, etc.) Programming with an IDE can provide some of the following advantages over command-line programming:
  • Compiling is built-in. Whenever you hit "Save", your code is compiled for you.
  • controlled execution environment means that you can control how exactly your program will be executed without changing what your current system is configured for (e.g. running your program using different Java virtual machines)
  • Graphical User Interface (GUI) provides immediate feedback on compile errors, warnings, and other problems with your project.
  • IDEs are highly customizable. From formatting and coloring preferences to programming in various languages and technologies, IDEs are extremely extensible.
  • Code editing and navigation is much easier because the IDE "understands" the language you're working with (you'll understand more of what this means with a few examples).
  • IDEs support large projects by providing many other tools not related directly to programming, but with software development in general.
In this tutorial we'll be covering Eclipse, a professional-grade, open-source development platform for Java (and many other languages!). We'll focus on some of the features found in Eclipse that are not found in command-line programming. A note about audience. We will be assuming two different users of this tutorial:
  • Home users: users working on their own machine, who can devote permanent space to their Eclipse work.
  • Lab users: users working in public laboratories who cannot devote permanent space to their Eclipse work. Lab users may need some special information specific to their lab, such as the proper location of their workspace. We may defer to yourlab instructor to get this specific information.

Home Users: follow these instructions.
  1. Go to and click on Download Eclipse.
  2. Find the Eclipse for Java Developers link on the page. Click on the link for your operating system along the right-hand side.
    Eclipse for Java Developers Figure 1: Downloading the Eclipse for Java Developers
  3. Select a mirror and download the file. Make sure that you are downloading a zip file.
  4. Once the zip file is downloaded, unzip the file to a location on your computer. I usually choose something likec:\eclipse-3.4. Remember this location - we will refer to this location as <YOUR INSTALL LOCATION>.
  5. Start Eclipse by executing <YOUR INSTALL LOCATION>/eclipse/Eclipse.exe

Starting Eclipse

When you first start Eclipse, you will be asked to select your workspace. Like this:
Choosing a Workspace
The Eclipse workspace is a permanent location for all of your work.
  • Home users: choose any location of your workspace on your hard drive. I usually choose something like c:\workspace.
The first time you start with a fresh workspace, you will be shown a Welcome view. Close the Welcome view according to the following figure
Figure 2: Closing the Welcome Screen
In most Eclipse versions, your interface looks like Figure 3. This is called the Java Perspective (which will have this icon in the upper-right: ). Feel free to mess around with the windows (called "Views"). If you want to reset the perspective to how it originally looked, go to Window > Reset Perspective. If you are not in the Java perspective, use Window > Open Perspective > Other... > Java (NOT Java Browsing!)
Figure 3: The Java Perspective

Now that we have our Eclipse workspace set up, let's set up our first project. An Eclipse project is a grouping of files, which are all part of one program. For example, you can have many Java files, the compiled Java .class files, the project's website, and other resources in a single Eclipse project. Let's start by creating a project called HelloWorld.
  1. Right click in the Package Explorer () and select New > Java Project as shown in Figure 4.
    Figure 4: Creating a new Java Project
  2. A window will pop up where you can change setting related to your project. Place HelloWorld as the name of your project. The other default settings are okay. Make sure that you select the option to Create separate folders for sources and class files.
    Figure 5: Configuring your new project
  3. Select Finish. You should see your new project appear in the Package Explorer. Click on the plus sign () to expand and look inside your project. Note: for Mac and Vista users, this may be an arrow () instead of a plus sign.
    Figure 6: Examining your new project
  4. Notice the src folder in your project. This is where we'll put all of our Java classes. If you do not have a src folder, right click on the project name and select New > Source Folder. In the resulting dialog, name the folder src. A bin folder (which will store all your compiled class files) will be automatically created for you.
So let's create a Java class called Right-click on the src folder, and select New > Class. Note: in this case, we are creating a project called HelloWorld and a class HelloWorld. Class names and project names do NOT need to be the same. Typically a project will have many classes, and none of the classes should have the same name.

  1. Figure: 7: Creating a new Java class
  2. In the Name box type HelloWorld for the name of your class (you do not need the .java extension). Also, check the box that says public static void main(String[] args) as method stub that you would like generated. Your screen should look like this.
    Figure 8: Naming and Configuring the New Class
  3. Hit Finish. Eclipse generated a file called, and placed stubs for comments and the main method. A Java editor has also been opened.
    Figure 9: Editing our new class
  4. Place the print statement for the string literal "Hello, World": System.out.println("Hello, World"); . Press the Save () button at the top (or hit Ctrl+S). If you type the print statement into the editor, you may notice a red Compiler Error Iconshow up to the left of your line. Eclipse is trying to compile your code as you type, and since you have an uncompleted statement, a compilation error is shown. Just ignore the red Compiler Error Icon for now, and focus on finishing your statement. If you have a red Compiler Error Icon after completing your statement, then you can investigate the compiler error.
    Figure 10: Adding our print statement and saving.
  5. When you just hit Save there, that compiled the program - equivalent to running the command javac HelloWorld.javaon the command-line. If there are any compile errors, they will pop up in the Problems view () after you hit Save. Additionally, the line of code with a compiler error will have a red Compiler Error Icon to the left, and there will be a red line under the code. If there are no compile errors, then right-click on in the Package Explorer and select Run as... > Java Application.
    Figure 11: Running a Java program
  6. The output to your program gets printed out to the Eclipse Console view (). We just ran our first Java program in Eclipse!! If you do not see the Console view, select Window > Show View > Console. You may need to rerun your program for the output to display as seen in Figure 12.
    Figure 12: Viewing console output

Now that we can create and run a program, let's create a larger program to demonstrate some of Eclipse's powerful code editing tools. As we create this program, we will cover the following features:
  • Quick Fix
  • Auto-complete
  • Code Templates and Formatter

Creating a New Project

Multiple projects can exist in a single Eclipse workspace. Let's create a new project called MovieInventory that will keep track of our DVDs. Inside your project, create a class file called MovieInventoryMovieInventory will keep track of the movies in our collection. Do not give MovieInventory a main method (typically most classes in a larger application will NOT have mainmethods. You only need one main method to start your program.)

Quick Fix

The Eclipse editor knows a lot of common errors. By storing patterns of common errors, Eclipse can give you a "Quick Fix" for your problem.
  1. First, let's define a field (instance variable) in our MovieInventory class to hold all of the Movies in our collection. Place this at the top of your MovieInventory class and then hit Save Save Button Icon:
    private Movie [] movies;
    Editor with compiler error Figure 13: Adding a field to the MovieInventory class to keep track of Movies.
  2. Looks like we've got a compiler error. (Remember that saving automatically compiles our code.) You can tell this in several ways:
    • There's a red squiggly under our new variable
    • There's a little red X along the left-hand side of editor: 
    • The Problems view at the bottom shows an error:
  3. ProblemsView Figure 14: The Problems View
    The compiler error states: "Movie cannot be resolved to a type." This error means there is no class in the JDK named Movie that we can create an object from. However, we would like to use a Movie object to keep track of all the information about a Movie. Therefore, we're going to have to create our own Movie class. HOWEVER! You may also notice a little lightbulb on the error icon: QuickFix icon. This means that Eclipse has an idea for how to fix your problem. In our case, all we need to do is create a Movie class. Let's let Eclipse do this for us.
  4. With your text cursor anywhere inside the red squiggly, hit Ctrl + 1 (that's the number ONE; Mac users, try Apple + 1). Up pops the quick-fix menu:
  5. Quick Fix Menu Figure 15: The Quick Fix Menu
  6. Notice all of the options here. Select the first option, to create class 'Movie' by hitting Enter. Eclipse will bring up a wizard for creating a new class. The class name will be entered for you. Hit Finish to create the new class.
    Creating a Movie Class Figure 16: Create a Movie Class
  7. Let's switch back to our MovieInventory class to keep working on our inventory. Switch back to editor (Ctrl + F6 is the keyboard shortcut, Mac users try Fn+Apple+F6).
The Eclipse Quick Fix tool can be very powerful, but also limited to very common and easily-solvable problems. The Quick Fix will only work on compile errors, not logic errors, for example. Quick Fix may not always fix your code exactly how you want to, so it's not a good idea to completely rely on this feature (it's only meant to save you time, anyway). Some common fixes are finding an import, creating a class/method/variable, public/private access, fixing parameters in a method, and many others.

Using Quick Fix for "Error-Driven Development"

One way to use Quick Fix is to first write your code ignoring all of your declarations. If you want to call a class you haven't written yet, just use it how you plan on using it, then use quick fix to do all of the declarations. It takes some getting used to, but allows you to write code very quickly in the end because you don't have to do so many declarations. I find myself writing code in this way because I can simply write what I am currently thinking about without having to stop and deal with details that can be Quick-fixed anyway. You might find that this way of writing code is not so different from writing pseudocode first!


  1. We have a field that can hold our movie inventory. Now, we need to initialize our field to hold 10 movies. We should create a constructor for MovieInventory to initialize our field. Eclipse can simplify the creation of our constructor by using auto-complete.
  2. Constructors have the same name as the class. On a new line, start typing in MovieInventory. You only need to type in 'M,' like this:
    Auto-complete for a Constructor Figure 17: Beginning to create a constructor
  3. Now press Ctrl + Space. Your text cursor should be just to the right of the M (as if you were in the middle of typing the variable MovieInventory). Here's what the menu looks like:
    Auto-complete menu Figure 18: Auto-complete menu
  4. This is the auto-complete menu. Note the MovieInventory default constructor is at the top of the list. Hit Enter to add the constructor's header.
  5. We can also use auto-complete to help us remember variable names. In the constructor, we want to initialize our Movie's array. If we start typing in the name of the array, and then hit Ctrl + Space, Eclipse will help us by suggesting variable names. Additionally, when we go to fill in the size of the Movie array, we can substitute in a constant name for the value we want to use. Quick Fix can then be used to create the class constant for the size of the array. When you are done, your code should look like the code in Figure 19.
MovieInventory completed constructor code Figure 19: Completed MovieInventory constructor
Hint : Any time you want to finish something that you think Eclipse can guess, it's worth hitting Ctrl + Space to see if it does. Eclipse will find things like method names, variables in the current scope, class names, or even make suggestions for a variable you're declaring! The idea is that you don't have to remember everything about the program you're writing. You can select the options with your mouse, but it's probably faster to use the arrow keys and the Enter key.

Code Templates and Formatter

Eclipse provides several code templates for commonly used methods and statements. Additionally, Eclipse can help you keep your code well formatted (which will help you lose less style points on your programming assignments).
  1. If you have a main method in your MovieInventory class, please delete it.
  2. With your text cursor in the program, start typing the word main and hit Ctrl+Space.
    Main method template generator Figure 20: The Main method code template
  3. There should be a code template (with the following icon: ) for the main method. Hit Enter to select it.
  4. Voila! There's our main method! Note that the text cursor lands in the middle of the method so you can just start typing code.
    Main method Figure 21: The Main Method
  5. Eclipse has another helpful code template called sysout. Invoke the sysout template the same way you did the maintemplate. (If you type all of sysout before hitting Ctrl + space, the menu doesn't pop up because there's only one option!).
  6. Now that we have our System.out.println(); call from the code template, type a String literal and ensure that your program prints it when you run MovieInventory.
    System.out.println() Figure 22: System.out.println
  7. Once you know that your program works, take a look at your code. Methods should be indented within classes, and statements should be indented within methods. If your code does not follow proper indentation and before you start formatting yourself, hit Ctrl + Shift + F (or go to the Source > Format in the menu; Mac users try Apple + Shift + F).
  8. If you want to add/edit code templates or the way your code gets formatted, go to Window > Preferences (Mac Users it'sEclipse > Preferences).
    • For code templates, go to Java > Editor > Templates. You can also start typing "Code templates" in the top text box to find the menu.
    • For the formatter, go to Java > Code Style > Formatter. You can also start typing "Formatter" in the top text box to find the menu
    Figure 23: Eclipse Preferences for Code Templates
Here are a few other key code templates:
  • There are several for code templates that will create a for-loop for you
  • The foreach template will search upward from your current location and find the nearest Iterable type and create an enhanced for-loop over it.
  • The test code template will create a JUnit 3 test method for you
  • Typing /** before a method will generate Javadoc, inferring the parameters to your method

Eclipse provides some tricks for traversing through code. In this section we'll cover:
  • Going to the declaration by clicking
  • Package explorer
  1. Go to your program. Hold down the Control key and hover your mouse over the declaration ofMovie. The Movie should turn into a hyperlink.
Code Navigation via class hyperlinks Figure 24: Turning class declarations into hyperlinks
  1. With Control still held down, click on the Movie hyperlink (Mac users try the Apple key). This will take you to the Movieclass.
  2. In general, if you Ctrl + Click on something, you'll go to where it is defined. So clicking on the Movie() constructor call will go to the class declaration (if a constructor were defined for Movie, then you would go to the constructor). This can save you a lot of time of finding where something is defined. If you cannot get it to work, make sure you've got the following things:
    • Make sure the current file is saved. Sometimes compilation will refresh what Eclipse knows about each class.
    • Make sure that you have all of your compile errors fixed.
    • Sometimes you need to hold down the Control key for a half-beat before the hyperlinks show up.
    • If you hover too long, the hyperlinks go away.
  3. The Package Explorer  can also be a very helpful view for managing large projects. Notice that we have our two classes in the Package Explorer already.
    Package Explorer Figure 25: Our Package Explorer
  4. Use the plus sign  (or arrow on Vista machines) to expand each element of our src folder. Here we see all of methods, instance variables, and static variables of our class.
    Package explorer expanded Figure 26: Expanding each part of our classes

Eclipse provides source generation of commonly used code. You will typically want to use source generation when creating plain old java objects (POJOs) or when you want to override methods from the Object class. Source code generation is only useful if you have specified data (or state) for your object. Let's create some state for our Movieobject. A Movie should keep track of its titlerelease yeargenre, and rating. Additionally, a Movie object should be immutable.
  1. Add the following code to create fields (instance variables) for Movie's state.
  2. Movie's State Figure 27: Movie's state
  3. Each of the fields has a yellow warning next to the line of code. The warning states that the field is never used locally. The lightbulb next to the warning triangle let's us know there is a quick fix. One will delete the field. Another will generate the getter (accessor) and setter (mutator) for the field. Typically, when creating fields you will want to generate getters and setters as appropriate to your class.
We want to make our Movie class immutable. Therefore, we do NOT want to create setters. The Quick Fix option only provides functionality for creating BOTH getters and setters. Additionally, the Quick Fix option only works on one field at a time. We can use another piece of Java's built in functionality to provide a more general code generation that also allows for selection of just getters. Right click anywhere in the Editor view. Select Source > Generate Getters and Setters....
    Source context menu Figure 28: Source Context Menu
All of the fields in the Movie class are displayed. We can press the Select Getters button to the right to generate getters for all of the fields. Using the arrows will display which of the methods will be created for each field. If you would like to save your self a little more time, select the check box next to Generate method comments. Additionally, you may want to change the insertion point so that the new methods are positioned at after the fields. Click Finish when you are done selecting options. The newly generated code will display in the Editor view. You'll want to save Movie, which will remove the earlier warning associated with each field.
    Generate getters and setters Figure 29: Generate getters and setters
Check that the getter methods were properly generated and added to the Movie class.
    Generated setters Figure 30: Generated setters
  1. Now that we've created state and getter methods for our Movie class, we'll need to provide a mechanism for creating a new Movie object. One way we could do that is by using the default constructor and providing setter methods, but that does not guarantee that a Movie object will be fully created by a user and violates our requirement of immutability. A better way to create a Movie object is through the use of a constructor where the user passes in values for each of Movie's fields.
Like the generation of getters and setters, Eclipse will generate a constructor for us. The file that you want to add the constructor to (Movie) should be displayed in the editor view. Right click in the editor and select Source > Generate Constructor using Fields.... You will select which fields you want to include in the constructor. Just because you have a field in your class does not require that a value is passed in as a parameter to the constructor, so you can leave fields unchecked. You should handle initialization of those fields within the constructor to the appropriate default value. If you would like to save your self a little more time, select the check box next to Generate constructor comments. Additionally, you may want to change the insertion point so that the constructor is positioned above your getter methods. Select OK.
    Constructor code generation Figure 31: Constructor code generation
Check that the constructor was added to your Movie class.
    Movie Constructor Figure 31: Generated Movie Constructor code
  1. The Object class is the parent of all Java objects, and provides many useful methods that we use frequently when developing software: equals()hashcode(), and toString(). However, Object's implementation of these methods may not be as robust as what we may want in our code. Eclipse can help us generate overridden versions of these methods for use in our objects.
The equals() method compares two object's to determine if they are equivalent. The default implementation of theequals() method is to compare the location's of the objects in memory. If the objects are in the same location, then they are the same object, and therefore equal. However, we may want to define object equality differently. Typically, objects are considered the same if some or all of their fields have the same values. We can override the equals()method to define that two Movies are the same if their fields are equivalent. Eclipse requires that if you override the equals() method using code generation that you also override thehashcode() method using code generation. This is to ensure that an object's hash is the same if the two objects are equal (you'll discuss hashes in data structures), and is an invariant of the Java programming language. To override the equals() and hashcode() methods, ensure that the class you're generating the methods in is active in the Editor view. Right click in the Editor, and select Source > Generate hashcode() and equals(). In the resulting dialog, select which fields are required for object equality. If you would like to save your self a little more time, select the check box next to Generate methods comments. Additionally, you may want to change the insertion point so that the new methods are positioned at the bottom of your getter methods. Click OK.
    Generate equals() and hashcode() Figure 32: Generate equals() and hashcode() methods
Check that the methods were generated in your source. Don't forget to save your changes!
    Generated equals() and hashcode() methods Figure 33: Generated equals() and hashcode() methods

Commenting your code is important! Comments describe what the code is for. At a minimum, you should comment your class, fields, and methods. Java provides a tool, called Javadoc, that will generate a set of webpages that display the comments for your code. Every time you use the Java API, you are using webpages generated with the Javadoc tool. Kindly, the Java developers have done an excellent job of commenting the class files in the Java SDK. You can then use the API to find classes and methods that may help you implement the code that you're implementing. You should return the favor to those that may use your code by providing comments. By providing the comments in a Javadoc format, you'll be able to generate an API for your code that will benefit future programmers. After you have written your Javadoc in your class files, you will want to run the Javadoc tool on your code. You can run Javadoc by selecting Project > Generate Javadoc. In the resulting dialog, you will need to configure the Javadoc command, if you don't already have the command configured. To configure your Javadoc command, select the Configure button. Browse to the location where you installed your JDK. The javadoc tool is in the bin folder. Additionally, you can select which projects/packages/classes/and files you want to run Javadoc on. Eclipse will default to generating your Javadoc in a new folder called doc within your project file.
    Javadoc generation Figure 34: Generate Javadoc
Selecting Next will allow you to edit additional details about the generated Javadoc, but the default settings should be sufficient for the Javadoc you'll create for this class. Selecting Finish will generate the Javadoc. If you don't have a doc folder in your project already, you will be prompted to create the destination folder. Select Yes To All. When the Javadoc has been created, you will need to refresh your project listing in the Package Explorer Package Explorer. You can do this by selecting your project and pressing F5. When you open your project, you should see a doc directory. Selecting index.html within the doc directory will open a Browser window in your editor with your newly generated Javadoc.
    Generated Javadoc Figure 35: Generated Javadoc
Any time you update your Javadoc, you should regenerate the html files.
You might be interested in :

No comments:

Post a Comment