Tutorial Eclipse for Java & Android Programming

Saturday, January 7, 20122comments

Eclipse is created by an Open Source community and is used in several different areas, e.g. as a development environment for Java or Android.

The Eclipse project is governed by the Eclipse Foundation. The Eclipse Foundation is a non-profit, member supported corporation that hosts the Eclipse projects and helps to cultivate both an open source community and an ecosystem of complementary products and services.

Eclipse roots go back to 2001. Today it is the leading development environment for Java with approx. 65% marketshare.

Eclipse can be extended with additional functionalities. Several Open Source projects and companies have extended Eclipse with additional components. It is also possible to use Eclipse as a basis for creating general purpose applications (Eclipse RCP).

This description focuses on using Eclipse as a Java development environment.

2. Getting started

2.1. Java

Eclipse requires an installed Java Runtime. I recommend to use Java 7 (also known as Java 1.7) or Java 6.

Java comes in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK). The JRE contains only the necessary functionality to start Java programs, while the JDK contains in addition the development tools.

Eclipse contains its own development tools, e.g. Java compiler. Therefore for this tutorial it is sufficient to use the JRE.

The JDK is required if you compile Java source code outside Eclipse and for advanced development scenarios. For example if you use automatic builds or if you develop web development. These scenarios are not covered in this tutorial.

Java might already be installed on your machine. You can test this by opening a console (if you are using Windows: Win+R, enter "cmd" and press Enter) and by typing in the following command:

java -version

If Java is correctly installed you should see some information about your Java installation. If the command line return the information that the program could not be found, you have to install Java. A Google search for "How to install Java on ..." should result in helpful links. Replace "..." with your operating system, e.g. Windows, Ubuntu, Mac OS X, etc.

2.2. Install Eclipse

To install Eclipse download the package "Eclipse IDE for Java Developers" from the website http://www.eclipse.org/downloads and unpack it to a local directory.

The download is a "zip" file. Most operating system can extract zip files in their file browser, e.g. Windows7 via right mouse click on the file and selecting "Extract all...". If in doubt, search via Google for "How to unzip a file on ...", again replacing "..." with your operating system.

Use a directory path which does not contain spaces in its name, as Eclipse sometimes has problems with that.

After unpacking the download, Eclipse is ready to be used; no additional installation procedure is required.

2.3. Start Eclipse

To start Eclipse double-click on the file eclipse.exe (Microsoft Windows) or eclipse (Linux / Mac) in the directory where you unpacked Eclipse. The system will prompt you for a workspace. The workspace is the place where you store your Java projects (more on workspaces later). Select an empty directory and press Ok.

Selecting the Workspace

Eclipse will start and show the Welcome page. Close the welcome page by pressing the "X" beside "Welcome".

Closing the Eclipse welcome screen

3. Eclipse UI Overview

Eclipse provides Perspectives, Views and Editors. Views and Editors are grouped into Perspectives. All projects are located in a workspace.

3.1. Workspace

The workspace is the physical location (file path) you are working in. You can choose the workspace during startup of Eclipse or via the menu ( FileSwitch WorkspaceOthers. All your projects, source files, images and other artifacts will be stored and saved in your workspace.

You can predefine the workspace via the startup parameter -data path_to_workspace, e.g. c:\eclipse.exe -data "c:\temp".

Please note that you have to put the path name into double quotes.

To see the current workspace directory in the title of Eclipse use -showLocation as an additional parameter.

3.2. Perspective

A Perspective is a visual container for a set of Views and Editors.

You can change the layout and content within a Perspective, for example by opening or closing Views or Editors, changing their size and position and more. Eclipse allows you to switch to another perspective via the menu WindowOpen PerspectiveOther.

For Java development you usually use the Java Perspective, but Eclipse has much more predefined Perspectives, e.g. Debug, Git Repositories, CVS Repositories.

A common problem is that you mis-configured your Perspective, e.g. by closing a View. You can reset a Perspective to its original state via the menu WindowReset Perspective.

3.3. Views and Editors

A View is typically used to navigate a hierarchy of information or to open an Editor. Changes in a View are directly applied to the underlying data structure.

Editors are used to modify elements and are typically text editors. An Editor can have code completion, undo / redo, etc. To apply the changes in an editor to the underlying resource, e.g. Java source file, you have to save.

3.4. Java Perspective and Package Explorer

The default Perspective for Java development can be opened via WindowOpen PerspectiveJava.

On the left hand side, this perspective shows the "Package Explorer" View which allows to browse your Java projects and to select the components you want to work on via double-click.

For example to open a Java source file, open the tree under src, select the corresponding .java file and double-click it. This will open the file in an Editor.

The following picture shows the Eclipse IDE in its standard Java perspective. The "Package Explorer" is on the left. In the middle you have the open Editor for a Java source file. If several Editors would be open, they would be stacked in the same place and you could switch between them by clicking on the next Editor. All editors share the same part of the Eclipse IDE; this part is called the "editor area".

To the right and below the editor area you find more Views which were considered useful by the developer of the perspective. For example the "Console" view shows the output of System.out statements in your code.

3.5. Linking the package explorer with the code editor

The Package Explorer allows displaying the associated file from the currently selected editor. For example if you working on Foo.java and you change in the editor to Var.java then the corresponding file will be selected in the the "Package explorer" View.

To activate this behavior, press the button "Link with Editor" in the "Package explorer" View.

Synchronize the project explorer with the current selected editor

3.6. Problems view

Sooner or later you will run into problems with your code or your project setup. To view the problems in your project you can use the "Problems" View which is part of the standard Java Perspective. If it is closed you can open it via WindowsShow ViewProblems.

Opening the problems view

You can configure the content of the "Problems" View. For example, to display the problems from the currently selected project, select "Configure Contents" and set the Scope to "On any element in the same project".

Configuring the problems view

Configuring the problems view

4. Create your first Java program

The following describes how to create a minimal Java program using Eclipse. It is tradition in the programming world to create a small program which writes "Hello World" to the console. We will adapt this tradition and will write "Hello Eclipse!" to the console.

4.1. Create project

Select from the menu FileNewJava project. Enter de.vogella.eclipse.ide.first as the project name. Select the flag "Create separate folders for sources and class files".

New Java Project Wizard

Press finish to create the project. A new project is created and displayed as a folder. Open the de.vogella.eclipse.ide.first folder and explore the content of this folder.

4.2. Create package

Create a new package. A good convention is to use the same name for the top package and the project. Create therefore the package de.vogella.eclipse.ide.first.

Select the folder src, right click on it and select NewPackage.

Right mouse click to create a package

Create a package Dialog

4.3. Create Java class

We will now create a Java class. Right click on your package and select NewClass.

Create a new class selection

Enter MyFirstClass as the class name and select the flag "public static void main (String[] args)".

Create a new class selection

This creates a new file and opens an Editor to edit the source code of this file. Write the following code.

package de.vogella.eclipse.ide.first;

public class MyFirstClass {

public static void main(String[] args) {
System.out.println("Hello Eclipse!");


4.4. Run your project in Eclipse

Now run your code. Right click on your Java class and select Run-asJava application.

Run project

Finished! You should see the output in the console.

Result of the running application

4.5. Prepare to run program outside Eclipse (create jar file)

To run your Java program outside of Eclipse you need to export it as a jar file. A jar file is the standard distribution format for Java applications.

Select your project, right click on it and select Export.

Export wizard for Java project

Select JAR file, select next. Select your project and maintain the export destination and a name for the jar file. I named it myprogram.jar.

Export wizard for Java project, Part II

Export wizard for Java project, Part III

Press finish. This creates a jar file in your selected output directory.

4.6. Run your program outside Eclipse

Open a command shell, e.g. under Microsoft Windows select StartRun and type cmd and press enter. This should open a console.

Switch to your output directory, by typing cd path. For example if your jar is located in c:\temp type cd c:\temp.

To run this program you need to include the jar file in your classpath. The classpath defines what Java classes are available to the Java runtime. You can add a jar file to the classpath with the -jar option.

java -classpath myprogram.jar de.vogella.eclipse.ide.first.MyFirstClass

If you type the command from above and are in the correct directory you should see the "Hello Eclipse!" output on the console.

Running application outside Eclipse

Congratulations! You created your first Java project, a package, a Java class and you ran this program inside and outside Eclipse.

5. Content Assist, Quick Fix and Class Navigation

5.1. Content assist

The content assistant allows you to get input help in an editor. It can be invoked by pressing CTRL+Space

For example type syso in the editor of a Java source file and then press CTRL+Space. This will replace syso with System.out.println("").

If you have a reference to an object, for example the object person of the type Person and need to see it's methods, type person. and press CTRL+Space.

Content Assists

5.2. Quick Fix

Whenever Eclipse detects a problem, it will underline the problematic text in the editor. Select the underlined text and press CTRL+1 to see proposals how to solve this problem.

For example type myBoolean = true; If myBoolean is not yet defined, Eclipse will highlight it as an error. Select the variable and press CTRL+1, Eclipse will suggest creating a field or local variable.

Using Quickfix Example

Quick Fix is extremely powerful. It allows you to create new local variables and fields as well as new methods and new classes. I can put try-catch statements around your exceptions. It can assign a statement to a variable and much more.

6. Opening a class

You can navigate between the classes in your project via the "Package Explorer" View.

In addition you can open any class via positioning the cursor on the class in an editor and pressing F3. Alternatively, you can press CTRL+Shift+T. This will show a dialog in which you can enter the class name to open it.

Opening a class

7. Generating code

Eclipse has several possibilities to generate code for you. This can save significant time during development.

For example Eclipse can override methods from superclasses and generate the toString(), hashcode() and equals() methods. It can also generate getter and setter methods for attributes of your Java class.

You can find these options in the Source menu.

Code generation

To test the source generation, create the following class in your de.vogella.eclipse.ide.first project.

package de.vogella.eclipse.ide.first;

public class Person {
private String firstName;
private String lastName;


Select SourceGenerate Constructor from Fields, mark both fields and press "Ok".


Select SourceGenerate Getter and Setter, select again both your fields and press the "Ok" button.

Select SourceGenerate toString(), mark again both fields and press "Ok".

You created the following class:

package de.vogella.eclipse.ide.first;

public class Person {
private String firstName;
private String lastName;

public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;

public String getFirstName() {
return firstName;

public void setFirstName(String firstName) {
this.firstName = firstName;

public String getLastName() {
return lastName;

public void setLastName(String lastName) {
this.lastName = lastName;

public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName
+ "]";


8. Refactoring

Refactoring is the process of restructuring the code without changing his behavior. For example renaming a Java class or method is a refactoring activity.

Eclipse supports simple refactoring activities, for example renaming or moving. For example you can select your class, right click on it and select RefactorRename to rename your class or method. Eclipse will make sure that all calls in your Workspace to your your class or method will also be renamed.

The following shows a screenshot for calling the "Rename" refactoring on a class.

Renaming a class

For the next examples change the code of "MyFirstClass.java" to the following.

package de.vogella.eclipse.ide.first;

public class MyFirstClass {

public static void main(String[] args) {
System.out.println("Hello Eclipse!");
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;

Another useful refactoring is to mark code and create a method from the selected code. For this mark the coding of the "for" loop, right click and select Refactoring Extract Method. Use "calculateSum" as name of the new method.

Extract Method refactoring

The resulting class should look like the following.

package de.vogella.eclipse.ide.first;

public class MyFirstClass {

public static void main(String[] args) {
System.out.println("Hello Eclipse!");
int sum = 0;
sum = calculateSum(sum);

private static int calculateSum(int sum) {
for (int i = 0; i <= 100; i++) {
sum += i;
return sum;

You can also extract strings and create constants from them. Mark for this example "Hello Eclipse!", right click on it and select RefactorExtract Constant. Name your new constant "HELLO".

Extract Constants

The resulting class should look like the following.

package de.vogella.eclipse.ide.first;

public class MyFirstClass {

private static final String HELLO = "Hello Eclipse!";

public static void main(String[] args) {
int sum = 0;
sum = calculateSum(sum);

private static int calculateSum(int sum) {
for (int i = 0; i <= 100; i++) {
sum += i;
return sum;

Eclipse has much more refactorings, in most cases you should get an idea of the performed action by the naming of the refactoring operation.

9. Eclipse Shortcuts

Eclipse provides a lot of shortcuts to work efficiently with the IDE. For a list of the most important Eclipse shortcuts please see Eclipse Shortcuts

10. Using jars (libraries)

10.1. Adding a library (.jar ) to your project

The following describes how to add Java libraries to your project. Java libraries are distributed via "jar" files. It assumes that you have a jar file available; if not feel free to skip this step.

Create a new Java project de.vogella.eclipse.ide.jars. Then, create a new folder called lib, by right clicking on your project and selecting NewFolder.

Creating a new folder

From the menu select FileImportGeneralFile System. Select your jar and select the folder lib as target. Alternatively, just copy and paste your jar file into the "lib" folder.

Right click on your project and select Properties. Under Java Build PathLibraries select the button "Add JARs".

The following example shows how the result would look like, if the junit-4.4.jar had been added to the project.

Adding a jar to the current project

Afterwards you can use the classes contained in the jar file in your Java source code.

10.2. Show source code for jar

As said earlier you can open any class via positioning the cursor on the class in an editor and pressing F3. Alternatively, you can press CTRL+Shift+T. This will show a dialog in which you can enter the class name to open it.

If the source code is not available when you attempt to open a class, the editor will show the decompiled byte-code of that class.

This happens if you open a class from a jar file and the source for this jar is not available.

To browse the source of a type contained in a library (i.e. .jar file), you can attach a source archive or source folder to that library. Afterwards the editor will show the source instead of the byte-code.

In addition setting the source attachment allows debugging this source code.

The Source Attachment dialog can be reached in the Java Build Path page of a project. To open this page, right click on a projectPropertiesJava Build Path. On the "Libraries" tab, expand the library's node, select the "Source attachment" attribute and press Edit.

In the Location path field, enter the path of an archive or a folder containing the source.

The following shows this for the standard Java library. If you have the Java Development Kit (JDK) installed, you should find the source in the JDK installation folder. The file is typically called "src.zip".

Maintaining the location of the source attachment to an jar

10.3. Add the Javadoc for a jar

It is also possible to add Javadoc to a library which you use.

Download the Javadoc of the jar and put it somewhere in your filesystem.

Open the Java Build Path page of a project via Right click on a projectPropertiesJava Build Path. On the "Libraries" tab expand the library's node, select the "Javadoc location" attribute and press Edit.

Enter the location to the file which contains the Javadoc.

Maintain the location to the Javadoc file for a jar file

11. Updates and Installation of Plugins

11.1. Eclipse Update Manager

Eclipse contains an Update Manager which allows you to install and update software components. Installable software components are called features and consists of plug-ins.

To update your Eclipse installation, select HelpCheck for Updates. The system will search for updates for the already installed software components. If it finds updated components, it will ask you to approve the update.

To install a new functionality, select HelpInstall New Software

Selecting an update site in the update manager

From the "Work with" list, select an URL from which you would like to install.

To add a new update site, press "Add" and enter the new URL as well as a name for the new update site.

Sometimes you have to uncheck "Group items by category" – not all available plug-ins are categorized. If they are not categorized, they will not be displayed unless the grouping is disabled.

11.2. Manual installation of plug-ins (dropins folder)

If you’re using a plug-in for which no Update Site is available, you can use the "dropins" folder in your Eclipse installation directory.

Plug-ins are typically distributed as .jar files. To add a plug-in to your Eclipse installation, put the plug-in .jar file into the Eclipse "dropins" folder and restart Eclipse. Eclipse should detect the new plug-in and install it for you.

11.3. Eclipse Marketplace

Eclipse also contains a client which allows installing software components from the Eclipse Marketplace. The advantage of this client is that you can search for components, discover popular extensions and see descriptions and ratings.

Compared to the update manager you don't have to know the URL for the update site.

To open the Eclipse Marketplace select HelpEclipse Marketplace.

Showing the Eclipse Marketplace Client

You can use the "Find" box to search for components. Pressing "Install" will start the installation process.

11.4. Restart required?

After an update or an installation of a new software component Eclipse to restart Eclipse. In general, it is a good idea to restart Eclipse in this situation, otherwise some components might not work corrrectly.

12. Tips and Tricks

12.1. Important Preference Settings

Eclipse can make typing more efficient, if you enable a few preference settings.

Select WindowPreferences to open the preferences settings dialog. You can use the filter box to search for specific settings.

Select JavaEditorTyping. In the section "Automatically insert at correct position”, check the "Semicolons" setting.

You can now type a semicolon in the middle of your code and Eclipse will position it at the end of the current statement.

Type Assists which allow setting the semicolon to the right position

Eclipse can automatically format source code and organize import statement automatically before the source code is saved. You can find this setting under JavaEditorSave Actions.

Save Actions

12.2. Templates

If you have to frequently type the same code / part of the document, you can create templates which can be activated via autocomplete (Ctrl + Space).

For example, lets assume you are frequently creating public void name(){} methods. You could define a template which creates the method body for you.

To create a template for this, select the menu WindowPreferencesJavaEditor Templates.

Maintaining code templates

Press New. Create the template show in the following screenshot.

Creating a new code template

${cursor} indicates that the cursor should be placed at this position after applying the template.

In this example the name "npm" is your keyword.

Now every time you type "npm" in the Java editor and press Ctrl+Space the system will allow you to replace your keyword with your template.

Using code templates

12.3. Code Templates

Eclipse generates lots of source code automatically. For example, in several cases comments are added to the source code.

Select WindowPreferencesJavaCode Style Code Templates to change the code generation templates.

In the code tree you have the templates. Select for example Code Method Body and press "Edit" to edit this template and to remove the "todo" comment.

Removing the todos from the Java code templates

12.4. Export / Import Preferences

You can export your preference settings from one workspace via FileExportGeneralPreferences.

Similarly you can import them again into another workspace.

12.5. Task Management

You can use // TODO comments in your code to add task reminders.

This indicates a task for Eclipse. You find those in the Task View of Eclipse. Via double-clicking on the task you can navigate to the corresponding code.

You can open this View via WindowShow ViewTasks.

For example, add a TODO to your MyFirstClass class to see it in the Tasks View.

package de.vogella.eclipse.ide.first;

public class MyFirstClass {

private static final String HELLO = "Hello Eclipse!";

public static void main(String[] args) {
// TODO Provide user interface
int sum = 0;
sum = calculateSum(sum);

private static int calculateSum(int sum) {
for (int i = 0; i <= 100; i++) {
sum += i;
return sum;

Close the editor for the MyFirstClass class. If you now double-click on the tasks, the Java editor opens again and the TODO comment is selected.

12.6. Working Sets

You will create more and more projects in your development career. Therefore the data in your workspace grows and it is hard to find the right information.

You can use working sets to organize your displayed projects / data. To set up your working set select the Package Exploreropen the drop-down menuSelect Working Set...

Showing the working set

Press "New" on the following dialog to create a working set.

Creating new working sets

On the next dialog select "Resource", press Next and select the projects you would like to see and give it a name.

Creating new working sets

Creating new working sets

You can now easily display only the files you want to see.

Filtering resources for the working set

This Article is a little part of this book :

Eclipse IDE 3.7 [Kindle Edition]

Eclipse IDE 3.7
Get it now. Click Here!

Share this article :
Powered by Blogger.
Copyright © 2011. Android Tutorials - All Rights Reserved
Proudly powered by Blogger