(For more resources related to this topic, see here.)
Creating a Java project
To create a new Java project, navigate to File | New | Project . You will be presented with the New Project wizard window that is shown in the following screenshot:
Choose the Java Project option, and click on Next . The next page of the wizard contains the basic configuration of the project that you will create. The JRE section allows you to use a specific JRE to compile and run your project. The Project layout section allows you to choose if both source and binary files are created in the project's root folder or if they are to be separated into different folders (src and bin by default). The latter is the default option.
You can create your project inside a working set. This is a good idea if you have too many projects in your workspace and want to keep them organized. Check the Creating working sets section of this article for more information on how to use and manage working sets.
The next page of the wizard contains build path options. In the Managing the project build path section of this article , we will talk more about these options. You can leave everything as the default for now, and make the necessary changes after the project is created.
Creating a Java class
To create a new Java class, right-click on the project in the Package Explorer view and navigate to New | Class . You will be presented with the New Java Class window, where you will input information about your class. You can change the class's superclass, and add interfaces that it implements, as well as add stubs for abstract methods inherited from interfaces and abstract superclasses, add constructors from superclasses, and add the main method.
To create your class inside a package, simply enter its name in the appropriate field, or click on the Browse button beside it and select the package. If you input a package name that doesn't exist, Eclipse will create it for you. New packages can also be created by right-clicking on the project in the Package Explorer and navigating to New | Package . Right-clicking on a package instead of a project in the Project Explorer and navigating to New | Class will cause the class to be created inside that package.
Creating working sets
Working sets provide a way to organize your workspace's projects into subsets. When you have too many projects in your workspace, it gets hard to find the project you're looking for in the Package Explorer view. Projects you are not currently working on, for example, can be kept in separate working sets. They won't get in the way of your current work but will be there in case you need them.
To create a new working set, open the Package Explorer's view menu (white triangle in the top-right corner of the view), and choose Select Working Set . Click on New and select the type of projects that the working set will contain (Java , in this case). On the next page, insert the name of the working set, and choose which projects it will contain. Once the working set is created, choose the Selected Working Sets option, and mark your working set. Click on OK , and the Package Explorer will only display the projects inside the working set you've just created.
Once your working sets are created, they are listed in the Package Explorer's view menu. Selecting one of them will make it the only working set visible in the Package Explorer. To view more than one working set at once, choose the Select Working Set option and mark the ones you want to show. To view the whole workspace again, choose Deselect Workspace in the view menu. You can also view all the working sets with their nested projects by selecting working sets as the top-level element of the Package Explorer view. To do this, navigate to Top Level Elements | Working Sets in the view menu.
Although you don't see projects that belong to other working sets when a working set is selected, they are still loaded in your workspace, and therefore utilize resources of your machine. To avoid wasting these resources, you can close unrelated projects by right-clicking on them and selecting Close Project . You can select all the projects in a working set by using the Ctrl + A keyboard shortcut.
If you have a big number of projects, but you never work with all of them at the same time (personal/business projects, different clients' projects, and so on), you can also create a specific workspace for each project set. To create a new workspace, navigate to File | Switch Workspace | Other in the menu, enter the folder name of your new workspace, and click on OK . You can choose to copy the current workspace's layout and working sets in the Copy Settings section.
Importing a Java project
If you are going to work on an existing project, there are a number of different ways you can import it into Eclipse, depending on how you have obtained the project's source code. To open the Import wizard, navigate to File | Import . Let's go through the options under the General category:
- Archive file : Select this option if the project you are working on already exists in your workspace, and you just want to import an archive file containing new resources to it. The Import wizard will list all the resources inside the archive file so that you can select the ones you wish to import. To select to which project the resources will be imported click on the Browse button. You can also select in which folder the resources are to be included. Click on Finish when you are done. The imported resources will be decompressed and copied into the project's folder.
- Existing Projects into Workspace : If you want to import a new project, select this option from the Import wizard. If the project's source file has been compressed into an archive file (the .zip, .tar, .jar, or .tgz format), there's no need to decompress it; just mark the Select archive file option on the following page of the wizard, and point to the archive file. If you have already decompressed the code, mark Select root directory and point to the project. The wizard will list all the Eclipse projects found in the folder or archive file. Select the ones you wish to import and click on Finish . You can add the imported projects to a specific working set and choose whether the projects are to be copied into your workspace folder or not. It's highly recommended to do so for both simplicity and portability; you know where all your Eclipse projects are, and it's easy to backup or move all of them to a different machine.
- File System : Use this wizard if you already have a project in your workspace and want to add new existing resources in your filesystem. On the next page, select the resources you wish to import by checking them. Click on the Browse button to select the project and the folder where the resources will be imported. When you click on the Finish button, the resources will be copied to the project's folder inside your workspace.
- Preferences : You can import Eclipse preferences files to your workspace by selecting this option. Preferences file contains code style and compiler preferences, the list of installed JREs, and the Problems view configurations. You can choose which of these preferences you wish to import from the selected configuration file.
Importing a project from Version Control Servers
Projects that are stored in Version Control Servers can be imported directly into Eclipse. There's a number of version control softwares, each with its pros and cons, and most of them are supported by Eclipse via plugins. GIT is one of the most used softwares for version control. CVS is the only version control system supported by default. To import a project managed by it, navigate to CVS | Projects from CVS in the Import wizard. Fill in the server information on the following page, and click on Finish .
Introducing Java views
Eclipse's user interface consists of elements called views. The following sections will introduce the main views related to Java development.
The Package Explorer view
The Package Explorer view is the default view used to display a project's contents. As the name implies, it uses the package hierarchy of the project to display its classes, regardless of the actual file hierarchy. This view also displays the project's build path.
The following screenshot shows how the Package Explorer view looks:
The Java Editor view
The Java Editor is the Eclipse component that will be used to edit Java source files. It is the main view in the Java perspective and is located in the middle of the screen.
The following screenshot shows the Java Editor view:
The Java Editor is much more than an ordinary text editor. It contains a number of features that makes it easy for newcomers to start writing Java code and increases the productivity of experienced Java programmers. Let's talk about some of these features.
Compiling errors and warnings annotations
As you will see in the Building and running section with more details, Eclipse builds your code automatically after every saved modification by default. This allows Eclipse to get the Java Compiler output and mark errors and warnings through the code, making it easier to spot and correct them. Warnings are underlined in yellow and errors in red.
This is probably the most used Java Editor feature both by novice and experienced Java programmers. It allows you to list all the methods callable by a given instance, along with their documentation. This feature will work by default for all Java classes and for the ones in your workspace. To enable it for external libraries, you will have to configure the build path for your project. We'll talk more about build paths further in this article in the Managing the project build path section.
To see this feature in action, open a Java Editor, and create a new String instance.
String s = new String();
Now add a reference to this String instance, followed by a dot, and press Ctrl + Space bar . You will see a list of all the String() and Object() methods. This is way more practical than searching for the class's API in the Java documentation or memorizing it.
The following screenshot shows the content assist feature in action:
This list can be filtered by typing the beginning of the method's name after the dot. Let's suppose you want to replace some characters in this String instance. As a novice Java programmer, you are not sure if there's a method for that; and if there is, you are not sure which parameters it receives. It's a fair guess that the method's name probably starts with replace, right? So go ahead and type:
When you press Ctrl along with the space bar, you will get a list of all the String() methods whose name starts with replace. By choosing one of them and pressing Enter , the editor completes the code with the rest of the method's name and its parameters. It will even suggest some variables in your code that you might want to use as parameters, as shown in the following screenshot:
Content assist will work with all classes in the project's classpath. You can disable content assist's automatic activation by unmarking Enable auto activation inside the Preferences window and navigating to Java | Editor | Content Assist .
When the project you are working on is big enough, finding a class in the Package Explorer can be a pain. You will frequently find yourself asking, "In which package is that class again?". You can leave the source code of the classes you are working on open in different tabs, but soon enough you will have more open tabs than you would like to have.
Eclipse has an easy solution for this. In the toolbar, select Navigate | Open Type . Now, just type in the class's name, and click on OK . If you don't remember the full name of the class, you can use the wildcard characters, ? (matches one character) and * (matches any number of characters). You can also use only the uppercase letters for the CamelCase names (for example, SIOOBE for StringIndexOutOfBoundsException). The shortcut for the Open Type dialog is Ctrl + Shift + T . There's also an equivalent feature for finding and opening resources other than Java classes, such as HTML files, images, and plain text files. The shortcut for the Open Resource dialog is Ctrl + Shift + R .
You can also navigate to a class' source file by holding Ctrl and clicking on a reference to that class in the code. To navigate to a method's implementation or definition directly, hold Ctrl and click on the method's call.
Another useful feature that makes it easy to browse through your project's source files is the Link With Editor feature in the Package Explorer view, as shown in the following screenshot:
By enabling it, the selected resource in the Package Explorer will always be the one that's open in the editor. Using this feature together with OpenType is certainly the easiest way of finding a resource in the Package Explorer.
Whenever there's an error or warning marker in your code, Eclipse might have some suggestions on how to get rid of it. To open the Quick Fix menu containing the suggestions, place the caret on the marked piece of code related to the error or warning, right-click on it, and choose Quick Fix . You can also use the shortcut by pressing Ctrl + 1 with the caret placed on the marked piece of code.
The following screenshot shows the quick fix feature suggesting you to either get rid of the unused variable, create getters and setters for it, or add a SuppressWarnings annotation:
Let's see some of the most used quick fixes provided by Eclipse. You can take advantage of these quick fixes to speed up your code writing. You can for example, deliberately call a method that throws an exception without the try/catch block, and use the quick fix to generate it instead of writing the try/catch block yourself.
- Unhandled exceptions : When a method that throws an exception is called, and the exception is not caught or thrown, Eclipse will mark the call with an error. You can use the quick fix feature to surround the code with a proper try/catch block automatically. Just open the Quick Fix menu, and choose Surround with Try/Catch . It will generate a catch block that will then call the printStackTrace() method of the thrown exception. If the method is already inside a try block, you can also choose the Add catch clause to the surrounding try option. If the exception shouldn't be handled in the current method, you can also use the Add throws declaration quick fix.
- References to nonexisting methods and variables : Eclipse can create a stub for methods referenced through the code that doesn't exist with quick fix. To illustrate this feature's usefulness, let's suppose you are working on a class's code, and you realize that you will need a method that performs some specific operation with two integers, returning another integer value. You can simply use the method, pretending that it exists:
int b = 4;
int c = 5;
int a = performOperation(b,c);
The method call will be marked with an error that says performOperation is undefined. To create a stub for this method, place the caret over the method's name, open the Quick Fix menu, and choose create method performOperation(int, int) . A private method will be created with the correct parameters and return type as well as a TODO marker inside it, reminding you that you have to implement the method. You can also use a quick fix to create methods in other classes. Using the same previous example, you can create the performOperation() method in a different class, such as the following:
OperationPerformer op = new OperationPerformer(); int a = op.performOperation(b,c);
Speaking of classes, quick fix can also create one if you add a call to a non-existing class constructor.
Non-existing variables can also be created with quick fix. Like with the method creation, just refer to a variable that still doesn't exist, place the caret over it, and open the Quick Fix menu. You can create the variable either as a local variable, a field, or a parameter.
- Remove dead code : Unused methods, constructors and fields with private visibility are all marked with warnings. While the quick fix provided for unused methods and constructors is the most evident one (remove the dead code), it's also possible to generate getters and setters for unused private fields with a quick fix.
Customizing the editor
Like almost everything in Eclipse, you can customize the Java Editor's appearance and behavior. There are plenty of configurations in the Preferences window (Window | Preferences ) that will certainly allow you to tailor the editor to suit your needs. Appearance-related configurations are mostly found in General | Appearance | Colors and Fonts and behavior and feature configurations are mostly under General | Editors | Text Editors . Since there are lots of different categories and configurations, the filter text in the Preferences window might help you find what you want. A short list of the preferences you will most likely want to change is as follows:
- Colors and fonts : Navigate to General | Appearance . In the Colors and Fonts configuration screen, you can see that options are organized by categories. The ones inside the Basic and Java categories will affect the Java Editor.
- Enable/Disable spell checking : The Eclipse editor comes with a spellchecker. While in some cases it can be useful, in many others you won't find much use for it. To disable or configure it, navigate to General | Editors | Text Editors | Spelling .
- Annotations : You can edit the way annotations (warnings and errors, among others) are shown in the editor by navigating to General | Editors | Text Editors | Annotations inside the Preferences window. You can change colors, the way annotations are highlighted in the code (underline, squiggly line, box, among others), and whether they are shown in the vertical bar before the code.
- Show Line Numbers : To show line numbers on the left-hand side of the editor, mark the corresponding checkbox by navigating to General | Editors | Text Editors . Right-clicking on the bar on the editor's left-hand side brings a dialog in which you can also enable/disable line numbers.
The Problems view
As we have seen in the Java Editor description, Eclipse uses the output of the automatic compilation of the class to mark the compiler's error and warning messages throughout the code. These messages are also listed in the Problems view. The following screenshot shows how the view looks:
By default, it shows all the errors and warnings in all the open projects inside the current workspace. As you can see, every entry contains the compiler error/warning message and where the problem is located. By double-clicking on the entry, a new tab of the Java Editor, for the resource that contains the problem, will be opened (unless the tab already exists), and the caret will be placed on the problem's line.
Customizing the Problems view
The Problems view allows plenty of customization to make it easier to browse its entries. You can, for example, group them by severity and type by entering the View menu (white triangle in the top-right side of the view) and selecting the Group By entry.
When you have too many different projects open in your workspace, showing all the errors and warnings from all the projects might not be a good idea. Fortunately, you can customize what the Problems view will show. For this, open the Configure Contents window in the view menu.
There's a list of problem configurations on the left-hand side of the window. You can choose to show items that match either all or any of the configurations. New configurations can be added by clicking on the New button. The four default configurations cannot be removed or renamed, but they can be edited just as the ones you created.
You can modify the scope in which your configuration will search for problems and the type of problem that your configuration contains (some of these types may not refer to Java code). You can also filter problems that either contain or do not contain some text.
Another feature of the Problems view that helps organize the problems' listing is creating other views. To create another view, open the view menu and choose the New Problems view. Each view will have its own configuration, so you can create multiple views and have each one displaying one type of problem.
The Outline view
The Outline view provides an overview of the selected class. By default, it shows a list of the class's fields and methods. You can configure the view to hide static elements, fields, nonpublic members, and local types.
The following screenshot shows the outline of a Book class:
The Type Hierarchy view
The Type Hierarchy view is where you visualize a class's superclasses and extensions. To load a class's type hierarchy in this view, select the reference to the class name in the Java Editor, right-click on it, and select Open Type Hierarchy ; alternatively, you can use the F4 keyboard shortcut. This tool can be useful when you have an interface and want to list all of its implementations.
The following screenshot contains the Type Hierarchy view showing the supertype hierarchy of the java.awt.Button class:
There's an alternative to the Type Hierarchy view named Quick Type Hierarchy . Instead of loading and displaying the Type Hierarchy view, it shows the class's hierarchy in a pop-up window. The keyboard shortcut for Quick Type Hierarchy is Ctrl + T .
The Call Hierarchy view
To see all the calls made to a specific method in the project, select a reference to the method's name in the Java Editor, right-click on it, and select Open Call Hierarchy ; alternatively, use the Ctrl + Alt + H keyboard shortcut. The view provides a full, recursive hierarchy of the selected method's calls, as shown in the following screenshot:
Eclipse makes it easy to manage a class's imports. By right-clicking on the Java Editor and navigating to Source | Organize Imports , all unused imports and import classes are removed if there are references to them in the code. You can also use the Ctrl + Shift + O shortcut to organize the imports.
To illustrate how this functionality is useful, let's suppose you want to add an ArrayList instance in your code. Instead of importing ArrayList and using it (and you may or may not know the package name of ArrayList from the top of your head), you can simply write:
Alternatively, you can also press Ctrl + Shift + O to add the import.
If the class's name occurs in more than one package in the current classpath, you will be prompted to choose the one to which you're referring.
You can define actions that are to be performed every time a Java source file is saved. For this, navigate to Window | Preferences in the toolbar; then, in the left menu, navigate to Java | Editor , and select Save Actions . Check the Perform the selected actions on save checkbox, and choose the actions you want to perform. It's possible to organize imports automatically to remove unused ones, add missing annotations, format the source code, and reinforce code style.
You can also define specific save actions for each project by right-clicking on the project's entry in the Package Explorer and clicking on Properties . Then, on the new window, navigate to Java Editor | Save Actions , and check Enable project specif ic settings .
Enforcing Coding Style with Formatter
Some companies and open source projects are very strict with their coding style. They have clear guidelines on when to skip lines or not, where to put whitespaces, how the indentation should look, and so on. All these guidelines can be implemented in Eclipse's Formatter tool that helps the developers to style the code without any worry. The formatter will modify your code to comply with a set of coding style rules. To run the formatter, navigate to Source | Format in the toolbar or use the Ctrl + Shift + F shortcut. You can also force Eclipse to run the formatter after file saves using Save Actions .
To edit your workspace's formatting settings, go to the preferences window (Window | Preferences ), and navigate to Java | Code Style | Formatter in the left menu. The formatter's settings are saved under profiles that can be saved, imported, and exported. The Edit button brings up a huge number of settings that will suit most of your code-styling needs.
You can also define project-specific format rules. In the project properties window (right-click on the project in the Package Explorer and select Properties ), navigate to Java Code Style | Formatter in the left menu, and check Enable project sp ecific settings .
In Java, you will eventually find yourself writing similar pieces of code over and over. Even though the good usage of design principles tends to minimize this, there are some methods, such as getters, setters, and constructors, in most cases look exactly the same. Eclipse can help you by generating code for these simple methods.
You can see all the code that Eclipse can generate by right-clicking anywhere in the Java Editor and choosing the Source entry. This menu can also be opened with the shortcut Alt + Shift + S .
Generating getters and setters
Getters and setters are generally the same. They provide access to some private field of the class by either returning its value or by assigning a new one. To avoid this no-brainer task and save some time to write real code, choose Generate Getters and Setters from the Source entry. You will be presented with a window, as shown in the following screenshot:
In the Generate Getters and Setters window, you will be able to determine for which fields you want to generate getters and setters, as well as choosing their access modifiers and where in the code they will be inserted.
Just like getters and setters, class constructors have a very typical template that receives values to be assigned to the class's fields and calls the superclass's constructor. You can also skip this tedious task by clicking on Generate Constructor using Fields in the Source menu entry. You will be presented with a window similar to the Generate Getters and Setters one in which you will be prompted to choose which fields will have their values initialized by the constructor, and where the constructor will be inserted in the code, among others.
Generating the hashCode() and equals() methods
There are cases in which you have to override the equals() and hashCode() methods inherited from the Object class in order to treat two different instances as being equal when they have the same parameter values.
Eclipse also has a template for these two methods. By choosing Generate hashCode() and equals() inside the Source menu entry, you will be able to generate methods that utilize the fields of your choice to compare two instances and to generate the hash code of the instance. The template for the equals() method will check if the other object is null, if it is an instance of the same class, and if the selected parameters are equal.
Generating the toString() method
To generate a toString() method that returns the value of the class's fields in a human-readable form, choose the Generate toString() option. Like the previous generators, this one will allow you to choose which fields you want your to String() method to contain.
Generating method comments
Comments for methods in the Javadoc format can easily be generated in Eclipse. For this, right-click on the desired method, and navigate to Source | Generate Element Comment, or use the shortcut Alt + Shift + J with the caret positioned in the method's signature line. These comments will be shown in Eclipse when the user hovers the mouse over the method's call or when the content assist feature is used.
The generated comment contains the method's parameters and return type. You only have to add a simple description of the method's usage and some words about the parameters when required. An example of a generated comment is presented in the following screenshot:
These shortcuts might look useless and hard to memorize, but once you get used to them, they become incredibly handy and increase your coding speed considerably since you'll rarely have to take your hands off your keyboard when you know the ones you use most by heart.
Editing code and comment templates
Although these templates will work on most of the situations, your project might have peculiarities that require a specific type of constructor. You can still take advantage of code and comment generation by editing the templates and tailoring them to fit your needs. For this, right-click on the project's entry in the Package Explorer and choose Properties . Expand the Java Code Style entry in the left menu and choose Code Templates . The following window will open:
By choosing a type of generated code or comment and clicking on Edit , you will be able to add code and variables to the template. You can also choose to add comments on newly generated methods and types automatically.
The code template settings edited in this window are project specific. The settings are saved in a metadata file inside the project folder, so when a project is imported, the coding style settings are automatically set. This allows you to enforce the project's coding style among all the project's developers. If you want to edit the default code templates for the whole workspace, open the Preferences window and navigate to Java | Code Style | Code Templates . Projects that don't contain any specific setting for templates will use these settings.
In this article, we have covered the basics of Java developing with Eclipse: creating and importing a Java project, organizing projects in working sets, adding new classes, among others. We went through all of Eclipse's views for Java developing, learned how they can be used to navigate through code, found errors, warnings, and much more. Special attention was given to the Java Editor by covering its most useful features. We also covered some more advanced topics, such as creating templates for code generation and project settings, that can be shared among developers in a team to enforce code style and best practices.
Resources for Article :
- Deployment of Reports with BIRT [Article]
- Installing Alfresco Software Development Kit (SDK) [Article]
- Vaadin Portlets in Liferay User Interface Development [Article]