Solutions for On-Line Notes

This page contains all the solutions to the different exercises in the on-line notes pages of the PROG10082 course. Solutions to textbook questions or programming exercises are not listed here (ask your professor where these might be found).

Table of Contents By Lesson

Lesson: First Programs

Location: Your First Java Programs - bottom of the page

1.

public class FavouriteFoods
{
	  public static void main(String[] args) 
	  {
        // print my favourite foods
		    System.out.println("Wendi's Favourite Foods:");
		    System.out.println("Strawberries");
		    System.out.println("Chocolate");
		    System.out.println("Perch");
	  }
}

2. The minimum number of statements for Question 1 is one! For example:

public class FavouriteFoods
{
	  public static void main(String[] args) 
	  {
        // print my favourite foods
		    System.out.println("Wendi's Favourite Foods\nStrawberries"
            + "\nChocolate\nPerch);
	  }
}

3.

public class Tree 
{
	  public static void main(String[] args) {

        // print a little tree
		    System.out.println("   *");
		    System.out.println("  ***");
		    System.out.println(" *****");
		    System.out.println("*******");
		    System.out.println("   #");
		    System.out.println("   #");
	  }
}

Lesson: Programming Style and Standards

Location: Exercises

1. Reformat the following code segments by hand so that they follow proper standards:

a)

public class BadCode { 

    public static void main(String[] args) {

        // print the title of a story/book
        System.out.println("Flowers for Algernon");
    }
}

b)

public class BadCode { 

    public static void main(String[] args){

        // do some calculations and print the result
        System.out.print("6/4*2 is ");
        System.out.println(6 / 4 * 2);
    }
}

      

2. Add documentation to each of the corrected code segments above.

a)

/* BadCode
 * 
 * Version 1.0
 *
 * September 2012
 * 
 * This program displays a book title on the screen.
 * Programmed by Wendi Jollymore
 */
public class BadCode { 

    public static void main(String[] args) {

        // display book title
        System.out.println("Flowers for Algernon");
    }
}

b)

/* BadCode
 * 
 * Version 1.0
 *
 * September 2012
 * 
 * This program displays an arithmetic
 * expression on the screen with its result.
 * Programmed by Wendi Jollymore
 */
public class BadCode { 

    public static void main(String[] args){

        // display the expression
        System.out.print("6/4*2 is ");

        // calculate and display the result
        System.out.println(6 / 4 * 2);
    }
}

Lesson: Data Types and Values

Location: Scientific Notation

For practice, try converting these to scientific notation:

1. 34,982.58 = 3.498258x104
2. .004785 = 4.785x10-3
3. .123467 = 1.23467x10-1

Now try converting these values from scientific notation into regular floating-point numbers:

1. 9.7824 x 103 = 9,782.4
2. 2.222 x 107 = 22,220,000
3. 1.987 x 10-2 = 0.01987
4. 5.5 x 10-4 = 0.00055

Lesson: Data Types and Values

Location: Exponential Notation

Convert the following into exponential notation:

1. 34,982.58 = 3.498258e4
2. .004785 = 4.785e-3
3. .123467 = 1.23467e-1

Lesson: Arithmetic Expressions

Location: Arithmetic Operations

1. Modulus is often used to find out if a number is even or odd. How would this work?
Answer: Any number N % 2 will be equal to 0 if the number is even, and equal to 1 if the number is odd.

2. Rewrite each of the following expressions in proper Java syntax:
a. 3 x 4
Answer: 3 * 4
b. (x + 2)(x - 3)
Answer: (x + 2) * (x - 3)
c. 10 ÷ 2
10 / 2
d. 2x - 4
2 * x - 4

Lesson: Arithmetic Operations

Location: Order of Precedence

1. In the table below there are 5 sets of algebraic expressions and a corresponding incorrect Java expression. Find the errors in the Java expressions and rewrite them correctly.

 Algebraic
Expression
Incorrect Java
Expression
1.(2)(3) + (4)(5)(2)(3) + (4)(5)
2.6 + 18
2
6 + 18 / 2
3.    4.5    
12.2 - 3.1
4.5 / 12.2 - 3.1
4.4.6(3.0 + 14.9)4.6(3.0 + 14.9)
5.(12.1 + 18.9)(15.3 - 3.8)(12.1 + 18.9)(15.3 - 3.8)
  1. 2 * 3 + 4 * 5
  2. (6 + 18) / 2
  3. 4.5 / (12.2 - 3.1)
  4. 4.6 * (3.0 + 14.9)
  5. (12.1 + 18.9) * (15.3 - 3.8)

2. Evaluate each of the following integer expressions:
a. 20 - 5 / 2 + 3 = 20 - 2 + 3 = 21
b. 20 - 5 / (2 + 3) = 20 - 5 / 5 = 20 - 1 = 19
c. 10 * (1 + 7 * 3) = 10 * (1 + 21) = 10 * 22 = 220
d. 15 % 3 = 0
e. 10 + 5 % 2 = 10 + 1 = 11
f. 10 * 5 % 2 = 50 % 2 = 0

3. Evaluate each of the following expressions:
a. 6.0 / 4.0 = 1.5
b. 20.0 - 5.0 / 2.0 + 3.0 = 20.0 - 2.5 + 3.0 = 20.5
c. 20.0 - 5.0 / (2.0 + 3.0) = 20.0 - 5.0 / 5.0 = 20.0 - 1.0 = 19.0
d. (20.0 - 5.0) / (2.0 + 3.0) = (15.0) / (2.0 + 3.0) = 15.0 / 5.0 = 3.0

4. Evaluate each of the following expressions:
a. 10.0 + 15 / 2 + 4.3 = 10.0 + 7 + 4.3 = 17.0 + 4.3 = 21.3
b. 10.0 + 15.0 / 2 + 4.3 = 10.0 + 7.5 + 4.3 = 17.5 + 4.3 = 21.8
c. 3 * 6.0 / 4 + 6 = 18.0 / 4 + 6 = 4.5 + 6 = 10.5
d. 20.0 - 5 / 2 + 3.0 = 20.0 - 2 + 3.0 = 18.0 + 3.0 = 21.0
e. 3.0 * 4 % 6 + 6 = 12.0 % 6 + 6 = 0.0 + 6 = 6.0

5. Question 2.17 on page 51:

4 / (3 * (r + 34)) - 9 * (a + b * c) + (3 + d * (2 + a)) / (a + b * d)

Lesson: Variables - Rules for Variable Identifiers

Location: Variables

1. Which of the following are valid variable identifiers? For the invalid ones, explain why they're invalid.

VALID / INVALID

headings headings12 headings 12 (contains a space) 12headings (starts with a digit)
point.x (contains a dot) pointX Xpoint point^x (contains a ^ symbol)

2. Do question 2.4 on page 40.

The valid identifiers are: miles, Test, $4, apps, x, y, and radius.

The identifiers that are keywords are: class, public, and int.

All the rest are invalid: a++, --a, 4#R, and #44.

Lesson: Variables - Identifiers

Location: Variables

For each of the following statements below, declare a variable and initialize it to a null value. Use the most appropriate data types and identifier names.
a. to store a customer's last name
String custLastName = ""; b. to record the number of customers
int numCustomers = 0; c. to record the customer's outstanding balance
double custBalance = 0.0; d. to store the customer's phone number
String custPhone = ""; bonus: to record a single keystroke made by the user
char keystroke = '\0';

Lesson: Variables and Assignment Statements

Location: Assignment Statements

1. Find the errors in each of the following code listings:

// 1. a)
public class Qu2PartA
{
	  public static void main(String[] args)
	  {

		    width = 15 // missing semi-colon, data type
		    area = length * width; // area, length not declared
		    System.out.println("The area is " + area);
	  }
}

Corrected version:

// 1. a)
public class Qu2PartA
{
	  public static void main(String[] args)
	  {
		    double width = 15;
        double length = 10;
		    double area = length * width;
		    System.out.println("The area is " + area);
	  }
}
// 1. b)
public class Qu2PartB
{
	  public static void main(String[] args)
	  {
		    int length, width, area;
		    area = length * width;
		    length = 20;    // both of these 2 stmts should be
		    width = 15;     // before area = length * width
		    System.out.println("The area is " + area);
	  }
}

Corrected version:

// 1. b)
public class Qu2PartB
{
	  public static void main(String[] args)
	  {
		    int length, width, area;
		    length = 20;
		    width = 15;
		    area = length * width;
		    System.out.println("The area is " + area);
	  }
}
// 1. c)
public class Qu2PartC
{
	public static void main(String[] args)
	{
		int length = 20, width = 15, area;
		length * width = area; // backwards!!
		System.out.println("The area is " + area);
	}
}

Corrected version:

// 1. c)
public class Qu2PartC
{
	public static void main(String[] args)
	{
		int length = 20, width = 15, area;
		area = length * width;
		System.out.println("The area is " + area);
	}
}

2. Do question 2.5 on page 41 and question 2.6 on page 43.

Question 2.5: Identify and fix the errors:

Line 3: the variable k is not defined anywhere. To fix: Declare the variable k before the variable i:

int k = 3; // or whatever value you want
int i = k + 2;

Question 2.6: Identify and fix the errors:

Line 3: only i is being defined, j and k don't exist and are not being defined in this statement. To fix:

int i = 2, int j = 2, int k = 2;

OR...

int i = 2;
int j = 2;
int k = 2;

OR...

int i = 2, int j, int k;
j = k = i;

...and there's probably a few other similar solutions, too.

3. Write a program that calculates the amount of money to tip a wait person by coding the following tasks:

  1. Define a variable for the bill amount and initialize it to 35.10.
  2. Define a variable for the tip percentage and initialize it to 15.
  3. Define a variable for the tip amount.
  4. Calculate the tip as the bill amount multiplied by the tip percentage (remember that 15% = 0.15) and assign and store the result in the tip amount variable.
  5. Display the output on the screen as shown below:
Bill Amount: 35.1    Tip%: 15.0
Tip Amount: $5.265
public class Question2 {
    public static void main(String[] args) {
        double billAmount = 35.1;
        double tipPercent = 15.0;
        double tipAmount = tipPercent / 100 * billAmount;
        System.out.println("Bill Amount: " + billAmount + "\tTip%: " + tipPercent
            + "\nTip Amount: $" + tipPercent);

Lesson: Constants

Location: Assignment Statements

1. The code:

public class ConstTest {
    // constant for the name of the college
    public static final String COLLEGE_NAME = "Sheridan College";
    
    public static void main(String[] args) {
        // print out where we work/attend school
        System.out.println("You attend " + COLLEGE_NAME + ".");
        // change the name! o.O  NOPE
        COLLEGE_NAME = "Sheridan College Institute of Technology and Advanced Learning";
        // print it out again!
        System.out.println("You should really call it " + COLLEGE_NAME);
    }
}

You should get an error when you compile ("Error: cannot assign a value to final variable COLLEGE_NAME"). The values of constant variables can never change once they're declared and assigned!

Lesson: Shorthand Operators

Location: Assignment Operators

Determine, without coding a program, the output of the following code segment:

int counter = 1;
int increment = 2;
System.out.print(counter + " ");
counter += increment;
System.out.print(counter + " ");
counter *= increment;
System.out.print(counter + " ");
increment /= 2;
counter -= increment;
System.out.println(counter);
System.out.println("increment: " + increment);

Output:

1 3 6 5
increment: 1

Lesson: Shorthand Operators

Location: Exercises

1. Question 2.24:

14
        3

2. Examine the code listing below. What do you think the output should be? Write this down. Then run the program and see if you're correct.

public class Question2
{
	public static void main(String[] args)
	{
		int factor = 2;
		int sum = 10;
		System.out.println("sum is " + sum);
		sum *= factor;
		System.out.println("sum is now " + sum);
		sum *= factor;
		System.out.println("sum is now " + sum);
		sum *= factor;
		System.out.println("sum is now " + sum);
	}
}

Output should be:

sum is 10
sum is now 20
sum is now 40
sum is now 80

3. How do you think the output would change if you wrote the program in question 2 like this:

public class Question3
{
	public static void main(String[] args)
	{
		int factor = 2;
		int sum = 10;
		System.out.println("sum is " + sum);
		sum *= factor;
		sum *= factor;
		sum *= factor;
		System.out.println("sum is now " + sum);
		System.out.println("sum is now " + sum);
		System.out.println("sum is now " + sum);

	}
}

Output will be:

sum is 10
sum is now 80
sum is now 80
sum is now 80

4.

Question 2.25:

  1. False: not all expressions can be used as statements. For example, the expression 5 + x is an expression, but is not a proper Java statement. To turn it into a statement, you could assign the expression to a variable, e.g: int y = 5 + x;
  2. True
  3. True (it's an assignment expression)
  4. False (it's confusing but it is legal)

Question 2.26:

7
6
7
7

(In line 2, b receives the value of a before a is incremented)

Lesson: Formatting Output

Location: Formatting Console Output

1. What is the output from each of the following print statements?

**NOTE: using the ■ to denote a space

  1. System.out.printf("%3d", 5);
    ■■5
  2. System.out.printf("%3d", 12345);
    12345
  3. System.out.printf("%5.2f", 7.24);
    ■7.24
  4. System.out.printf("%5.2f", 7.277);
    ■7.28
  5. System.out.printf("%5.2f", 123.456);
    123.46
  6. System.out.printf("%5.2f", 123.4);
    123.40
  7. System.out.printf("%-5.2f", 7.277);
    7.28■
  8. System.out.printf("%-5.2f", 123.456); 123.46

2. What are the errors in each of the following print statements?

  1. System.out.printf("%d", 23)
    Missing a sem-colon!
  2. System.out.printf("%f", 5);
    %f is for floating-point numbers, but 5 is an int literal.
  3. System.out.printf("%4d", 123.4);
    %4d is an int format specifier, but 123.4 is a floating-point literal.
  4. System.out.printf("value 1: %d value 2: d", 5, 10);
    The second "d" is missing the % sign - it's treated as just the letter "d" and the compiler will tell you that the value 10 is missing a format specifier.

Lesson: Formatting Output

Location: Other Formatting Characters

What is the output from each of the following print statements?

  1. System.out.printf("%15e%n", 12.78);
    ■■■1.278000e+01
  2. System.out.printf("%-15e%n", 12.78);
    1.278000e+01■■■
  3. System.out.printf("%15s%n", "Programming");
    ■■■■Programming
  4. System.out.printf("%-15s%n", "Programming");
    Programming■■■■
  5. System.out.printf("%-7.2f%n", 12.78);
    12.78■■
  6. System.out.printf("%-5d%n", 12);
    12■■■
  7. System.out.printf("%03d%n", 0);
    000
  8. System.out.printf("%07.1f%n", 12.78);
    00012.8
  9. System.out.printf("%,010.1f%n", 12345.67);
    0012,345.7
  10. System.out.printf("%,10d%n", 7777);
    ■■■■■7,777

Lesson: Formatting Output

Location: Using String.format()

1. Write the code to declare and initialize two variables for the numerator and denominator of a fraction (initialize each to whatever values you wish, or use the values in the example, below). Write the code that displays the following message dialog:

exercise 1

The result of numerator / denominator should be formatted to 3 decimal places.

import javax.swing.JOptionPane;
public class Exercise1 {
    public static void main(String[] args) {
        int numerator = 1;
        int denominator = 3;
        JOptionPane.showMessageDialog(null, String.format("%d/%d = %.3f", 
            numerator, denominator, ((double)numerator / denominator), 
            "Fractions", JOptionPane.INFORMATION_MESSAGE);
    }
}

2. Write the code to display the values below in a single message dialog box, one value per line. Each value should be formatted to be right-justified, lined up at the decimal point, and showing only one digit after the decimal point:

35 28.29 143.12 .8899

import javax.swing.JOptionPane;
public class Exercise1 {
    public static void main(String[] args) {
        String output = String.format("%6.2f%n%6.2f%n%6.2f%n%6.2f",
            35.0, 28.29, 143.13, .8899);
        JOptionPane.showMessageDialog(null, output, 
            "Question 2", JOptionPane.INFORMATION_MESSAGE);
    }
}

Lesson: Math Class Methods

Location: Using String.format()

1. Use Chapter 5.10 of your textbook or the Math class documentation as a reference. What Math class methods would you use to perform the following tasks:

  1. find the square root of 13
    Math.sqrt(13)
  2. find the minimum value of the two numbers stored in the variables dblNum1 and dblNum2
    Math.min(dblNum1, dblNum2)
  3. find the ceiling of -123.45
    Math.ceil(-123.45)
  4. find the floor of -123.45
    Math.floor(-123.45)
  5. find the absolute value of -123.45
    Math.abs(-123.45)

2. Write a single statement to perform each of the following calculations and store each result in a variable of the appropriate type:

  1. The square root of x - y
    double root = Math.sqrt(x - y);
  2. The absolute value of a2 - b2
    double value = Math.abs(Math.pow(a, 2) - Math.pow(b, 2));
  3. The area of a circle (pi multiplied by radius-squared)
    double radius = Math.PI * Math.pow(radius, 2);

3. Write each of the following expressions as a single Java statement:

a.   double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
b.   double p = Math.sqrt(Math.abs(m - n));
c.   double sum = a * (Math.pow(r, n) - 1) / (r - 1);

Lesson: IPO

Location: IPO Charts

1. Define the inputs, processing, and outputs for a program that gives the surface area and volume of a cylinder.

Inputscylinder radius
cylinder height
Processingsurface area = 2 * PI * radius2 + height * 2 * PI * radius
volume = height * PI * radius2
Outputsurface area
volume

2. Define the inputs, processing, and outputs for a program that displays the future value of an investment for a principal P at a rate R compounded yearly for n years. The formula for compound interest is final amount = P(1+R/100)n.

Inputsprincipal
interest rate
number of years
Processingfuture value = principal * (1 + rate/100)years
Outputfuture value of investment

Lesson: IPO

Location: Exercises

a) Develop a solution for a program that converts a temperature from Fahrenheit to Celsius. (Celsius temperature = 5.0/9.0 * (Fahrenheit temperature - 32.0).

InputFahrenheit temperature
Processingcelsius = 5.0/9.0 * (fahrenheit - 32.0)
OutputCelsius temperature

b) Develop a solution for a program that calculates a person's target heart rate (a target heart rate is the heart rate you should aim to maintain while you're working out). Use the following formula: Target Heart Rate = .7 * (220 - your age) + .3 * Resting Heart Rate (your resting heart rate is your heart rate while you're not participating in any physical activity).

Inputresting heart rate
age
Processingtarget heart rate = .7 * (220 - age) + .3 * resting heart rate
Outputtarget heart rate

c) Write a tip calculator that allows a restaurant or bar customer to calculate the amount of a tip to give their wait person. The program should allow the customer to specify the bill amount and the percentage of tip they would like to give.

Inputbill amount, tip percentage
Processingtip amount = tip percentage / 100 * bill amount
Outputtip amount

d) The three ingredients required to make a bucket of popcorn in a movie theatre are popcorn, butter, and a bucket. Write a program that requests the cost of these three items and the price of a serving of popcorn (assume we have only one size). The program should then display the profit.

Inputcost of bucket
cost of butter
cost of popcorn
selling price
Processingprofit = selling price - (cost of bucket + cost of butter + cost of popcorn)
Outputprofit for one bucket of popcorn

e) You would like to be able to calculate your average grade for all the courses you've taken in first semester. Write a program that prompts you for the grades for the five courses you would have completed in first term. After recording all five grades, display the average grade on the console.

Sample output using sample data:

You entered your five grades as:  85.6 78.9 75.5 90.0 86.5
Your average grade:  83.3
Inputcourse 1 grade
course 2 grade
course 3 grade
course 4 grade
course 5 grade
Processingaverage grade = (course 1 grade + course 2 grade + course 3 grade + course 4 grade + course 5 grade) / 5
Outputlist of grades input
average grade

Lesson: Getting User Input

Location: Input Using Scanner

a)

Question a) temperature conversion

b)

Question b) target heart rate

c)

Question c) tip amount

d)

Question d) popcorn profit

3)

Question e) average grade

Lesson: String and Character Operations

Location: Characters and Character Operations

1. Write a program that finds the ASCII code for each of the following character values:

  1. '7'
  2. '1'
  3. 'a'
  4. 'A'
  5. 'z'
  6. 'Z'
  7. '*'
public class CharOps {
    public static void main(String[] args) {
        int value = 0;
        char c1 = '7';
        value = c1;
        System.out.println(value);
        char c2 = '1';
        value = c2;
        System.out.println(value);
        char c3 = 'a';
        value = c3;
        System.out.println(value);
        char c4 = 'A';
        value = c4;
        System.out.println(value);
        char c5 = 'z';
        value = c5;
        System.out.println(value);
        char c6 = 'Z';
        value = c6;
        System.out.println(value);
        char c7 = '*';
        value = c7;
        System.out.println(value);
    }
}

2. Open the following chart in a new browser window/tab: Simple ASCII Table.

  1. What is the decimal value for the character 'A'?
    65
  2. What is the decimal value for the character 'a'?
    97
  3. What do you think would each of the following statements would evaluate to?
    1. (char)('m' - 5) = (char)(109-5) = (char)(104) = h
    2. (char)('K' + 6) = (char)(75 + 6) = (char)(81) = Q
    3. (char)('y' - 'V') = (char)(121 - 86) = (char)(35) = #
    4. (char)('K' + '*' - 1) = (char)(75 + 42 - 1) = (char)(116) = t
  4. What character has a decimal value of 0?
    the null-character, or \0

Casting and Converting

Location: Explicit Casting

1. How would you use casting to solve the problem in the TestData example in the first section?
Cast one or both of val1 and val2 into a double value; you'll also have to declare result as a double:
double result = (double)val1 / val2

2. Using the declaration/initialization statements below, determine the result of each of the following explicit casts.

double dNum1 = 5.5;
double dNum2 = 10.2;
double dNum3 = 1.1;
  1. (int)dNum1 = (int)5.5 = 5
  2. (int)dNum2 = (int)10.2 = 10
  3. (int)dNum3 = (int)1.1 = 1
  4. (int)(dNum1 + dNum3) = (int)(5.5 + 1.1) = (int)(6.6) = 6
  5. (int)dNum1 + dNum3 = (int)5.5 + 1.1 = 5 + 1.1 = 6.1
  6. (double)((int)dNum1) + dNum3 = (double)((int)5.5) + 1.1 = (double)(5) + 1.1 = 5.0 + 1.1 = 6.1
  7. (double)((int)(dNum1 + dNum3)) = (double)((int)(5.5 + 1.1)) = (double)((int)(6.6)) = (double)(6) = 6.0

Lesson: Relational and Logical Operators

Location: Relational Expressions

1.

  1. x == 3: relational expression
  2. x = 3: assignment statement
  3. x >= 3: relational expression
  4. x * 3: mathematical expression
  5. 3 < x: relational expression
  6. x - 3 <= 10: relational expression

2.

Scanner in = new Scanner(System.in);
int value1 = (int)(Math.random() * 10) + 1;
int value2 = (int)(Math.random() * 10) + 1;
System.out.printf("What is %d + %d?", value1, value2);
int answer = in.nextInt();
int realAnswer = value1 + value2;
boolean correct = realAnswer == answer;
System.out.printf("%d + %d = %d is %B%n", value1, value2, realAnswer, correct);
      

Comparing Strings

Location: Comparing Strings

Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
String name = in.nextLine();
System.out.println("Do we have the same name? " +
    name.equalsIgnoreCase("Freddie"));

Logical Operations

Location: Logical Operations

1.

  1. a == 5 TRUE
  2. b * d == c * c
    = 2 * 5 == 4 * 4
    = 10 == 16 = FALSE
  3. d % b * c > 5 || c % b * d < 7
    = 5 % 2 * 4 > 5 || 4 % 2 * 5 < 7
    = 1 * 4 > 5 || 0 * 5 < 7
    = FALSE || TRUE = TRUE
  4. d % b * c > 5 && c % b * d < 7
    = 5 % 2 * 4 > 5 && 4 % 2 * 5 < 7
    = 1 * 4 > 5 && 0 * 5 < 7
    = FALSE && TRUE
    = FALSE

2. Given that:
a = 5
b = 2
c = 4
d = 6
e = 3
What is the result of each of the following relational expressions?

  1. a > b
    = 5 > 2
    = true
  2. a != b
    = 5 != 2
    = true
  3. d % b == c % b
    = 6 % 2 == 4 % 2
    = 0 == 0
    = true
  4. a * c != d * b
    = 5 * 4 != 6 * 2
    = 20 != 12
    = true
  5. d * b == c * e
    = 6 * 2 == 4 * 3
    = 12 == 12
    = true
  6. a * b < a % b * c
    = 5 * 2 < 5 % 2 * 4
    = 10 < 1 * 4
    = false
  7. c % b * a == b % c * a
    = 4 % 2 * 5 == 2 % 4 * 5
    = 0 * 5 == 2 * 5
    = false
  8. b % c * a != a * b
    = 2 % 4 * 5 != 5 * 2
    = 2 * 5 != 10
    = false
  9. d % b * c > 5 || c % b * d < 7
    = 6 % 2 * 4 > 5 || 4 % 2 * 6 < 7
    = 0 * 4 > 5 || 0 * 6 < 7
    = 0 > 5 || 0 < 7
    = true
  10. d % b * c > 5 && c % b * d < 7
    = 6 % 2 * 4 > 5 && 4 % 2 * 6 < 7
    = 0 * 4 > 5 && 0 * 6 < 7
    = 0 > 5 && 0 < 7
    = false

3.

  1. A customer's age is 65 or more: custAge >= 65
  2. The temperature is less than 0 degrees: temperature < 0
  3. A person's height is over 6 feet: hight > 6.0
  4. The current month is 12 (December): month == 12
  5. The user enters the name "Fred": userName.equals("Fred") or userName.equalsIgnoreCase("Fred")
  6. The user enters the name "Fred" or "Wilma"
    userName.equals("Fred") || userName.equals("Wilma") OR
    userName.equalsIgnoreCase("Fred") || userName.equalsIgnoreCase("Wilma")
  7. The person's age is 65 or more and their sub total is more than $100
    age >= 65 && subTotal > 100
  8. The current day is the 7th of the 4th month
    day == 7 && month == 4
  9. A person is older than 55 or has been at the company for more than 25 years
    age > 55 || numYears > 25
  10. A width of a wall is less than 4 metres but more than 3 metres
    width > 3 && width < 4
  11. An employee's department number is less than 500 but greater than 1, and they've been at the company more than 25 years
    deptNum < 500 && deptNum > 1 && numYears > 25

4.

3.2: (try this by hand before checking your answer in your editor!)

true
false
false
true
true
true

3.3:

Neither set of statements is valid. If you go back to the lesson on Casting and Converting, you'll notice in the conversion chart that you can't cast a boolean into any primitive type, and you can't cast any primitive type into a boolean.

5.

3.18: Assuming x is 1:

(true) && (3 > 4) = true && false = false
!(x > 0) && (x > 0) = !(true) && true = false && true = false
(x > 0) || (x < 0) = true || false = true
(x != 0) || (x == 0) = true || false = true
(x >= 0) || (x < 0) = true || false = true
(x != 1) == !(x == 1)= false == !(true) = false == false = false

3.19:

a) num >= 1 && num <= 100

b) num >= 1 && num <= 100 || num < 0

3.20:

a) Math.abs(x - 5) < 4.5

b) Math.abs(x - 5) > 4.5

3.21:

  1. x > y > 0: not legal - each operator requires 2 operands
  2. x = y && y: not legal - y && y results in a boolean, which can't be assigned to an int
  3. x /= y: legal
  4. x or y: not legal - or is not a valid Java operator
  5. x and y: not legal - and is not a valid Java operator
  6. (x != 0) || (x = 0): not legal - x = 0 is an assignment statement

3.22:

a. x % 2 == 0 && x % 3 == 0
b. x % 6 == 0

In other words, is a number that is both evenly divisible by 2 and evenly divisible by 3, also evenly divisible by 6? Yes, since 2 and 3 are both factors of 6.

3.23:

x >= 50 && x <= 100 if x is 45, 67, or 101

x is 45:
45 >= 50 && 45 <=100 = false && true = false

x is 67:
67 >= 50 && 67 <= 100 = true && true = true

x is 101:
101 >= 50 && 101 <= 100 = true && false = false

3.24:

(x < y && y < z) is true
(x < y || y < z) is true
!(x < y) is false
(x + y < z) is true
(x + y > z) is false

3.25:

age > 13 && age < 18

3.26:

weight > 50 || height > 60

3.27:

weight > 50 && height > 60

3.28:

weight > 50 ^ height > 60

6.

d
d
false
-4

7.

a)
false
2
This is probably what you would expect to get: The entire expression evaluates to false, and x has a value of 2 after the statement executes: (x >= 1) is true, but (x > 1) is false, so the entire expression is false. After the evaluation of the conditions are complete, x increments by 1 and becomes 2.

b)
false
1
This may not be the output you expected: The expression evaluates to false, but notice that the value of x after this expression executes is 1. This is because of the short-circuiting of the Java && operator: Since the first condition (x > 1) is false, Java doesn't even bother checking the second condition, so therefore the x++ is never executed.

8.

Question 9. number is positive/negative

9.

Question 9. displaying trivia questions

The Conditional Operator

Location: The Conditional Operator

1.

Question 1. heads or tails

2.

Question 2. guess a number

3.

Question 3. rolling dice

Single-Sided Ifs

Location: Single-Sided Ifs

1.

Question 1. valid number version 1

2.

Question 2. valid number version 2

3. (textbook questions 3.4 and 3.5 page 80)

3.4

if (y > ) {
    x = 1;
}

3.5

if (score > 90) {
    pay *= 1.03; // pay = pay + (pay * .03) or pay = pay * 1.03
}

Double-Sided Ifs

Location: Double-Sided Ifs

Textbook questions 3.6 and 3.7 page 81:

3.6

if (score > 90) {
    pay *= 1.03;
} else {
    pay *= 1.01;
}

3.7 a)

If number is 30:

30 is even
30 is odd

(there's no braces so the 2nd println() will execute regardless)

If number is 35:

35 is odd

3.7 b)

If number is 30:

30 is even

If number is 35:

35 is odd

Programming Questions:

1.

Question 1. number is even or odd

2.

Question 2. simulate coin flip

3.

Question 3. guess a number

4.

Question 4. roll pair of dice

5.

Question 5. determine interest rate

6.

Question 6. calculate pay with overtime

7.

Question 7. validate department # (a)

8.

Question 8. validate department # (b)

9.

Question 9. validate department # (c)

Multi-Sided Ifs

Location: Multi-Sided Ifs

1. a. What would the output be if the user entered a final grade of 48? F

1. b. What would the output be if the user entered a final grade of 55? D

1. c. What would the output be if the user entered a final grade of 85? D

1. d. Why doesn't this program do what it's supposed to do? How would you rewrite it correctly? It doesn't work because the range check is not done properly. Since you're starting from the bottom and going up to higher values, you should be comparing grade to the highest value in each range.

Rewrite grades program

Question 2:

Question 2. determine interest

Question 3:

Question 3. calculate sales commission (img a, continued below...)
Question 3. calculate sales commission (img b)

Switch Statement

Location: Switch Statement

Textbook questions 3.30 and 3.31 page 103:

3.30

After the code is executed, y is 2 (both case 6 and default are executed)

Rewrite using if-else (rewrote as it executes):

int x = 3;
int y = 3;
if (x + 3 == 6) {
    y = 1;
}
y += 1;  // executes regardless of condition value

Rewrite as an else-if properly:

int x = 3;
int y = 3;
if (x + 3 == 6) {
    y = 1;
} else {
    y += 1;
}

3.31

After the code segment is executed, x is 17.

Rewrite as switch:

int x = 1;
int a = 3;
switch (a) {
    case 1:  
        x == 5;
        break;
    case 2:  
        x += 10;
        break;
    case 3:  
        x += 16;
        break;
    case 4:  
        x += 34;
}

1.

Question 1. convert if to switch

2.

Question 2. determine day of week

3.

Question 3. determine shipping charge

Nested Selections

Location: Nested Selections

1. What is the output of each of the following code segments:

a)

int x = 5;
int y = 10;
int z = 2;
if (x > y) {
System.out.println("twice x is " + (x * 2));
if (x * z == y) {
System.out.println("xz equals y");
}
} else {
System.out.println(y /= z);
}

0
(the first condition x > z is false, therefore it jumps to that if's matching else block and prints y /= z)

b)

int x = 5;
int y = 10;
int z = 2;
if (x > y) {
System.out.println("twice x is " + (x * 2));
}
if (x * z == y) {
System.out.println("xz equals y");
} else {
System.out.println(y /= z);
}

xz equals y
(the braces have moved around in this question: the if (x * z == y) is no longer inside the if (x > y) block, so it's evaluated regardless of the truth value of x > y)

Question 2:

Question 2. dvd rentals

Question 3:

Question 3. student residence

Question 4:

Question 4. medical fee reimbursement

Question 5:

Question 5. date validation part a
Question 5. date validation part b

Errors with Selections

Location: Errors with Selections

Do exercises 3.11 to 3.14 on page 86-87.

3.11

Code segment (a) is hard to read so you might want to re-write it using proper indentation, first!

Which are equivalent? (a), (c), and (d) are equivalent to each other.

(a) and (d) are not correctly indented (they should look exactly like (c)); (b) and (c) are correctly indented.

3.12

boolean newLine = count % 10 == 0;

3.13

Both (a) and (b) are correct syntactically and logically.

(b) is better because it's more efficient. With (a), the computer will execute both if-statements and thus evaluate both conditions, whereas in (b) it will evaluate only one condition and only have to move to the else if the condition is false: Therefore, (a) is more work than (b).

3.14

Segment (a):

If number is 14:
14 is even
If number is 15:
15 is is a multiple of 5
If number is 30:
30 is even
30 is a multiple of 5

Segment (b):

If number is 14:
14 is even
If number is 15:
15 is a multiple of 5
If number is 30:
30 is even

(The key here is that in (a) both if statements can be executed if both conditions are true. In (b), the if-else block is only executed if the if-block condition is false.)

Confirm Dialog

Location: Confirm Dialog

Data Validation

Location: Data Validation

Question 1:

Question 1. item qty and cost part 1

Question 2:

Question 2. enter positive number

Question 3:

Question 3. item qty and cost part 2

Question 4:

Question 4:

Question 4. gps coordinates

While Loops

Location: While Loops

1. For what values do each of these loops terminate?

  1. while (recCount != 10)
    when recCount contains the value 10)
  2. while (userInput.equals(""))
    when the userInput String object contains characters (when it isn't empty)
  3. while (x >= 5)
    when x's value becomes less than 5
  4. while (x < 5)
    when x's value becomes 5 or more
  5. while ( (x < 5) && (y > 10) )
    when x's value becomes 5 or more OR when y's value becomes 10 or less

2. a. What do you think is the output of this loop if the user enters the value 4?

System.out.print("Enter a value to count to:");
int number = keysIn.nextInt();
int counter = 1;
while (counter <= number) {
    System.out.print(counter + " ");
    counter++;
}
System.out.println("\nDone!");

Solution:
1 2 3 4 Done!

2. b. How would you modify this program so that the output appears instead as:

1
2
3
4
Done!

Solution: Change the print() inside the loop to a println().

3. What is the output of the following code segment?

int counter = 1;
int sum = 0;
while (counter <= 5)
     sum += counter++;
System.out.println(sum);

Solution:
15

4. What's wrong with the following program?

public class LoopProblem 
{
	public static void main(String[] args) 
	{
		// print from 1 to 10 by 2's
		int counter = 1;
		while (counter != 10)
		{
			System.out.println(counter);
			counter += 2;
		}
	}
}

Solution: You have an endless loop because counter will never be equal to 10.

5. a. Write a loop that prints the numbers from 1 to 10 with their squares, like this:

1		1
2		4
3		9
4		16
5		25
6		36
7		49
8		64
9		81
10		100

Solution:

public class Question5a {
    public static void main(String[] args) {
        int counter = 1;
        while (counter <= 10) {
             System.out.printf("%d %10d%n", counter, Math.pow(counter));
             counter++;
        }
    }
}

5. b. How would you make the loop do the same output backwards (from 10 to 1)?

Initialize the counter to 10
Change the loop condition to counter >= 1
Change the increment to a decrement (counter--)

6. Write a while loop that counts from 1 to 20 by 2's on one line:

2 4 6 8 10 12 14 16 18 20
public class Question6 {
    public static void main(String[] args) {
        int counter = 2;
        while (counter <= 20) {
             System.out.printf("%d ", counter);
             counter += 2;
        }
    }
}

This will work, too:

public class Question6 {
    public static void main(String[] args) {
        int counter = 0;
        while (counter < 20) {
             counter += 2;
             System.out.printf("%d ", counter);
        }
    }
}

7. What is the output of each of the following loops?

Example 1:

4
3
2
1

Example 2:

1
2
3
4

Example 3:
(no output)

Example 4:

3
2
1
0

Example 5:

9
8
7
6
5

Example 6:

1, 2
2, 1
3, 0
4, -1
x: 5 y:-1

Iteration

Location: Do-While Loops

1. What's the output of each of the following code segments:

Example 1:

4
3
2
1

Example 2:

9
8
7
6
5
4

Example 3:

1

Question 2a:

Question 2. a) enter valid grade

Question 2b:

Question 2. b) enter valid grade

Question 2c:

Question 2. c) enter valid grade

Question 3 (post-test loop):

Question 3. total results (do-while)

Question 3:

Question 3. total results (while)

Solutions to 5.2, 5.4, and 5.6 can be found on the textbook web site.

For Loops

Location: For Loops

1. What's the output of the following code segments:

a.

0, 1, 2, 3, 4, 
After the loop, i is 5

b.

0 4 8 12 16 20

c.

1 4 7 10 13 16 19

d.

20 16 12 8 4 0

Question 2:

Question 2. fahrenheit/celcius conversion table

Question 3:

Question 3. investment value

Nested Loops

Location: Nested Loops

1. What's the output of each of the following code segments:

Example a.

0:  0 0 
1:  1 2 
2:  2 4 
3:  3 6 
4:  4 8 
5:  5 10

Example b.

0:  0 0 0 
1:  3 2 1 
2:  6 4 2 
3:  9 6 3 
4:  12 8 4 
5:  15 10 5

Question 2:

Question 2. table of values

Question 3:

Question 3. box of *'s

Question 4:

Question 4. average scores

Nested Structures

Location: Nested Structures

Question 1:

Question 1. fahrenheit/celsius conversion

Question 2:

Question 2. grades to alpha grades

Nested Structures

Location: More Loop Exercises

Question 1:

Question 1. print triangle

Question 2:

Question 2. break even analysis

Question 3:

Question 3. calculate final grade

Solutions to 5.8, 5.10, 5.16, 5.18, 5.24, and 5.30 can be found on the textbook web site.

Methods 1: Basics

Location: Intro to Methods

Question 1:

Question 1. display greeting

Question 2:

Question 2. display closing

3.

I have some  methods:
This is method one.
This is method two.
Going back to main...
That's all!

Question 4:

Question 4. display personal greeting

Question 5:

Question 5. display java 10 times

Methods 2: Parameters

Location: Arguments/Parameters

Question 1:

Question 1. estimate age

2. If you try to pass a String into the guessAge() method, you get an error because the method is expecting an integer, but instead you passed it a String.

Methods 2: Multiple Parameters

Location: Multiple Arguments/Parameters

1.

  1. public void factorial(int n): a single int value
  2. public void getPrice(int type, double yield, double maturity): an int value, and then 2 double values
  3. public void getInterest(char flag, double price, double time): a char value, and then 2 double values
  4. public void backwards(String sentence): a single string value

2.

6.12: On line 3, the 2 arguments are reversed: the method accepts a String, then an int (see line 6) but line 3 is passing in an int argument, then a String argument. To correct it, use:

nPrintln("Welcome to Java!", 5);

Additionally, inside the nPrintln() method, the int argument is named "n" but there is a new local variable "n" being declared on line 7. I will assume they don't need the local variable at all so to fix it, remove line 7.

6.13: Pass-by-value means that a copy of an argument's value is passed into a method parameter variable, not the original. The effect is that you can then modify the parameter variable inside the method and it has no effect at all on the original argument variable.

Output of a) 2

Output of b)

2 
2 4 
2 4 8 
2 4 8 16 
2 4 8 16 32 
2 4 8 16 32 64 

Output of c)

Before the call, variable times is 3
n = 3
Welcome to Java!
n = 2
Welcome to Java!
n = 1
Welcome to Java!
After the call, variable times is 3

Output of d)

1 
2 1 
2 1 
4 2 1 
i is 5

Question 3:

Question 3. get alpha grade

Question 4:

Question 4. area and circumference of circle

Methods 2: Return Values

Location: Return Values

1. If you change the "perim" variable's data type to an int or to String, your program won't compile because calcPerimSquare() returns a double, and you can't put a double into an int or a String.

2. The two statements are different in that the first one doesn't store the return value anywhere - the perimeter returned by the method is not stored or output. The second statement does store the method's return value in a variable, so it can be used later.

Question 3a:

Question 3a. get alpha grade

Question 3b:

Question 3b. area and circumference of circle

4. You can find the solutions to these questions on the textbook web site.

Question 5:

Question 5. tip calculator

Methods 2: Scope

Location: Variable Scope

1.

in main: 
1. 1
  m1: 5 6
2. 1
  m2: 10
3. 1
        

2. a)

n is 10
now n is 0
num is 10

You get this output because when you pass the argument "num" into the doSomething() method into parameter "n", you are only passing a copy of the value ("pass by value"). When you modify the parameter n inside the doSomething() method, the argument num is not affected.

This is true of all primitive variables: they are passed by value.

2. b)

2
4
6

You get this output because when you pass an object into a method (remember, an array is a type of object), the argument's memory address is passed into the parameter. So for example, if the nums array is stored at address FF88, then FF88 is passed into the parameter "array". This means that when you access the parameter "array" inside the doSomething() method, you are going to the same array in memory that nums is pointing to. In the case of objects, you "pass by reference", which means you pass the argument's address/reference into the parameter. The effect of this is that you can modify the object inside the method via its parameter variable.

Methods 3: Method Overloading

Location: Method Overloading

1.

6.16: Ambiguous Invocation: both methods have a single int parameter.

6.17: a) the second method is the best match because we're passing 2 ints and the second method accepts an int and a double. b) will also execute the second method, since it's an exact match. c) will execute the first method, since it's an exact match.

2.

Ambiguous Invocation for the first and third doStuff() method: both accept a single String argument.

Question 3:

Question 3. constants I added to the program
Question 3. the methods I added to the program

String Processing

Location: String Processing

Question 1:

Question 1. display sentence backwards

Question 2:

Question 2. search and replace

Question 3:

Question 3. time difference

Question 4:

Question 4. display sentence backwards (words)

Question 5:

Question 5. count words with E's

Question 6:

Question 6. telephone digits

Question 7:

Question 7. social insurance number

String Comparison

Location: String Comparison

1.

  1. "happy", "HAPPY" greater than
  2. "123abc", "abc123" less than
  3. "hello, world", "hello, " + "world" equal to
  4. "", " " less than
  5. "television", "TV" greater than
  6. "12", "2" less than
  7. "sweet", "sweet-tooth" less than
  8. "one", "eighty" greater than

2.

  1. "happy".compareTo("HAPPY") 32
  2. "123abc".compareTo("abc123") -48
  3. "hello, world".compareTo("hello, " + "world") 0
  4. "".compareTo(" ") -1
  5. "television".compareTo("TV") 32
  6. "12".compareTo("2") -1
  7. "sweet".compareTo("sweet-tooth") -6
  8. "one".compareTo("eighty") 10

Question 1:

Question 1. determine if array is sorted

Question 2:

Question 2. sort array

Arrays

Location: Array Intro Exercises

1. For each of the following, declare an array with an appropriate name and type and allocate an appropriate amount of storage.

  1. a list of grades for 100 courses
    double[] grades = new double[100];
  2. A list of 10 names
    String[] names = new String[10];
  3. a list of 50 temperatures
    double[] temperatures = new double[50];
  4. a list birth years for 25 club members
    int[] birthYears = new int[25];
  5. a list of 200 product IDs (product IDs can include digits, letters, and the dash (-))
    String[] prodIds = new String[200];
  6. a list that keeps track of the numbers of students in 5 different classes (e.g. class 1 has x students, class 2 has y students, etc)
    int[] numStudents = new int[5];

2. Fill in the elements for the values[] array (it has 10 elements) as the following code executes:

int counter = 1;
values[0] = 10;
values[counter] = counter;
counter++;
values[5] = counter;
values[9] = values[5] + counter;
values[counter] = values[9] - values[1];
values[9] += ++counter;

Array: values[10]

101 30 02 00 04 3

Arrays

Location: Coding/Using Arrays

Question 1:

Question 1. display array backwards

Question 2a:

Question 2a. sentence to char[]

Question 2b:

Question 2b. search/replace char[]

Question 3:

Question 3. avg/high/low

Question 4:

Question 4. frequency table

Question 5:

Question 5. accumulate array

Question 6:

Question 6. is array sorted?

Arrays: Initializing

Location: Initializing Arrays

public class ArraysInit {
    
    public static void main(String[] args) {
        
        String[] courses = {"Computer Programming 1", 
            "Problem Solving & Programming Logic",
            "Mathematics for Computing",
            "Web Technologies 1",
            "Linux/Unix Operating System",
            "Underwater Basket Weaving"};
        
        for (int i = 0; i < courses.length; i++) {
            System.out.println(courses[i]);
        }
    }
}

Arrays: For-Each Loop

Location: For-Each Loop

public class ArraysInit {
    
    public static void main(String[] args) {
        
        String[] courses = {"Computer Programming 1", 
            "Problem Solving & Programming Logic",
            "Mathematics for Computing",
            "Web Technologies 1",
            "Linux/Unix Operating System",
            "Underwater Basket Weaving"};
        
        for (String c : courses) {
            System.out.println(c);
        }
    }
}

Arrays: Parallel Arrays

Location: Parallel Arrays

Question 1:

Question 1. revenue array

Question 2:

Question 2. high and low temps

Arrays: Passing/Returning

Location: Passing/Returning Arrays

2. a)

Before:
 1. 5,  2. 2
In Swap:
 1. 2,  2. 5
After:
 1. 5,  2. 2

2. b)

Before:
 1. 5,  2. 2
In Swap:
 1. 2,  2. 5
After:
 1. 2,  2. 5

2. c) In (a), the argument values are copied into the parameter variables, so when the parameter variables are swapped, it has no effect on the original arguments. In (b), you're passing the memory address of the array, not a copy of the array values. Therefore, when you swap the 2 array elements, you're modifying the actual array declared in the main() method.

In general, when you pass primitives, you're passing a copy of the values into the parameter variables (pass by value). When you pass objects, you're passing the address/reference of the argument object into the parameter variables, which means the parameter and argument are both referring to the same object in memory (pass by reference).

Exception Handling

Location: Exceptions Intro

Revisit your program that calculates the difference between 2 amounts of time.

Exception Handling

Location: Exceptions with Wrapper Classes

a) What is the name of the exception that is thrown when this code runs, and what line causes the exception?

NumberFormatException, on the parseInt() line.

b) What happens if you use strValue1 as the parseInt() method's argument instead of strValue2? Why does this happen?

You get the same exception, because strValue1 is a floating-point number; a floating-point number can't be parsed into an int because of the decimal point (ints can only have digits).

c) What exception is caused if you change the last line to:

double dblValue = Double.parseDouble(strValue2);

Same exception. A double can only be digits and one decimal point, so parseDouble() will throw a NumberFormatException if you try to pass it anything invalid.

d) What is the output of the following code?

String strValue1 = "2.5";
double dblValue = Double.parseDouble(strValue1);
System.out.println(dblValue);

2.5

Exception Handling

Location: More Exceptions Exercises

Question 1a:

Question 1a. get sales and commission rate

Question 1b:

Question 1b. get sales and commission rate

Exception Handling

Location: More Data Validation

get a valid department number

Intro to OOP

Location: Demonstration of Objects

 myAcct.withdraw(800);
myAcct.setRate(5.4);
System.out.println(myAcct);
// exception is thrown here:
myAcct.withdraw(1500);

Intro to OOP

Location: OOP Exercises

1.

MP3 Player
Properties:
status (on/off), current track, # of tracks, colour, model, brand, etc.
Methods:
play(), stop(), skip(), turnOn(), turnOff(), etc.
Sample objects:
the old player you bought 13 years ago, your mom's mp3 player she wears in the gym

Car
Properties:
make, model, colour, number of doors, engine type, engine status, etc.
Methods:
accelerate(), decelerate(), start(), changeGear(), etc.
Sample objects:
your car, your dad's car, the car you crashed into a snow bank

Student
Properties:
student id, first name, last name, program, gpa, address, phone number, email address, current term, etc.
Methods:
changeProgram(), register(), calculateGpa(), dropCourse(), printTranscript(), etc.
Sample objects:
you!

2.

the Room class
the TestRoom class

3.

the Square class
the TestSquare class

Constructor Methods

Location: Exercises

1.

the Circle class
the TestCircle class

2.

the Time class
the TestTime class

3.

the Dice class
the TestDice class

Instance Variables and Accessor/Mutator Methods

Location: Exercises

2.

the Circle class
the TestCircle class

3.

the Time class
the TestTime class

4.

the Dice class
the TestDice class

The toString() and equals() Methods

Location: Exercises

1. What would make 2 Room objects equal? It can depend on context. For example, in a program that is planning blueprints, two rooms would only be considered equal if the length of one room equaled the length of the second room, and the width of one room equaled the width of the second room. For example, if room1 had a length of 10 and a width of 20 and room2 had a length of 10 and a width of 20, then those 2 rooms would be equal:

public boolean equals(Object obj) {
    Room room = (Room)obj;
    return room.getLength() == this.length && 
        room.getWidth() == this.width;
}

Note that we have to use the accessors for the room variable because the width and length instance variables have private access inside the room class. However, for the current (this) room, we're inside the class itself so it's ok to refer to length and width directly.

What if room1 had a length of 5 and a width of 15, and room2 had a length of 15 and a width of 5? In this case, they would not be equal because you can't take a 5 x 15 room and replace it on a blueprint with a 15 x 5 room: they occupy the space differently. However, what if your room class was being used in a Health & Safety application that kept track of rooms and their occupancy? In that case a 5 x 15 room would be the same as a 15 x 5 room because they would both have the same occupancy, required number of doors and emergency exits, etc. In that case, you could simply compare the areas of the 2 rooms:

public boolean equals(Object obj) {
    Room room = (Room)obj;
    return room.calcArea() == this.calcArea();
}

There are probably other answers, but there's the 2 most common ones.

2. What would make 2 Time objects equal? Since this Time class models a time on a clock, 2 times would be equal if both of their hours were equal, both their minutes were equal, and both their seconds were equal. Even better, you could just compare the total seconds of each time and you'd have a little less work to do:

public boolean equals(Object obj) {
    Time time = (Time)obj;
    return time.calcTotalSeconds() == this.calcTotalSeconds();
}