Developing Java applications for Eclipse

Hands-on exercises

Lab 01: Installing and Running Eclipse

Objective:

Eclipse is open source software, mainly used as an Integrated Development Environment (IDE) and as a product base.

In this lab you will install and run Eclipse. Before you start installing it, the product must be downloaded from the site. After you have downloaded the file, you can proceed with the installation. One the installation is completed you will run Eclipse.

Lab:

Step 1: Download Eclipse

The software can be downloaded from the site. From this page choose the appropriate geographic region (North America for example), and choose the build you want to download. In most of the cases you will want to download the latest build. Click on the latest build and than choose the platform where you want to install the product.

You will be prompt for what to do with the file. Choose to save the file to the local disk, and than specify the location for storing the file.

You have downloaded Eclipse at this point to your local machine.

Step 2: Install Eclipse

Once you have Eclipse downloaded to the local disk, you can proceed with the installation. The file you have downloaded is a ZIP file that contains entire Eclipse software. To install Eclipse, you simply unzip the downloaded file to the local disk, e.g. c:\ drive. Extracting the ZIP file to the c:\ drive will result in creating c:\eclipse directory that contains the Eclipse executable file (eclipse.exe).

Step 3: Run Eclipse


Double-click on the eclipse.exe file to run Eclipse. As Eclipse is built in Java, the software requires a Java runtime environment (JRE) to run. If you don’t have the path set for javaw.exe a dialog will come up:

In this case, set up the JAVA_HOME environment variable to point to your JDK installation directory. If you don’t have JDK installed on your local drive, you can download it from Sun’s Java site.

Once you have the JDK installed locally you can set up the JAVA_PATH environment variable.

After you have JAVA_PATH in place and double-click on eclipse.exe file, the installation will complete by creating default workspace directory under the install directory, e.g., c:\eclipse\workspace and the Workbench will appear.

Summary:

In this lab you have installed and run Eclipse.

Lab 02: Object-Oriented Concept, Game of Life

Objective:

In this lab you will learn about the problem domain that you will be working on for the reminder of the labs. This lab will explain the rules of the Game of Life, which you will try to model. The Game of Life is one of the most well-known 2-dimensional cellular automations. It is not a real game, as there are no players, no winners, or losers. It is a game where the starting position and the rules determine everything that happens after that. More information on the game and its background can be found at and links.

Rules of the Game of Life:
Life is played on a grid of square cells--like a chessboard -- extending infinitely in every direction. A cell can be live or dead.

A marker on a cell indicates a live cell. An empty cell indicates dead cell. Each cell in the grid has a neighborhood consisting of the eight cells in every direction including diagonals. To apply one step of the rules, count the number of live neighbors for each cell. What happens next depends on this number:


  1. Birth Rule: A dead cell with exactly three live neighbors becomes a live cell.

  2. Survival Rule: A live cell with two or three live neighbors stays alive.

  3. Death Rule: In all other cases, a cell dies or remains dead.

The number of live neighbors is always based on the cells before the rule is applied.

Lab:

Step 1: Identify objects in the game

Look at the game requirements above and try to identify the objects involved in the game (objects are usually identified by looking for nouns in the requirements).

What objects can you identify in the game?

Here are some questions that may help you identifying objects:

  • What represents the game itself?
  • What is the game played on?
  • What influences how the game evolves over time?

As there may be several appropriate answers to the questions above, it is probably correct to say that most obvious objects are game, board and rule, and that these objects make up the game.

Step 2: Identify basic classes

Based on the results of previous step what classes make up the game system? What are the class names, data and behavior?

The basic classes in the system may be Game, Board and Rule. Game has a board and set of rules, as well asan index “generation” to identify how many generations a board evolves. Board has cells, and it is initialized at creation time with some pattern of live and dead cells. Rule may have a name and a type and evaluates for every cell of the board. Rule type can be birth, survival, or death. When it evaluates, a Rule’s type is checked and based on the type different computations performed.

Summary:

In this lab you have analyzed the problem domain of the game you will be implementing in remaining labs.

Lab 03: Java Overview

Objective:

In this lab you will use the Scrapbook to evaluate some Java code. The Scrapbook is used in Eclipse to test and evaluate code. First you will need to create a project and within the project a new Scrapbook. The exercise should make you more familiar with the Eclipse environment as well as with basic Java syntax and rules.

Lab:

Step 1: Create a Scrapbook page

In the Eclipse environment select File -> New -> Project… -> Java -> Java Project, specify project name ExperimentLab and click Finish.

A New Java project is created. From the pull-down menu choose File -> New -> Other… -> Java -> Scrapbook Page than specify page name (ExperimentPage) with project selected and click Finish.

A page editor will open the page.

Step 2: Evaluating and displaying the following expressions:

Write and display the result of evaluating the following expression:

5+2*10/4–7

What is the result? Is it expected?

Answer: In evaluating expression above first 2*10 is evaluated to 20 and than 20/4 evaluates to 5. After that 5+5-7 evaluates to the final result 3.

Step 3: Experiment with primitives and variables

Write and display the result of evaluating the following expressions:

inta=6;

doubleb=a;

b

What happens? Was int converted to double, and why?

Answer: The double primitive type is a wider type than int type and JVM is capable of converting int to double by doing automatic, implicit casting.

Now write and display the result of evaluating the following expressions:

doublea=6;

intb=a;

b

What happens now? Why did you get the “Typemismatch:cannotconvertfromdoubletoint” message? What if you evaluated (int)b at the end?

Answer: The double type cannot be converted to int type, as it is wider type and no implicit casting is done. With explicit cast (int)b you are saying to the JVM that is ok to assign wider type to narrower type.

Write and display the result of evaluating the following expressions:

longa=45L;

doubleb=a;

b

What is the result of evaluating expressions now?

Write and display the result of evaluating the following expressions:

doublea=45.00;

longb = a;

b

What is the result of evaluating expressions now? Did you get the same result as in previous evaluation? Why?

Answer: Both types are same size. In the first expression evaluation a long type is assigned to a double and that is handled by JVM as double is of higher precision. In the second example however, higher precision type is assigned to lower, and you get an error. Even if an explicit cast was used here the JVM couldn’t handle it.

Step 4: Messages and objects

Inspect the following expression from the Scrapbook:

StringmyString=newString("My String");

myString

An Inspector shows up. Look at all characters that make up the inspected string.

Now evaluate the following expression:

StringmyString=newString("My String");

System.out.println(myString);

What is the message you sent to the output object? Where does the string get printed?

Answer: println is the message sent to the out object. The string is printed to the standard Java console represented with a Console view in Eclipse.

Step 5: Literals

Inspect the literal "This is a string" in the Scrapbook. What kind of object it is? What is the difference between the literal and evaluating newString("This is a string")expression?

Answer: The "This is a string" is a literal string object. It is the same as the string object created using newString("This is a string")expression.

Step 5: Arrays

Create and inspect an array of 5 integers initialized to zeros.

Create and inspect multidimensional array of 5 arrays created in the previous step.

Summary:

In this lab you have used the Eclipse Scrapbook to evaluate and run simple Java code.

Lab 04: Building Java classes

Objective:

In this lab you will become familiar with Eclipse Java Development Tools. In particular you will build basic game classes. After you finish this lab you should be familiar with creating classes using Eclipse, as well as using Eclipse Java refactoring tools.

Lab:

Step 1: Create the project

Create new Java project called LifeGame. To create a project, choose from the pull-down menu: File -> New -> Project -> Java -> Java Project and click Next. Specify name of the project and click Finish.

Step 2: Create package

Create package that will contain domain classes for the game. Packages group classes by functionality and are their namespaces. Usually classes that represent a model are in the same package, classes used for testing are in a different package, etc. To create new package, select the project and choose New -> Package from the context menu. Use org.eclipse.lifegame.domain as a package name and click Finish.

Step 3: Create Game and Board classes

Create a class Board that will have private field cells that is 2-dimensional array of integers. The cells field should be 10x10 and will contain either zeros or ones after game runs.

Generate getter and setter for the field. Add a constructor to the Board class that will accept 2-dimensional array as a parameter. This will represent pattern (initial cells state) for the game when it runs. Also override the default constructor to simply initialize cells to 2-dimensional array (10x10) when created.

Define two evolve methods in the class: evolve(Game) and evolve(Game,int). These methods do have a void return type and should iterate through their cells and based on rules evolve them to the next stage. The evolve method that accepts an integer as parameter evolves the board many times (depending on the parameter). Leave these methods empty for now as you will implement them in the later labs.

Override the toString() method in the Board class to simply return string "Board for game of life" . Later in the labs you will add more behavior to this method.

Create a class Game that has board field of type Board and field generation of type int (indicates how many generation should board evolve). Generate getter and setter for the added fields. Add a constructor to the Game class that will accept a board as a parameter and initialize game’s board field to the parameter, and initialize generation to 1.

Step 4: Creating Game and Board instances

Use the Scrapbook from previous labs to create and instance of the Board class. The classes will not be visible in the Scrapbook. First of all you have to add LifeGame project as a dependency to the project containing the Scrapbook.

Select the ExperimentLab project and choose Properties from the context menu. Click on the Java Build Path and select Projects tab. Select the LifeGame project and click OK.

In the Scrapbook choose Set Imports from the context menu and than select Add Packages… button. Select the package that contains classes and click OK twice.

Create an instance of the Game class passing the previously created board object. Inspect the game object.

In the Scrapbook, you may have code like the following:

int[][]boardCells={

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1},

{0,0,0,0,0,0,0,0,0,1}};

Boardboard=newBoard(boardCells);

Gamegame=newGame(board);

game

Summary:

In this lab you have created basic classes for Game of Life, and you became familiar with writing constructors, methods, and defining fields. Lab 05: Using the Debugger

Objective:

In this lab you will become more familiar with Eclipse Java Development Tools as you will be using some of the most commonly used tools, in particular the Debugger, and again the Scrapbook and the Inspector. These tools are very helpful when developing Java code. In this lab you will be stepping through the execution of a new Board constructor and you will try to identify and correct inappropriate behavior.

Step 1: Create a Rule class

In the LifeGame project, create new class Rule (same package as other game classes) that has a private field name of String type. Generate getter and setter for the field. The class will be used later in the labs to represent different game rules. For now you will create basics for this class.

Add a constructor to the class that accepts a String parameter and assigns it to the name field. The constructor should look like this:

publicRule(Stringname){

name=name;

}

Step 2: Create a Rule instance

Create new rule instance using defined constructor in the Scrapbook and inspect it. What is the name field value?

Obviously the name field is not set in the constructor for some reason. You will need to use the Debugger to see what happens when name is passed to the constructor.

In the LifeGame project, create new package org.eclipse.lifegame.test and add a LifeTester class to the package. When you create the class make sure you select creation of the main() method.

You will use this class to invoke Debugger, and test some code.

In the main() method write the code from the Scrapbook. The code should look like the following:

publicstaticvoidmain(String[]args){

Rulerule=newRule("Survival");

System.out.println(rule.getName());

}

Note that Rule class is in different package, and that you need to add import statement. Run the class by choosing Run -> Run As -> Java Application from the pull-down menu. The null is printed to the Console.

Step 3: Debug the constructor

Set a breakpoint in the main method and run the LifeGameTester again. Did Debugger come up? In order to invoke Debugger you need to choose Debug option instead of Run option for the LifeGameTester class.

The Debugger comes up and stops the execution in the main method where the breakpoint was set.

Step into the constructor and evaluate parameter passed as well as the name field. Can you see the problem with the code?

The constructor uses expression name = name; where name is the parameter passed to the constructor and at the same time a field in the class. When code evaluates, the passed name value is assigned to passed name variable. This has no effect and the Eclipse recognizes that and displays a warning next to this expression.

The appropriate expression would be this.name = name; where this.name means field and name means passed parameter.

If you evaluate code with the breakpoint from the Scrapbook, the Debugger should open. If code has warnings, the Debugger will not open.

Summary:

In this lab you have become familiar with using the Eclipse Debugger.
Lab 06: Control Statements

Objective:

In this lab you will use control statements to implement some of the behavior in the game classes. In particular you will implement Singleton pattern for the Game class, and the toString() method of the Board class.

Lab:

Step 1: Implement Singleton pattern for the Game class

How many instances of the Game class you will need at the same time in one single application? Well, most likely you will need only one instance of the Game class in one application. This instance should represent the game itself. This is known as a Singleton pattern, when no more than one instance of the class can be created within the same JVM. In this step you will implement this pattern for the Game class.

Define a private static field called theInstance in the Game class. This field should store the instance of the class, so field’s type should be Game. Add a publicstatic method getInstance() to the Game class that will return instance of the class stored in theInstance field . In the method check first if field’s value is null, and if it is create new Game instance and assign it to the field. This implementation is known as lazy initialization.