Introduction to IDEA

Written by Jonas Kvarnstr÷m and checked for compatibility with IDEA 6.0 by Martin Magnusson. Please report any bugs, inconsistencies or vague requirements as soon as possible.

Introduction to Lab 1

The main development environment in this course will be IntelliJ IDEA 6.0, a very nice integrated development environment that provides support for programming rather than building GUIs. We strongly recommend that everyone uses IDEA -- even those of you who, like the lecturer, are long-time Emacs fans with multiple-modifier commands like C-A-\ and M-% hard-coded in your fingers. Unlike many other IDEs, IDEA is made for programmers and stays out of the way when you don't want it to interfere.

This lab is intended to allow you to get used to using IDEA. Therefore, the object-oriented concepts used in the exercises are quite simple — in fact, you should have learned these concepts before taking the course — and the exercises themselves might seem trivial. This is intentional, so that you are not distracted from learning the environment. (If you have never programmed in Java before, despite this being part of the prerequisites for taking this course, this lab may also help you get some experience with the most basic parts of Java before getting started with the main project.)

In addition to this lab, there is also an introduction to the features in IDEA available. Reading this takes a little bit of time, but should save you a lot of time in the end since you will be able to make better use of IDEA's features. Additional documentation is available from the IDEA documentation site.

This lab must be done in IDEA, and we strongly recommend that you use IDEA in the project too. The code generation and refactoring capabilities of this environment will make life a lot easier for you in the project lab, and we might require changes and refactorings to your code that are easy to do in IDEA but would take hours in Emacs.

After you have finished this lab, you are free to decide to use another environment. However, the final code you hand for your message forum project must be in the shape of a fully functional IDEA project! We will be using built-in IDEA functionality together with a number of plugins to enable us to navigate through your code more easily as well as to help assess the quality of your code.

This lab should not be handed in. Instead, you should ask a lab assistant to take a look at the finished code on screen. He might require a few improvements and changes before your code is approved.

Don't hesitate to ask the lab assistant to take a look at your code during any scheduled lab time, even if you don't have a particular question in mind. We might have suggestions that help make your code cleaner, or that might save time in the future.

Asking for Help

If you need to ask for help, you should first check the list of common problems. This list is updated during the course, so even if your problem was not listed a couple of hours ago it may be listed now.

If you want to ask for help by e-mail, please include the course code "TDDI48" in the subject.

If your problem isn't listed and there is no lab assistant available, you can still ask for help by e-mail. In that case, please make sure that you give us all the information you can find about the problem:

Getting started with IDEA

Installing IDEA
Starting IDEA
Creating a project in IDEA

Installing IDEA

Before you use IntelliJ IDEA you must install the IDEA configuration files in your home directory. This is done only once!

  ~TDDI48/idea/ideaconfig6.sh
      

This creates a directory called .IntelliJIdea60 in your home directory and copies some configuration files to that directory.

You must also add the JDK 5.0 module:

  module add prog/jdk/5.0
  module initadd prog/jdk/5.0
    

Starting IDEA

Several versions of IDEA have been installed in parallel. New updates will be installed as they are released and will be announced on the course home page. At the time of writing, the most recent version is IDEA 6.0.4 build 6148. To start it, use the following command.

  ~TDDI48/idea/idea-6148/bin/idea.sh
    

If new versions of IDEA are installed, you may have to change this command line to reflect the new version number.

Creating a project in IDEA

Follow these steps to create a project in IDEA. For TDDI48, you should create one IDEA project for the first lab and one IDEA project for the larger programming project.

  1. Create a new project using File | New Project. If this is the first time you start IDEA, the New Project dialog may appear automatically.

    Give the project a suitable name, preferably without Swedish letters ňń÷┼─Í (just in case...), for example "Lab1".

    Then tell IDEA the location where you want to save the project, for example in /home/noone123/tddi48/lab1/. You can type the path manually or press the "..." button to select a path. In the resulting dialog window, you can press the folder-with-a-star toolbar button to create a new folder.

    Press Next.

  2. You will be asked for a compiler output path where IDEA will place compiled classes. This could for example be "/home/noone123/tddi48/lab1/Lab1/classes/". The default value should be safe.

    Press Next.

  3. The next thing to specify is the JDK (Java Development Kit) to be used with your project files. Please use the newest version of JDK 1.5.x / 5.x available (at the time of writing, this should be JDK 1.5.0_10). If no version of JDK 1.5 is available, use the "+" button to add a new JSDK and select /sw/jdk-1.5.0_10 in the file dialog.

    Press Next.

  4. A project consists of one or more modules, which can be reused in more than one project. In this course, we will only use a single module for each project. Select "Create single-module project".

    Press Next.

  5. Since the first lab is not related to web applications, you will create a plain Java module, without any special web application related features. Select Java Module.

    Press Next.

  6. Give the module a name. You can give it the same name as the project, for example "Lab1", or you can choose another name.

    Specify the content root for the module. This is the location where all the files related to the module are stored. By default, this is the same directory as the project directory. Accepting the default location is a safe choice.

  7. A module can contain Java source files as well as other related files. In this step, IDEA wants to know where your source files are located. It is safe to accept the default, that is, to create a "src" subdirectory inside the module directory.

    Press Finish.

Exercise 1: Shape, Circle, and Rectangle

In this exercise, you will implement a few simple Java classes. We assume that you have already started IDEA and created an IDEA project as shown above.

Note again that the entire point of doing this lab is learning how to use IDEA. The end result does not matter -- we want you to explore some of the functionality available in the environment, and therefore you should make sure you actually use code generation, navigation and other features as described below. Just typing everything from scratch might get you through this tiny lab more quickly, but you won't learn as much and you will waste time during the much larger project.

First, a Shape class.

Then, a Circle class.

The third shape class is called Rectangle. Do you remember how you did this before?

Finally, a test class.

What is printed when you run ShapeTest (see instructions below)? Which methods and constructors are executed, and in which order? Make sure that you understand why.

Compiling a project in IDEA

You can compile the entire project using Build | Rebuild project, or use Build | Make Project (Ctrl-F9) to only recompile the files that have changed and the files that depend on them.

Running a Java program in IDEA

Running a program (a class with a main() method) in IDEA requires a run configuration. You can create new run configurations in the following way:

You can then run your program by selecting a run configuration in the drop-down menu beside the green "play" button in the toolbar, and then pressing the "play" button.

As a shortcut, you can also create a temporary run configuration for any program with a main() method, and then immediately execute this run configuration, in the following way:

Exercise 2: Data Hiding

In the previous exercise, all the fields you created were public. Now you realize your mistake: They should have been private! Make them private, introduce getters for all the fields (and setters, if you want to), and make sure that you use the getters and setters wherever this is necessary.

Go to the Circle class: Select Go To | Class: Ctrl-N and type "Cir" (which is auto-expanded), followed by Enter.

Choose Refactor | Encapsulate Fields. Select the checkboxes for x, y and radius to encapsulate these three fields. Select Get Access to create getters, and unselect Set Access (you do not want to create setters). Make the encapsulated fields' visibility private, and the accessor methods' visibility public. Unselect Use accessors even when field is accessible, so that you don't have to use the accessors within Circle, only outside the class. Click OK/Enter. You will get a refactoring preview, where the two uses of x and y in ShapeTest are shown. Here you can unselect items that you don't want to change, if any. Then you click Do Refactor: Alt-D.

Do the same thing in Rectangle. Since we never used Rectangle's fields outside its class, the refactoring preview only contains the fields themselves.

Exercise 3: Changing the Internal Representation

In this exercise, you will extend the program you wrote in Exercise 1 (Shape, Circle, Rectangle).

Create a new class Point. This class should have:

Rewrite the Circle class so that it uses a Point object instead of the old x and y fields. The old constructor should still exist, and should still take x and y arguments, but instead of saving x and y directly, it should create a new Point object that it stores in a Point field. You must also rewrite the two getters.

Rewrite the Rectangle class in the same way.

Exercise 4: Implement equals() and HashCode

In this exercise, you will extend the program you wrote in exercise 3 by implementing equals() and hashCode() methods for Point, Rectangle and Circle. (If you don't know what a hash code is, take a look at the definition in the Java Glossary.)

To generate equals() and hashCode() methods in a class, select Code | Generate: Alt-Insert and then select equals() and HashCode(). Select the fields that should be included in the comparison for equals and then for hashCode (all?).

If there are non-primitive fields (object-type fields such as the Point field in Circle and Rectangle, then IDEA will ask you for a set of non-null fields. A non-null field is a field whose value cannot be null, so that IDEA does not have to insert a null check for this field. If in doubt, do not select any non-null fields at all. In this example, though, we know that the center of a Circle is never null (always an actual Point).

Take a close look at the methods that are generated and ensure that they are what you intended. Never trust a code generation tool completely. Always double-check what has been generated. Tools are no substitute for knowing what you're doing!

Exercise 5: Using the Collections Framework

The Collections Framework contains several list classes, for example ArrayList.

In this exercise you will create two new data structures, a Queue and a Stack. These structures will not allow the user to add or remove inner elements; you can only push and pop elements at the correct "end".

You can still use an ArrayList for the inner storage, however.

Then write a Stack class, which is similar except that pop(Object obj) returns and removes the last object in the list, or throws NoSuchElementException if the list is empty.

Press F5 while visiting the Queue class to create a clone of that class. Select Stack as the new name. Change the new class according to the instructions above.

Finally, you should write a test program that uses your new classes. For example, you could write a test program that adds some strings to a Queue using push(), and then pop()s all the strings, one at a time, and prints them to the screen. Do the same thing using a Stack.

Exercise 6: The Collections Framework: Sorting and Iteration

Write a program that sorts all its command line arguments in alphabetical order and prints them to the screen.

First, create a list (ArrayList or LinkedList) and add all command line arguments to that list.

Then, sort the list using the static utility method Collections.sort(List list) (as you may remember from the lectures, this method is placed in the utility class Collections rather than in any specific list data type, since it can be used for any List).

After typing "Collections.sort(", press ctrl-shift-space to see all items of the appropriate type, that is, all items of type List. This is called SmartType Completion and automatically filters out all items except those of the correct type.

The reason for not using SmartType Completion always is that you may have to go through an intermediate step before you reach the intended type. For example, if you had wanted to type Collections.sort(foo.getBar().getList()), you would have had to use Basic Completion to complete foo and getBar(), and then you could have used SmartType Completion to complete getList().

Finally, print the resulting list. Ask the list for an Iterator that you use to iterate over all elements in the list.

First declare an Iterator variable, and make sure it points to the iterator you got from the list. Then use the itit template to actually use the iterator..

To test this program, run it with some command line parameters to sort.

Create a new run configuration as described earlier in these instructions. Add your command line parameters in the "Program parameters" field. Do not add them in "VM parameters"; those parameters are given to the Java virtual machine, not to your program.

Exercise 7: Rename some Fields

You just realized that you don't want the x and y coordinate fields in Point to be named x and y. Instead, they should be named xCoord and yCoord. Rename them.

Let's suppose you were in the Circle class when you got this idea. If you're not already there, go to Circle using Ctrl-N.

Hold down Ctrl as you move the mouse around the code. You will see tooltips showing information about the items over which the pointer is hovering.

Now ctrl-click Point in the code. You will automatically be moved to the Point class.

In Point, go to the x field and select Refactor | Rename: Shift-F6. Enter the new name for this field and press Enter. IDEA will ask you whether it should also rename the getter; please do so. After verifying that everything is correct in the refactoring preview, select click Do Refactor: Alt-D.

Do the same thing for y.

Exercise 8: Creating an Exception Type

Extend the program you wrote in exercise 3. Create a new exception type called NegativeSizeException, subclass of Exception. Modify the constructors of the Shape subclasses so that they throw a NegativeSizeException if the width, height, or radius argument is negative.

You may need to take care of potential NegativeSizeExceptions in certain places where you create objects.

IDEA can help you write catch statements. Use Ctrl-W (maybe multiple times) to select the code you want to surround with a try/catch statement, and then use Code | Surround With | Try/Catch: Ctrl-Alt-T 6 to generate the statement. Note that IDEA automatically determines which exceptions can be thrown within the block you marked, and adds catch clauses for those statements.

As always, you should test your program to make sure that it work.

The end

That's it: You've finished the first mandatory exercise. You should now ask the lab assistant to take a look at your code. You do not have to hand it in.


Jonas Kvarnstr÷m


Valid HTML 4.0!   [Check links]