Sie sind auf Seite 1von 14

Kuntal Dave

Bhavnidhi Kalra
Table of Contents

1. Goals ________________________________________________________ 3
2. Background____________________________________________________ 3
3. Why use Eclipse for Java Development______________________________ 3
4. The tutorial ____________________________________________________ 4
4.1 Getting Started___________________________________________ 4
4.2 Writing Java Code________________________________________ 6
4.3 Content Assist ___________________________________________ 6
4.4 Code Generation__________________________________________ 9
4.5 Java Errors______________________________________________ 10
4.6 Refactoring______________________________________________ 11
4.7 Running Code ___________________________________________ 13
5. Exercises______________________________________________________ 14
6. Further reading and References ____________________________________ 14
Best Practices: JAVA in Eclipse
Goals
This tutorial aims on introducing Eclipse to a Java Developer. Eclipse is a universal
platform for integrating development tools.
The skills learnt at the end of the tutorial would enable the student, the use of Eclipse for
Java development.

The results of this tutorial are:


¾ Creating a Java Project
¾ Learn the features of Java Development Tools – this includes code formatting,
content assist etc.
¾ Code Generation and Java Error fixing
¾ Refactoring techniques
¾ Running Java classes

The prerequisites for this tutorial are the basic knowledge of Java and the tutorial
“Introduction to Eclipse” which will give the user an overview of the IDE.

Background
The advent of Java used only the command prompt to compile and run the Java
programs. The advancement of Java introduced many IDE’s but most of the Java
Developer’s have not yet adopted any IDE completely.
Thus the process of successfully running a Java program needed the program to be
written in an editor and then compiled in the command prompt. The errors would be
displayed and the debugging has to be done using the editor. This involves a very
complex procedure for running even a simple Java program. Thus, we need to use an IDE
which is simple to understand and easy to use. The IDE would help the developers to be
more focused while coding and debugging.

Eclipse is an open source tool integration platform which helps in the writing, compiling,
debugging and running of programs. The ease of use of this IDE helps the developers in
developing their projects in a very systematic format. Since Eclipse is a superlative Java
development environment, using Eclipse for Java is extremely useful.

Why use Eclipse for Java Development?


Eclipse provides an open platform for application development tools. It runs on a wide
range of operating systems and provides tools for GUI and non GUI. The Java
Development Environment provides advanced tools to generate edit and navigate the
code; it also provides syntax highlighting, code implementation, code assist, re-factoring,
spell check, full-feature debugger.

University of Sheffield – Genesys Solutions 3


Java in Eclipse Tutorial
These features and many more attribute to us favouring Eclipse to be used as an IDE for
project development in Genesys.

The tutorial
This tutorial follows the pattern of a brief description of the topic, with exercises
following to ensure the understanding of the topic.

Java Development Tools (JDT) provided by Eclipse include a Java perspective, a Java
debug perspective, a Java project definition, editors, views, wizards, refactoring tools,
Java builder (compiler), a scrapbook for evaluating Java expressions, search tools and
many others that make writing Java code quick, fun and productive.

Getting Started
The Java perspective is the default perspective that Eclipse offers. It contains the Package
Explorer view, Hierarchy view and the Navigator view. The Package Explorer view helps
navigate through the different Java files and projects. The middle pane consists of the
editors, where the actual Java code is written. The following diagram gives an overview
of the Eclipse Platform:

Figure 1: Java Perspective Overview

University of Sheffield – Genesys Solutions 4


Java in Eclipse Tutorial
Amongst the most commonly used icons to write and run a Java program are:

Java Perspective:

Icons involved for creation of the respective resource:

Running the compiled code:

Let’s write our first Java project in Eclipse

The fundamentals involved in doing this consists of the following topics that have been
covered in detail in the book: Chapter 3 – Using Java Development Tools

¾ Creating a Java project


Page 71: The Fundamentals - Creating a Java project
¾ Creating a package
Page 72: The Fundamentals - Creating a package
¾ More details about searching java elements and workspace
Page 73-75: The Fundamentals

University of Sheffield – Genesys Solutions 5


Java in Eclipse Tutorial
Writing Java Code
The code is written in the space provided in the centre of the program called the editor.
There are various features provided by Eclipse which help in the writing of the code more
productively. They are discussed as follows:

Content Assist

While editing Java code, you can press Ctrl+Space to see phrases that complete what
you were typing. This is done based on an ongoing analysis of your Java code as you edit
it.

For example, to quickly enter a reference to class ArrayIndexOutOfBoundsException,


type arr, press Ctrl+Space, then continue typing the remaining letters to narrow the list to
that class and press Enter. The complete reference is inserted. Automatic invocation
works based on a character activation trigger and a delay. The default activation trigger
for Java is the period (.), and for Javadoc it's the "at" sign (@). If you type the activation
trigger character as you are entering Java source or Javadoc and then pause, content assist
will display suggestions

The content assist pop-up lists matching templates and Java references on the left
along with their respective icons (class, interface, and method); on the right is the
proposed code. These suggestions come from two places: Java references based on
an analysis of your code and your defined code templates.

In some cases, you can save typing if you have an idea what you want next or what the
suggestion should be. Keep typing with the content assist prompt displayed and you will
see the list narrowed to match your typing. At any point, select an entry and press Enter.

You can use content assist in a variety of situations. The following figure shows
generation of a stub for a ‘for’ loop from a template. You can also generate public
method templates, while loops, and try/catch expressions

University of Sheffield – Genesys Solutions 6


Java in Eclipse Tutorial
Figure 2: Example for content assist (for loop)

The other functions content assist provides are:

• Overriding Inherited Methods: Position the insertion cursor within a class definition,
but outside any method, and activate content assist. You'll see a list of methods this
class can override or must define based on an interface implementation. The
following figure represents the example:

Figure 3: Content Assist Override Method

• Import Statements: When a Java reference is typed and after content assist is
activated, a list of applicable types can be seen as shown in the figure. Select one and

University of Sheffield – Genesys Solutions 7


Java in Eclipse Tutorial
it completes the reference and includes the required import statement. Also when
import is typed, after typing the beginning of the name of a package or type, and then
activating content assist, a list of types and packages can be viewed.

Figure 4: Content Assist Import Statement

• Variable References: Begin to type the name of a variable or field in an expression


and then activate content assist. It provides a list of possible references, including
variables within the scope of the expression

Figure 5: Content Assist Variable Reference

University of Sheffield – Genesys Solutions 8


Java in Eclipse Tutorial
• Parameter Hints: Content assist provides another way to see information about
parameter types for a method invocation, in addition to Ctrl+Shift+Space. Position
the insertion cursor in the parameters of a method invocation and activate content
assist. It displays the parameter types. As the parameters are entered or the cursor is
moved over them, it highlights the type of the parameter

Figure 6: Content Assist Parameter Hints

Code Generation

In addition to content assist, JDT provides other code generation capabilities. These are
options available under the Source menu item or from the editor's context menu.
• Code Comments: Comments in a Java can be added and removed. Adding
comments generates line comments, which are prefaced by two backslashes (//) on
the lines with the selected expression.

• Import Statements: An unresolved reference can be selected and on using


Source > Add Import to add an import statement for that reference only. The
keyboard equivalents are Ctrl+Shift+O and Ctrl+Shift+M, respectively.

• Method Stubs: A stub for an existing method can be created by dragging it from
one class to another. A list of methods to override can be seen. Select one or more
to have stubs generated.

• Getters and Setters: A quick way to create getter and setter methods is to select
a field and then select Source > Generate Getter and Setter… The following
figure shows the same:

University of Sheffield – Genesys Solutions 9


Java in Eclipse Tutorial
Figure 7: Generating Getter and Setter Methods

• try/catch statements: If an expression is selected and then Source > Surround with
try/catch, the code is analyzed to see if any exceptions are thrown within the scope of
the selection and try / catch blocks are inserted for each. This works well with the
Alt+Shift+Up and Alt+Shift+Down expression selection actions to accurately select
the code to which you want to apply try/catch blocks.

• Javadoc Comments: Javadoc comments can be generated for classes and methods
with Source > Add Javadoc Comment. The Javadoc is generated based on template
definitions in your Java Templates preferences.

• Superclass constructor: When a class is created, the option to generate constructors


from its superclass is available.

Java Errors

• Navigating Java Errors and Warnings

JDT displays two types of errors in the Java code. The first are errors and warnings
resulting from compiling your code. These are shown as entries in the Tasks view, as
markers on the marker bar, and as label decorations in the views. The second are
errors detected as you edit Java code, before it's compiled. These are shown as error
clues (red underlining) in the source and on the overview ruler on the right border
(small red rectangles).

University of Sheffield – Genesys Solutions 10


Java in Eclipse Tutorial
• Fixing Java Errors with Quick Fix

For errors having suggested corrections, a quick fix icon on the marker bar can
be seen. Quick fix can be used to correct a wide variety of problems, from spelling
errors and missing import statements to declaring local variables and classes. Click
on the icon to see a list of possible solutions as shown in the figure. If the cursor is
positioned within the red underlined text and then Ctrl+1 is pressed suggestions are
displayed. If an item in the pop-up is selected the proposed fix or a description can
be seen. Press Enter make the correction.

Figure 8: Quick Fix Suggestions

Refactoring

Refactoring refers to a class of operations that can be used to reorganize and make other
global changes to the code. This is done in response to API changes, to improve
maintainability, or to make naming more consistent. JDT provides state-of-the-art Java
refactoring capability that allows changes to be made and update references, including
string literals and Javadoc comments. This includes the ability to do the following.
• Move
Java elements can be moved and, optionally, modify references to the element
being moved. This can be used for fields, methods, classes, interfaces, packages,
source files, and folders.

University of Sheffield – Genesys Solutions 11


Java in Eclipse Tutorial
• Rename
Java elements can be renamed and, optionally, modify references to the element
being renamed. This can be used for fields, variables, methods, method
parameters, classes, interfaces, packages, source files, and folders.

• Extract Local Variable


This creates a new variable from the selected expression and replaces all
occurrences of the expression with a reference to the variable within the scope of
the enclosing method.

• Self Encapsulate
References to a field can be replaced with calls to its getter and setter methods.
This refactoring operation assumes the getter and setter methods do not yet exist.

When you request a refactoring operation, the Refactoring wizard appears (see figure
given below). The first page displays the minimum information needed to complete the
operation. Typically this is a new name or destination and options, for example, to update
references to the changed element.

Figure 9: Refactoring Wizard

Selecting Next displays a list of warnings and potential errors that will occur if you apply
the proposed changes to your code. If Finish is selected, this list of warnings and
potential errors will only be displayed if the code contains an error or warning of greater
severity than you've specified in your Java Refactoring preferences. The page after that,

University of Sheffield – Genesys Solutions 12


Java in Eclipse Tutorial
shown in the following figure, shows each of the changes and a before-and-after view of
the code.

Figure 10: Previewing Refactoring Changes


Running Code

To run Java code it has to be in one of the Java perspectives. There are 3 basic ways to
run code in Java projects: run (launch) a Java program with the Run action, run a Java
program with the Debug action, and evaluate (execute) a Java expression in a scrapbook
page. With the run action your program executes and it is not possible to suspend its
execution or examine variable or field values. In debug mode, the program can be
suspended, resumed, and examine a programs execution.

Java Programs, that is, classes with main methods, are identified with the Run label
decoration. To run a Java program select a class or a Java element containing a class,
and select Run from the menu or the Run pull down menu and then select Run As
>Java Application. JDT executes the main method and sends output to the console
view. Select from these to rerun programs. When a Java program is run, it is run as a
Java Application, JUnit test or run time workbench.

University of Sheffield – Genesys Solutions 13


Java in Eclipse Tutorial
Exercises
To complete the following exercise please gain complete understanding of the example
exercise given in the book: Chapter 29 – Section 1: HelloWorld.

1) Create a Java class to display “Good Morning”, “Good Afternoon”, “Good


Evening” to the user depending on the system time.

2) Create a Java project for the following problem. Create class that represents a
rectangle. The rectangle object could be created by specifying either the (x,y) co-
ordinates of its two diagonally opposite corners, or by specifying its length and
height and the (x,y) co-ordinates of its left corner. The rectangle should be a
square if only one of the length or breadth is specified. By default, if no co-
ordinates are specified the rectangle should be a square of unit length with two
edges along positive x and y-axes.
Define methods for the following:
a. that moves the rectangle to another position
b. that changes either the length or breadth of the rectangle
c. that determines whether a point (x,y) lies within the rectangle
d. Define another class that tests the above class.

What you learnt from the exercise???

a. To create a Java project.


b. To navigate through your project.
c. To view the classes and methods available in the Outline.
d. To compile and see the results in the console.
e. To run and see the output in the console.

Further reading and References


The Eclipse Java Developers Guide is the base reference for this tutorial and is also
quoted in the tutorial itself.

University of Sheffield – Genesys Solutions 14


Java in Eclipse Tutorial

Das könnte Ihnen auch gefallen