Getting Started with Eclipse for Beginning Programmers :
|2.||Installing and Starting Eclipse|
|3.||Our First Eclipse Project|
|4.||Code Editing Tools|
|5.||Navigating Through Code|
|6.||Java Source Generation|
Target Audience: this tutorial is geared toward the beginning Java programmer who has some experience with Java programming from the command-line.
- Compiling is built-in. Whenever you hit "Save", your code is compiled for you.
- A 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)
- A 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.
- 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.
- Go to http://eclipse.org and click on
- Find the
Eclipse for Java Developerslink on the page. Click on the link for your operating system along the right-hand side.
- Select a mirror and download the file. Make sure that you are downloading a zip file.
- Once the zip file is downloaded, unzip the file to a location on your computer. I usually choose something like
c:\eclipse-3.4. Remember this location - we will refer to this location as
<YOUR INSTALL LOCATION>.
- Start Eclipse by executing
<YOUR INSTALL LOCATION>/eclipse/Eclipse.exe
Starting EclipseWhen you first start Eclipse, you will be asked to select your workspace. Like this:
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
Welcomeview. Close the
Welcomeview according to the following figure
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!)
- Right click in the
Package Explorer() and select
New > Java Projectas shown in Figure 4.
- A window will pop up where you can change setting related to your project. Place
HelloWorldas 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.
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.
- Notice the
srcfolder in your project. This is where we'll put all of our Java classes. If you do not have a
srcfolder, right click on the project name and select
New > Source Folder. In the resulting dialog, name the folder
binfolder (which will store all your compiled class files) will be automatically created for you.
So let's create a Java class called
HelloWorld.java. Right-click on the
srcfolder, 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.
- In the
HelloWorldfor 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.
Finish. Eclipse generated a file called
HelloWorld.java, and placed stubs for comments and the
mainmethod. A Java editor has also been opened.
- 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 show 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 for now, and focus on finishing your statement. If you have a red after completing your statement, then you can investigate the compiler error.
- 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
Problemsview () after you hit Save. Additionally, the line of code with a compiler error will have a red to the left, and there will be a red line under the code. If there are no compile errors, then right-click on
Package Explorerand select
Run as... > Java Application.
- The output to your program gets printed out to the Eclipse
Consoleview (). We just ran our first Java program in Eclipse!! If you do not see the
Window > Show View > Console. You may need to rerun your program for the output to display as seen in Figure 12.
- Quick Fix
- Code Templates and Formatter
Creating a New ProjectMultiple projects can exist in a single Eclipse workspace. Let's create a new project called
MovieInventorythat will keep track of our DVDs. Inside your project, create a class file called
MovieInventorywill keep track of the movies in our collection. Do not give
mainmethod (typically most classes in a larger application will NOT have
mainmethods. You only need one
mainmethod to start your program.)
Quick FixThe Eclipse editor knows a lot of common errors. By storing patterns of common errors, Eclipse can give you a "Quick Fix" for your problem.
- First, let's define a field (instance variable) in our
MovieInventoryclass to hold all of the
Movies in our collection. Place this at the top of your
MovieInventoryclass and then hit Save :
private Movie  movies;
- 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:
Problemsview at the bottom shows an error:
- 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:
- 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.
- Let's switch back to our
MovieInventoryclass to keep working on our inventory. Switch back to the
MovieInventory.javaeditor (Ctrl + F6 is the keyboard shortcut, Mac users try
The compiler error states: "
Moviecannot be resolved to a type." This error means there is no class in the JDK named
Moviethat we can create an object from. However, we would like to use a
Movieobject to keep track of all the information about a
Movie. Therefore, we're going to have to create our own
Movieclass. HOWEVER! You may also notice a little lightbulb on the error 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
Movieclass. Let's let Eclipse do this for us.
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!
- 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
MovieInventoryto initialize our field. Eclipse can simplify the creation of our constructor by using auto-complete.
- 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:
- 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:
- This is the auto-complete menu. Note the
MovieInventorydefault constructor is at the top of the list. Hit
Enterto add the constructor's header.
- 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
Moviearray, 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.
Hint : Any time you want to finish something that you think Eclipse can guess, it's worth hitting
Ctrl + Spaceto 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
Code Templates and FormatterEclipse 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).
- If you have a
mainmethod in your
MovieInventoryclass, please delete it.
- With your text cursor in the program, start typing the word
- There should be a code template (with the following icon: ) for the
Enterto select it.
- Voila! There's our
mainmethod! Note that the text cursor lands in the middle of the method so you can just start typing code.
- Eclipse has another helpful code template called
sysout. Invoke the
sysouttemplate the same way you did the
maintemplate. (If you type all of
Ctrl + space, the menu doesn't pop up because there's only one option!).
- 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
- 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 > Formatin the menu; Mac users try
Apple + Shift + F).
- If you want to add/edit code templates or the way your code gets formatted, go to
Window > Preferences(Mac Users it's
Eclipse > 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
- For code templates, go to
- There are several
forcode templates that will create a for-loop for you
foreachtemplate will search upward from your current location and find the nearest
Iterabletype and create an enhanced for-loop over it.
testcode template will create a JUnit 3 test method for you
/**before a method will generate Javadoc, inferring the parameters to your method
- Going to the declaration by clicking
- Package explorer
- Go to your
MovieInventory.javaprogram. Hold down the
Controlkey and hover your mouse over the declaration of
Movieshould turn into a hyperlink.
Controlstill held down, click on the
Moviehyperlink (Mac users try the
Applekey). This will take you to the
- In general, if you
Ctrl + Clickon 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
Controlkey for a half-beat before the hyperlinks show up.
- If you hover too long, the hyperlinks go away.
- 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.
- Use the plus sign (or arrow on Vista machines) to expand each element of our
srcfolder. Here we see all of methods, instance variables, and static variables of our class.
Objectclass. Source code generation is only useful if you have specified data (or state) for your object. Let's create some state for our
Movieshould keep track of its
rating. Additionally, a
Movieobject should be immutable.
- Add the following code to create fields (instance variables) for
- 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
Movieclass 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
Source > Generate Getters and Setters....
All of the fields in the
Movieclass are displayed. We can press the
Select Gettersbutton 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
Finishwhen you are done selecting options. The newly generated code will display in the
Editorview. You'll want to save Movie, which will remove the earlier warning associated with each field.
Check that the getter methods were properly generated and added to the
- Now that we've created state and getter methods for our
Movieclass, we'll need to provide a mechanism for creating a new
Movieobject. One way we could do that is by using the default constructor and providing setter methods, but that does not guarantee that a
Movieobject will be fully created by a user and violates our requirement of immutability. A better way to create a
Movieobject is through the use of a constructor where the user passes in values for each of
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 constructorcomments. Additionally, you may want to change the insertion point so that the constructor is positioned above your getter methods. Select OK.
Check that the constructor was added to your
Objectclass is the parent of all Java objects, and provides many useful methods that we use frequently when developing software:
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.
equals()method compares two object's to determine if they are equivalent. The default implementation of the
equals()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 the
hashcode()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
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.
Check that the methods were generated in your source. Don't forget to save your changes!
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
Configurebutton. Browse to the location where you installed your JDK. The javadoc tool is in the
binfolder. 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
docwithin your project file.
Yes To All. When the Javadoc has been created, you will need to refresh your project listing in the
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.htmlwithin the doc directory will open a Browser window in your editor with your newly generated Javadoc.
Any time you update your Javadoc, you should regenerate the html files.You might be interested in :
- Don't write the code instead Generate it! Check it out : 8 most useful shotcuts in Eclipse IDE