Equality in Java


Prerequisites

This Magercise covers some points on the semantics of equality in Java.

There are two ways to compare objects in Java, one is using the operator ==, which is true if the two objects being compared have the same identity (they are the same object). The other way is to use the equals method, which is defined in the class Object (and thus for all objects), and can be used to determine if two objects are equal on a value basis.

Equality is discussed in detail in the course notes.

Work Location

Perform all work for this magercise in VisualAge project MageLang Magercises, package magercises.Equality in Java.

If this project does not appear in your Workspace add it from the repository (if it exists there) or create a new project using this name.

Tasks

Perform the following tasks:

  1. As you did in the previous Magercise, add a method findEmployee to the Company class, in the Magelang/JavaBasics package. It takes as its argument an Employee and returns the same object if it is found to be an employee of the Company. Otherwise it returns null.

  2. Add a similar method called findEmployeeNamed. This method takes as its argument a String name and tries to find an Employee of that name. It returns the Employee object if successful.

  3. Add code in the main method of the EqualityTest class to use these two new methods to search for some employees.

  4. Run your solution via the EqualityTest class.

The task numbers above are linked to the step-by-step help page. Also available is a complete solution to the problem, and expected behavior, to demonstrate it.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.