CSE logo University of Washington Computer Science & Engineering
 CSE 331 Homework 2 Part II -Winter 2012
  CSE Home   About Us    Search    Contact Info 

   

Homework 2, Part II: Eclipse setup and Java practice

Useful Links

Java API ("JavaDocs"): reference for all standard Java library classes. A Java programmer's Bible!

Java coding standards: The official "best practices" for coding style.

Working from home: instructions for setting up your personal machine and remotely accessing your files on the departmental servers. If the terms attu, ssh, and scp are Greek to you, this information was written for you!

Deadline: Wednesday, January 18 at 11pm Sunday January 22 at 11 pm; no late days allowed and no assignments accepted after that time.

In this part you will set up your development environment, familiarize yourself with Eclipse and other tools, and do some very light coding. This is to get the configuration/rampup stuff out of the way now and provide a Java refresher if needed. Although it looks long, the steps are mostly short and simple. Nevertheless, start early in case you run into configuration issues.

The CSE lab machines should have all the software you need. You are welcome to work from home, but we can't provide support for configuration problems specific to your personal machine. Please use Java 6 if possible rather than Java 7, which has not yet been installed in the labs. You don't need to uninstall Java 7 if you have it already, but using new Java 7 features will place you at the mercy of an unhappy grader. ;)

Errata

In HolaWorld, the greeting should be "Hola Mundo! Los mejores deseos de <uwid>!" (the <uwid> was initially omitted). This is a minor thing; don't worry if you used the original specs and left out the <uwid> as a result.


Set up Eclipse

  • Select workspace. When Eclipse starts, it will prompt you to choose a workspace. (If not, you can go to File >> Switch Workspace.) A workspace allows you to store and see all your code projects in one place. For organization and performance reasons, it's a good idea to create a workspace dedicated to this class.

    On Windows lab machines, choose a workspace name like Z:\workspace331. This will save your files in a directory called "workspace331" on your student account. Do not put your workspace on the C:\ drive or it will be deleted when you log out!

    On Linux lab machines, choose a workspace name like /homes/iws/<YourUserName>/workspace331.

  • Configure JDK. To configure Eclipse to use the Java JDK (development kit) instead of the JRE (runtime environment):

    • Open the Window >> Preferences dialog
    • Select Java >> Installed JREs
    • In the Installed JREs pane, if the selected name contains "jdk" rather than "jre" (e.g. jdk1.6.0_29), you can skip the following steps. Linux lab machines should be OK already, but not Windows.
    • Click Search... in the Installed JREs pane
    • In the window that appears, browse to where you installed Java. On the Windows lab machines, this is C:\ » Program Files » Java. Click OK.
    • In the Installed JREs list, check the box next to jdk1.6.0_27 (or the closest-sounding name that contains "jdk") and click OK

  • Configure generic errors. Java has a feature called generics that allows you to specify the type of elements held in a collection (e.g., sets and lists). Generics are the reason a single List class can be constructed as a List<String>, List<Integer>, List<Foo>, etc. If you use generics incorrectly, Eclipse by default marks the problems as warnings (indicated by yellow lines and markers). Change it so Eclipse issues errors (indicated by red lines and markers) instead:
    • Go to Windows >> Preferences and select Java >> Compiler >> Errors/Warnings
    • Under Generic types, change the value of Unchecked generic type operation to Error.
  • Switch to Java perspective. Go to Windows >> Open Perspective >> Other... and select Java (default) to open the basic Java IDE if it's not open already.
  • Create a new project. In its simplest sense, an Eclipse project is just what you'd think of as a project: a collection of code that forms a mostly self-contained program. You can see all the projects in your current workspace. This is useful, for instance, if you want to refer to past homework assignments but organize them separately. You'll complete several programming projects in this class, some spanning multiple homework assignments. We recommend putting each one in a separate Eclipse project.

    To get started, select File >> New >> Java project. Enter "HW2" for the name and select Finish.


Hello, World!

  • Create a new class named HelloWorld. Highlight "HW2" in Package Explorer (left-hand column), then go to File >> New >> Class. Notice that the source folder is listed as "HW2/src." Enter "HelloWorld" as the name and click Finish.
  • Using copy-and-paste, replace the contents of your new class with the text of the provided HelloWorld.java.
  • Eclipse compiles your code automatically as you type, so you should now be able to run HelloWorld (using Ctrl-F11, Run >> Run As >> Java application, or the green button with a white arrow in the toolbar). The output should appear in a console window.
  • Modify this class to set the greeting to Hello World! Best wishes from <uwid>! where <uwid> is the name that comes before your @u.washington.edu identifier. For example, Krysta's @u identifier is krystay so her greeting would be: "Hello World! Best wishes from krystay!" (Run it to check, of course.)

Hola, World!

  • Create another class, HolaWorld. This time, in the New Class window, indicate that the class should extend HelloWorld, either by typing HelloWorld directly in the "Superclass" textbox or by clicking the "Browse..." button and starting to type "HelloWorld" in the textbox.
  • Again using copy-and-paste, replace the template with the text of HolaWorld.java.
  • You should see compilation errors on two lines. Eclipse marks these errors with red squiggly lines in HolaWorld.java and the Package Explorer marks HolaWorld.java with a red crossmark. Mouse over the underlined code to see more details about the problem.
  • Fix these two errors. Eclipse's autocomplete feature can come in handy. Try these techniques:
    • When you type variableName. and pause for a moment, a window pops up listing variableName's available fields and methods. You can highlight each one to see a brief description.
    • CTRL+Space autocompletes many things in Eclipse. For instance, if you have a variable variableName and you type variableN, pressing CTRL+Space expands it to variableN.
  • Modify the greeting to be: "Hola Mundo! Los mejores deseos de <uwid>!", then run HolaWorld.
  • What is output when you invoke HolaWorld through its main method, and why? (Hint: if you modified the code to match the author's intention, there should be two lines of text.)

Eclipse tutorials (OPTIONAL)

Feel free to explore the following resources to learn more about Eclipse.

  • Go to the Eclipse Welcome screen (Help >> Welcome) and select the Tutorials icon. The only pertinent tutorial for now is Create a Hello World Application.
  • Go back to the Welcome screen and select the Overview icon. The Workbench Basic is the pertinent piece for now. Within that, read the Eclipse platform overview and the Basic Tutorial (under Getting started). You can skim (or skip) the parts on Working with other editors, Tasks and markers, Bookmarks, Comparing, Local history, and Responsive UI — and you needn't look at Team CVS tutorial or Ant and external tools tutorial. You should read/skim the Concepts piece, skimming or skipping the topics listed in the previous sentence.
  • If you prefer videos, you can watch some tutorials on Java and Eclipse, particularly Using the Eclipse Workbench and Eclipse and Java for Total Beginners.
  • There are quite a few more Eclipse tutorials if you search the web; feel free to post ones you've found useful on the discussion board.

RandomHello

  • Create a class called RandomHello. In the New Class window, check the box to automatically create a main method. Including the main method makes the class runnable, just like HelloWorld and HolaWorld.
  • Delete the "TODO" comment in main and replace it with the following code:
    RandomHello randomHello = new RandomHello();
    System.out.println(randomHello.getGreeting())
    
  • At this point, the class does not compile because getGreeting has not been defined. Implement this method to return a greeting from a list of five greetings at random. Use Java's Random class to select a greeting. Construct the random number generator with something like:
    Random randomGenerator = new Random();
    
    To create a random number between 0 and 4, use a method invocation like randomGenerator.nextInt(5);
  • Until you import the Random class, Eclipse will use a red underline to mark your code as an error. You must import the Random class by entering import java.util.Random; directly at the top of your file, by mousing over the error line and clicking on the recommended import, or by using CTRL-SHIFT-O to Organize your imports. This command adds import statements to your code for missing packages and removes them for unneeded packages.
  • One way to store a random greeting is using an array. This approach might look something like:
    String[] greetings = new String[] {
             "Hello World",
             "Hola Mundo",
             "Bonjour Monde",
             "Hallo Welt",
             "Ciao Mondo"};
     
    Feel free to be creative and define your own greetings!
  • You might have noticed that HelloWorld and HolaWorld defined their greetings as constants at the top of the file. This is generally good style, making it easier to identify and modify constant values (strings, ints, etc.) later on, and you should do the same for RandomHello. So the definition of your greetings array should actually look more like:
    public final String[] GREETINGS = new String[] {
    ...
    
  • After you write your code, run it several times to ensure that all five greetings can be displayed.

Debugger

Bugs happen. Debuggers help you squash them. In this part, you will be introduced to Eclipse's built-in debugger.

One of the most useful features of a debugger is the ability to set breakpoints in your program. When you run your program through the debugger, it will pause when it reaches a line with a breakpoint. You can inspect the current state of variables, then continue running your program normally or step through one line at a time to watch the variables change.

  • Create a new class named Adder. Replace the template with the text of Adder.java. This simple program is supposed to print the sum of two user-provided integers. Try running it a few times (or reading the source code) and you'll see that it doesn't behave as expected.
  • Double-click in the left-hand margin of the class next to the line return x - y; A blue circle should appear, indicating a breakpoint. (Double-clicking again removes the breakpoint.)
  • Run the program in debug mode by using F11, Run >> Debug, or the green bug icon in the toolbar. As before, enter two ints (say, 3 and 4) in the console when prompted. When your program hits the breakpoint, Eclipse asks if you want to open the Debug perspective. Choose yes.
  • The debug perspective looks overwhelming at first, but don't worry! In the top-right panel, select the "Variables" tab and you'll see the names and values of all variables in the current context. The top-left panel ("Debug") shows where the program is currently paused, where the current method was called, and so on. (This is called the stack trace). Double-click on a method name to see the corresponding line in the panel below, where you can view and edit your source code. Finally, the bottom-left panel shows the console window.

    What are all the names and values listed in the "Variables" panel? What does the "Debug" panel list as the current method and line number? (Write down the text that was highlighted when the Debug perspective first opened.)

  • Immediately above the "Debug" panel are several buttons for running your program. Mouse over each one for a description. "Resume" (green arrow) causes your program to continue executing normally until it finishes or hits another breakpoint. If you want to monitor what happens shortly after the breakpoint, use "Step Into" and "Step Over" (yellow arrows). "Step Over" executes the current line and pauses on the next line. "Step Into" enters any method called on the current line so you can execute that method line-by-line. (To finish the current method and jump back to the caller, use "Step Out.") Hit "Step Over" once to execute the return statement and exit computeSum. Hit "Step Over" again to progress to the next line..

    What are all the names and values listed in the "Variables" panel after EACH of the two step overs?

  • Hit "Resume" to allow the program to finish executing. Return to the default Java perspective by clicking "Java" in the top-right corner or by going to Windows >> Open Perspective >> Other....
  • When a program does something unexpected, it's not always clear where it went wrong. In the past, you may have used System.out.println() to probe variables at various points in your program. Breakpoints accomplish the same thing in a much more powerful way.


Additional Java practice (OPTIONAL)

If you're feeling a little rusty with Java, try the following resources:

  • Read Oracle's Java tutorial
  • Complete some or all of problems 1-5 from a past offering of 331. (For problems 2 and 3, you will need Primes.java. Problem 5 says to open Point.java, but the source code is listed below.)

Javadoc

Javadoc is the standard format for documenting Java code. All libraries in the official Java API are documented in this manner, as are many third-party libraries and projects. Clicking a class or method name anywhere in your code and hitting SHIFT+F2 brings up the appropriate Javadoc page, if available. The term "Javadoc" also refers to a tool that allows you to automatically generate your own Javadoc pages. See the section slides from Thursday, Jan. 12 for more information about how and why to use Javadoc.

  • Create a new class named IntStack.java. Replace the contents with IntStack.java. Notice that most methods already contain Javadoc comments, as does the class itself. Javadoc comments are denoted by an addition * at the start of the comment (/**...*/ instead of /*...*/) and are colored blue in Eclipse.
  • Add Javadoc comments above size(), pop(), and combine(), using the other methods in the class for examples. You should use each of @param, @requires, @throws, @modifies, @effects at least once (and perhaps more often - wherever they are appropriate).
  • Run the Javadoc tool to generate a Javadoc page for IntStack.
    • First, you need definitions for a few non-standard Javadoc tags we have defined for this course. Download and unzip javadoc331.zip. Copy the inner javadoc331/ directory (using the basic file system copy command). Back in Eclipse, select your HW2 project in Package Explorer and paste in the javadoc331/ folder.
    • Now, choose Project >> Generate Javadoc...
    • Eclipse needs to know where to find javadoc.exe. On Windows lab machines, enter "C:\Program Files\Java\jdk1.6.0_30\bin\javadoc.exe" in the "Javadoc command" textbox. On Linux lab machines, "/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/bin/javadoc" should work. On a home machine, click "Configure..." and browse to where you installed the JDK. Open the bin directory and look for javadoc or javadoc.exe in there. (On my Windows machine, it's C:\Program Files (x86)\Java\jdk1.6.0_29\bin.)
    • Under "Select types for which Javadoc will be generated," expand HW2 and click on (default pacakge). In the window on the right, check the box next to IntStack.java. Make sure no other classes are checked.
    • Verify that "Use standard doclet" is checked and that the textbox below contains the path to your HW2 project followed by doc. Click Next twice.
    • In the "Extra Javadoc options" box, enter:

      -taglet javadoc331.EffectsTaglet -taglet javadoc331.ModifiesTaglet -taglet javadoc331.RequiresTaglet -taglet javadoc331.ReturnsTaglet -taglet javadoc331.SpecfieldTaglet -tagletpath <pathToHW2Project>

      For example, on a Windows lab machine I might enter Z:\workspace331\HW2 for the path to the project.
    • Click Finish. If a dialog box asks if you want to update the Javadoc location for 'HW2,' say Yes.
    • A doc folder should appear underneath the HW2 project in Package Explorer. Inside is a long list of HTML files. Find and open IntStack.html. (If it opens source code instead of a webpage, right-click on the name and choose Open With >> Web Browser.) Verify that everything looks correct, specifically that your comments for every method show up and all the different tags are there. For reference, the appearance should be similar to the official Java API Javadocs.

JUnit

JUnit is a framework that allows you to run automated tests of Java programs. You can write tests that call your methods and verify that they have the expected behavior. We are using JUnit 4. If you are working from home, you might need to download JUnit 4, then tell Eclipse where to find it by going to Project >> Properties >> Java Build Path >> Libraries >> Add External JARs... and browsing to the junit.jar file you just downloaded.

  • You will store your JUnit tests in a tests package within your HW0 project. Like projects, packages are a way to organize code. If a single code project has several discrete parts (e.g. the UI, backend logic, and unit tests), each part might gets its own package, for example. Unlike projects, which are a feature of Eclipse, packages are part of the Java language. A class indicates to package to which it belongs, if any, by a package <name>; line at the top of the file.
  • Create a new JUnit test case. Choose File >> New >> JUnit Test Case. Check the box for "New JUnit 4 test," enters tests for the package name, enter MathTests for the name, and click Finish. If a message pops up that JUnit 4 is not on the build path, select the option to add JUnit 4 to the build path (it should be selected by default). If you are working from home, you might need to download and install JUnit 4 first.
  • Replace the contents of the new file with the text of MathTest.java. Notice the @Test tag above each method. This tag indicates that the associated method is a test to be run.
  • Run MathTests using Run >> Run as >> JUnit Test. A JUnit panel should appear on the left-hand side of the screen. At the top, it shows how many tests were run (6) and how many of these failed. Below, it lists the name of each test. A green checkbox means the test passed, while a blue X means it failed. Click on a failed test to see more information, including the expected and actual values, under "Failure Trace."

    Which tests failed? What were the expected and actual values?

  • Create another test case called ArraysTest and fill it with the text of ArrayTests.java. Try running it. All tests should pass this time, indicated by a green bar above the test results.
  • In a large program, you usually write a separate test case for each class being tested. You can run them all at once with a test suite. Create a new Java class named "AllTests" and fill it with the text of AllTests.java. This file lists all the test cases we want to run - in this case, MathTest and ArraysTest. Run AllTests, noticing how it shows the results of tests from both classes.
  • Take a screenshot of Eclipse after running AllTests. The JUnit panel should indicate that a total of 9 tests were run from MathTest and ArraysTest.


Turnin

Please submit the following files to the dropbox. Written answers to questions can all go in one file in any standard format (txt, doc, docx, pdf).

  • Answers to part 1, unless submitted during class.
  • Answer to HolaWorld question: what was printed to the console after you fixed the bugs and ran HolaWorld?
  • RandomHello.java
  • Answer to debugger questions:
  • What variables (names and values) were listed immediately on entering the breakpoint? What did the "Debug" panel list as the current method and line number? What variables (names and values) were listed after one "step over"? Two "step overs"?
  • Javadoc: IntStack.java and the IntStack.html Javadoc page.
  • Answer to JUnit questions: which tests failed in MathTest? What were the expected and actual values in each failed test?
  • JUnit test suite: your screenshot showing the results of running AllTests.

Please double-check that you turned in all parts!


CSE logo Computer Science & Engineering
Box 352350, University of Washington
Seattle, WA  98195-2350
(206) 543-1695
[comments to Hal Perkins]
Privacy policy and terms of use