Laboratory 3

Before starting

Classes should start with a capital letter, while attribute, method, package and project names start with a lowercase letter.

Class, attribute, method and package are Java concepts, whereas project is an Eclipse concept.

Recall how to compile and run Java applications in the command line, and how to create and run jar files here.


Being able to run a simple java application and create the corresponding .jar file, both from the command line and the Eclipse environment.

Get familiar with Eclipse environment.

Exercise 1

Consider the canonical program “hello world” which prints to the terminal the message

Hello world!

a) Edit and execute this canonical program in the Eclipse environment:

  • Create a Java project named lab3.
  • Create a Java package named hello.
  • Create a Java class named HelloWorld.
  • Add to the HelloWorld class a main method that prints the required string to the terminal.
  • Execute this canonical program within the Eclipse environment.
b) Compile and execute the program from the command line.

c) Create a .jar file with the program and execute it.


Understand the main java primitives:

  • classes, attributes and methods
  • constructors
  • inheritance from ObjecttoStringequals, hashCode

Exercise 2

A complex number is a number that can be expressed in the form a+bi, where a and b are real numbers. In this expression, a is the real part and b is the imaginary part of the complex number.

Complex numbers are added by adding the real and imaginary parts, that is, (a+bi) + (c+di) = (a+c) + (b+d)i.

They are subtracted by subtracting the real and imaginary parts, that is, (a+bi) - (c+di) = (a-c) + (b-d)i.

The multiplication of two complex numbers is defined as (a+bi) (c+di) = (ac-bd) + (bc+ad)i.

a) In a package named lab3, define a class Complex to represent complex numbers. A Complex object should be immutable once created; the add, subtract and multiply routines return newly-created Complex objects containing the results.
b) Define the textual description of a Complex object as “a+bi” where a is its real part and b is its imaginary part. Recall that this is done with the toString method.
c) Create another independent package named main. Define therein a class named Main with a main method. In the main method create two Complex objects, and print them to the terminal. Then add them, subtract them and multiply them. For each of these operations print the resulting Complex object to the terminal. 
d) Create two Complex objects with the same real and imaginary part. Test identity (==) and equality (equals) between them. Explain the result.
e) Back in lab3 package, override the equals method from Object to return true iff two complex numbers have the same real and imaginary part. Which other method from Object should be also overridden? Justify. Implement it, accordingly.