This handout describes how to perform common Java development tasks on Athena with Eclipse, Emacs, and the command-line. You may choose whichever tool or combination of tools you feel most comfortable using.

Contents:

Starting the environment

Before you begin, you should run the student-setup.pl script described in Tools: Initial Setup and log out and back in again.

Emacs

Type the following command from the command-line to start Emacs in your current working directory:

emacs

Eclipse

Type this at the athena% prompt to start Eclipse:

runeclipse &

It is extremely important that you run Eclipse on Athena using exactly this command so that you run the correct version of Eclipse with the correct workspace.

Eclipse will start up, displaying a splash screen, and then show a workplace selection dialog:

Screenshot:
Eclipse Workspace Selection

Eclipse is asking you which workspace folder to use for this session. In response, type:

/mit/<username>/6.170

where <username> is your Athena username. (Note: Do not enter "~/6.170" for this step. Eclipse does not recognize the '~' character.) This directory should have been created for you by student-setup.pl. This directory has special permissions that let the 6.170 staff read files within it, so you should use it as your workspace when using Eclipse for 6.170. You may also want to select the checkbox to "Use this as the default and do not ask again". If you do not, when you start Eclipse on Athena in the future you will again see this dialog, but the correct workspace directory should already be entered as the default. In any case you can just click "Ok" or hit Enter to continue.

If this is your first time running Eclipse, you will need to click on the "Workbench" icon on the initial Eclipse screen to bring you into the main workbench view. Subsequent runs of Eclipse should bring up that view automatically.

Eclipse generics errors configuration

We expect your code to not have any generics-related problems. For example, the following code is unacceptable:

List myList = new ArrayList();
myList.add("foo");

The generic type List of myList should be parametrized, for instance, to String by replacing the first line with List<String> myList = new ArrayList<String>(); Note that List<String> myList = new ArrayList(); is also incorrect.

By default, Eclipse shows generics problems as warnings (indicated by yellow lines and markers). You can configure Eclipse to instead issue errors (indicated by red lines and markers) for these problems. Doing so will help you remember to write acceptable generics code.

To make this configuration, go to Windows » Preferences and select Java » Compiler » Errors/Warnings. Under Generic types, change the value of Unchecked generic type operation to Error.

(Note that there is another setting named Usage of a raw type that is set to Ignore by default. We recommend leaving this option disabled or set simply to Warn because it is specific to the Eclipse compiler and checks for more stringent requirements than required by the Java language specification. Thus, "Usage of raw type" may complain about issues, that while providing insight about your code, is not checked by Sun's javac, which is our official standard for compilation errors and warnings in this class.)

Eclipse Ant configuration

If you use Eclipse, you will need to make some one-time changes to the default Ant settings. If you have not yet checked out the psets module (see the Version Control document for instructions), you can skip this step and return later.

First, go to Windows » Preferences. In the window that appears, select Ant » Runtime. Select on Ant Home Entries (Default) in the list. Now click Add JARs, and select psets/lib/ant-contrib.jar and click OK twice.

Screenshot: Ant Home Entries

Screenshot: JAR Selection

Opening Files; Managing Multiple Files

If you've just checked out your code, you'll want to take a look at it. Emacs and Eclipse make it easy to open files, and both provide useful ways to manage multiple open files.

Emacs

You can create or open multiple files in Emacs by using CTRL+x CTRL+f (hold down CTRL, then press x and f in succession). Alternatively, you can select File » Open File ... from the menu bar. Either action will bring up the "Find File" mini-buffer in the bottom-most pane of your Emacs window. Type the name of the file that you would like to open or create, and then press ENTER. (Press TAB to complete a partially-typed filename, if there are multiple possibilities. Press TAB again to see a list of choices.) Every opened file resides in a separate Emacs buffer. To switch between buffers, you can hit CTRL+x b (hold down CTRL, press x, then let go of CTRL and press b) and type in the name of a buffer (which is usually the same as its filename). If you cannot remember the buffer name, you can hit TAB twice to see a list of buffers. Alternatively, you can use CTRL+x CTRL+b to see a list of all buffers and select one by middle-clicking on it with the mouse.

To see multiple buffers at the same time, use CTRL+x 2 to split your screen horizontally, CTRL+x 3 to split your screen vertically, or CTRL+x 5 2 to pop open a new editor window (you can choose to view any buffer in any section of your Emacs screen).

Eclipse

Switch to the "Java" perspective in Eclipse if you're not already in it (Window » Open Perspective » Other... » Java).

You can open multiple files in Eclipse by double-clicking each of them from the Package Explorer pane. Once you have multiple files open, you can switch between them quickly by holding down Ctrl and hitting F6 to bring up a dropdown box of open files, and then using the arrow keys to select the file whose editor you wish to bring into focus. You can also navigate through different files using the tabs on top of the editor pane.

Creating New Files

To create Java programs, you start by writing a Java source file. Java source filenames usually have a .java extension. Source files are just text files, which you may create and edit with Emacs or your favorite text editor, or with an IDE (integrated development environment) such as Eclipse.

Emacs

In Emacs, there is one command used to both create a new file and to open an existing file (of any type): CTRL+x CTRL+f. If you try to open a file that does not exist, Emacs will automatically create it for you.

Eclipse

New Java files

To create a new Java source file (with the .java extension), select from the top menu File » New » Class. A window will pop up, asking you details about the class. Leave the source folder as psets, and select a package (e.g. ps0 or ps0.optional). Choose a name for your class (e.g. MyClass) Type this name in the "Name" field and click Finish.

(If you want your new class to be executable, it will need a main method. Eclipse can generate that automatically for you if you check the appropriate checkbox in the New Java Class screen.)

Screenshot: New Java Class

New Text files

There is a similar procedure for creating new non-Java files such as text files. Select File » New » File. In the resulting dialog box, choose the parent directory of your new file and type the desired filename. If you want to create a new directory, you can do so by appending the directory name in front of your desired filename. For example, if you want to create a file problem4.txt in the directory ps0/answers, but the answers directory does not yet exist, you can choose ps0 as the parent directory, and then type answers/problem4.txt as the file name, and Eclipse will create the new directory and file for you.

Editing Java Source Files

Here are some useful actions that you can perform when editing Java code:

Autocompletion

Autocompletion is the ability of an editor to guess what you are typing after you type out only part of a word. Using autocompletion will reduce the amount of typing that you have to do as well as the number of spelling mistakes, thereby increasing your efficiency.

Emacs

Unlike Eclipse, Emacs is not aware of Java syntax, but it does have a general autocompletion feature that can be used by typing ALT+/. If you type out a few letters of a word, then hold down ALT and press /, Emacs will search backwards through your current buffer for the first word that begins with those few letters and fill it in for you. Successive presses of / while keeping ALT held down will cycle further backwards in your document for additional words. This feature works when you are editing Java code, or when you are editing any other type of file (such as problem set answers).

Eclipse

Eclipse continuously parses your Java files as you are editing, so it is aware of the names of variables, methods, etc... that you have declared thus far.

CTRL+Space can be used to autocomplete most things inside the Eclipse Java editor. For example, if you have declared a variable named spanishGreeting in the current class, and have typed the letters spanishGree in a subsequent line, Eclipse can infer that you mean to type spanishGreeting. To use this feature, press CTRL+Space while your cursor is at the right of the incomplete name. You should see spanishGree expand to spanishGreeting.

Eclipse can also help you autocomplete method names. Suppose you have a variable myList of type List, and you want to call the method clear. Begin typing "myList." — at this point, a pop-up dialog will display a list of available methods for the type List, and you can select the appropriate method with the arrow keys. You can force the popup to appear with CTRL+Space.

Organizing Imports

Eclipse

You can press CTRL+SHIFT+o to organize your imports in a Java file. Eclipse will remove extraneous import statements and try to infer correct ones for types that you refer to in your code but have not yet been imported. (If the name of the class that needs to be imported is ambiguous – for example, there is a java.util.List as well as a java.awt.List – then Eclipse will prompt you to choose which one to import.)

Viewing Documentation

Although you can directly browse the Java 1.5 API and other documentation at the Sun website, it is often useful to be able to cross-reference parts of your code with the appropriate documentation from within your editor.

Note that you need to generate the api docs locally before you can view docs for classes in the problem set.

Emacs

Pressing CTRL+h f (mnemonic: "help for function") runs jdk-lookup, which displays JDK documentation for a Java package, class, method, or field. You will see a prompt called "JDK doc for:" on the bottom of your Emacs window. Type in the Java element (for instance, "List") there (you can use tab completion to assist you). The documentation will appear in your web browser and not within Emacs itself.

Eclipse

To view the documentation of a class that is referred to in your code, place your cursor over the class's name, and press SHIFT+F2. A web browser window will be opened to the class's documentation page. If the class is provided by Java, the documentation page will be on Sun's website.

For your own classes, you will need to tell Eclipse where to find their documentation. To do so, right click on the project name (e.g. psets) in the Package Explorer pane and click "Properties". Select "Javadoc Location" in the left pane. Select the location, e.g. "file:/mit/<username>/6.170/psets/api/". (Note: the "file:" portion is important, since the location is expected to be recognizable by a web browser.) After setting the Javadoc location path, click OK.

Running Automated Tasks with Ant

Ant is a tool that can be used to automate many common tasks, such as compiling, testing, and running code. It is also used to validate a 6.170 problem set submission.. The instructions for Ant are stored in a "buildfile" named build.xml in each problem set's directory.

The buildfile specifies a set of targets that it supports, such as build and test. Note that the "help" target will output information about the supported targets in our buildfile.

Important: the validate target is only supported on Athena.

Command-line

To run Ant for problem set N from the command line, do the following:

cd ~/6.170/psets/psN
ant <target>

Emacs

To run Ant in Emacs, do Alt-x compile and then type the desired command, such as ant (which is the default).

Emacs's compilation mode has powerful commands that let you navigate the Ant output. One example is Alt-x next-error (shortcut: Ctrl-x `, which finds the next error in the Ant output and puts your cursor on the line that caused the error. See the Emacs documentation for more compilation-mode commands.

Eclipse

To run Ant in Eclipse, right click psets/psN/build.xml in the Package Explorer, where N is the desired problem set number. Now right click Run As » Ant Build... and in the resulting window, go to Targets and select the desired target(s).

There is a button near the left-hand side of the Eclipse toolbar that looks like a green 'play'
button with a suitcase below it which will re-run the last ant target (or other external tool) that you ran. The drop down button will let you easily re-run a number of ant targets.

Compiling Java Source Files

You must compile your source code before running it. The javac compiler is used to transform Java programs into bytecode form, contained in a class file. Class files are recognized by their .class extension. The bytecode in class files can be executed by the java interpreter.

Extensive on-line documentation for javac, java, and other tools in the JDK can be found through the Java documentation page at MIT.

Command-line

To compile all source files for a particular problem set, change your current directory to ~/6.170/psets/psN/, where N is the desired problem set number. Now type on the command-line:

ant build

This will run an Ant script that uses the instructions denoted in build.xml to compile all the .java files into corresponding .class files. Note that if one or more of your files do not compile, you will receive error messages and no .class files will be generated for the files that do not compile properly.

If you would like to manually compile files without the use of an Ant script, you can use javac to compile one or more source files into class files for execution by the Java interpreter. The following commands:

cd ~/6.170/psets
javac -Xlint -d . -g [more options] psN/file1.java psN/file2.java ...
will generate class files psN/file1.class, psN/file2.class, etc., for each specified source file. Type "man javac" at the Athena prompt for more information on javac options. You should almost always use the -g option, which will provide improved debugging output, and also the -Xlint option, which provides stricter compiler warnings.

Emacs

You can compile Java code by typing CTRL+c CTRL+c, which brings up a prompt where you can type in a javac command similar to what you can do from the command-line. Alternatively, you can also type ALT+x compile.

Eclipse

Eclipse is set up by default to automatically recompile your code every time you save. Classes with compile errors are marked in the Package Explorer with red cross marks. The compile errors, as well as compile warnings, also appear in the Problems view (usually situated at the bottom panel of Eclipse).

If your file is saved and Eclipse says that it does not compile but you believe that it should, make sure that all of the files on which your file depends are saved and compiled. If that does not work, try refreshing your project or using Project » Rebuild Project to force Eclipse to recognize the latest versions of everything.

Compiling With Ant in Eclipse

To compile with Ant in Eclipse, right click psets/psN/build.xml in the Package Explorer, where N is the desired problem set number. Now right click Run As » Ant Build... and in the resulting window, go to Targets and select build in the list of targets.

Running Java Programs

Once you have compiled your source code into class files, you can execute it with the Java interpreter.

Command-line

Typically, to run a program you will just type ant on the command line, possibly with a more specific target: ant target. However, you can also invoke the Java virtual machine directly via the java program.

Here is how to run Java programs from the command-line:

cd ~/6.170/psets
java -ea psN.theClassYouWantToRun

(The -ea flag enables assertions.)

For example, if you wish to run the RandomHello class from ps0, you would run:

java -ea ps0.RandomHello
    

Note that you do not include .java or .class at the end of the class name.

Emacs

There are several ways to run a program from within Emacs. Here are a few of them:

Eclipse

To run a program, right click on the Java source file containing the main() method and choose Run As... » Java Application.

There is also a button near the left-hand side of the Eclipse toolbar that looks like a
green 'play' button which will re-run the last application (or JUnit test, see below) that you ran.

Testing Java Programs with JUnit

JUnit is the testing framework that you will be using for writing and running through your test cases for your problem sets. Currently, 6.170 uses version JUnit 3.8.

For more information, visit:

6.170 JUnit Framework

Because your JUnit tests will likely have different class and method names than those of your classmates, there needs to be a standardized way of accessing every student's tests. Thus, each problem set comes with the JUnit test classes psN.test.SpecificationTests and psN.test.ImplementationTests. You will load all the JUnit tests you wrote in one of these two test suites.

psN.test.SpecificationTests, as it name suggests, should contain only specification tests — that is, those tests that check only for features implied by the specification. Consequently, your specification tests should be valid tests for any other person's code that claims to satisfy the same specification, even if that implementation is inherently very different.

Conversely, psN.test.ImplementationTests should contain implementation tests — that is, those tests that test only details that are specific to your implementation.

As an example, suppose you were implementing the following specification:

/**  Frobs the blarghnik.
  * @requires b != null
  */
public void frob(Blarghnik b);

A specification test should never pass in a null parameter to this method — this would violate the specified pre-condition. However, your particular implementation might check for the null parameter and throw a NullPointerException. Your implementation test can safely exercise this case by passing in null.

Similarly, an iterator specification which does not specify the order in which elements are returned indicates that no specific order should be assumed in a specification test. Your implementation may happen to keep elements in a sorted list, and so your implementation test may wish to check that the elements returned by the iterator are sorted.

Before your submit each problem set, you should ensure that your code passes both the SpecificationTests and ImplementationTests test suites. We have provided a convenient way to run these tests in each problem set's build file in ~/6.170/psets/psN/build.xml. The test gui.test targets will run psN.test.SpecificationTests and psN.test.ImplementationTests in the textual and graphical JUnit user interfaces, respectively. The validate target runs these tests on a fresh copy of your code it checks out from your repository.

Running JUnit Tests

You can run JUnit from several different environments:

Command-line

To run a particular test for a problem set, switch into the ~/6.170/psets/psN/ directory and run:

ant gui.test -Duse.test=<test class>

where <test class> is the JUnit class you want to run (e.g. ps0.test.FibonacciTest or ps1.test.RatPolyTest). Note the ~/6.170/psets/psN/test/ directory needs to exist (it can be empty) for this to work properly. As mentioned above, the test and gui.test (when used without an argument) Ant targets can be used to test SpecificationTests and ImplementationTests.

To run JUnit without using Ant, change to the ~/6.170/psets directory and invoke either java junit.swingui.TestRunner (for the GUI) or java junit.textui.TestRunner (for the text interface) with the name of the test class as a parameter. For example, if I wanted to run RandomHelloTest from ps0, I could type:

cd ~/6.170/psets
java junit.swingui.TestRunner ps0.test.RandomHelloTest

Emacs

To run tests from within Emacs, type Ctrl-c Ctrl-t (mnemonic: "test"). This runs a compilation process with the command ant test. You can use Emacs's normal compilation-mode commands (such as Alt-x next-error, which is also bound to Ctrl-x `) to navigate among the test results.

Eclipse

JUnit is integrated with Eclipse, so you can run the test suite from within the IDE.

If you are not working on Athena, you might have to explicitly add the junit.jar library using Project » Properties » Java Build Path » Libraries » Add External JARs and then telling Eclipse where your copy of junit.jar is located.