Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section 5.13 Exercises

Exercises Data Exercises

Note:For programming exercises, first draw a UML class diagram describing all classes and their inheritance relationships and/or associations.

1. Paired Terms.

Explain the difference between the following pairs of terms:
(a)
Representation and action
(b)
Binary operator and unary operation
(c)
Class constant and class variable
(d)
Helper method and class method
(e)
Operator overloading and method overloading
(f)
Method call and method composition
(g)
Type conversion and type promotion

Type Sizes.

For each of the following data types, list how many bits are used in its representation and how many values can be represented:
2.
int bits and values
3.
char bits and values
4.
byte bits and values
5.
long bits and values (use ^ to represent to the power of).
6.
double bits and values. (use ^ to represent to the power of)

Fill in the Blanks.

Fill in the blanks.
7.
Methods and variables that are associated with a class rather than with its instances must be declared .
8.
When an operation involves values of two different types, one value must be before the expression can be evaluated.
9.
Constants should be declared .
10.
Variables that take true and false as their possible values are known as .

11.

Arrange the following data types into a promotion hierarchy: double, float, int, short, long, char, byte.

12. True/False Questions.

Assuming that o1 is true, o2 is false, and o3 is false, evaluate each of the following expressions:
(a)
    o1 || o2 && o3
  • True.

  • False.

(b)
    o1 ^ o2
  • True.

  • False.

(c)
    !o1 && !o2
  • True.

  • False.

13. Operator Precedence 1.

Arrange the following operators in precedence order: + - () * / % < ==

14.

Arrange the following operators into a precedence hierarchy: *,++, %, ==

15. Evaluate Expressions.

Parenthesize and evaluate each of the following expressions. (If an expression is invalid, mark it as such):
(a)
11 / 3 % 2 == 1
(b)
11 / 2 % 2 > 0
(c)
15 % 3 >= 21 %
(d)
12.0 / 4.0 >= 12 / 3
(e)
15 / 3 == true

16. Evaluate Code 1.

What value would m have after each of the statements that follow is executed? Assume that m, k, j are reinitialized before each statement.
int m = 5, k = 0, j = 1;
(a)
m = ++k + j;
(b)
m += ++k * j;
(c)
m %= ++k + ++j;
(d)
m = m - k - j;
(e)
m = ++m;

17. Evaluate Code 2.

What value would b have after each of the statements that follow is executed? Assume that m, k, j are reinitialized before each statement. It may help to parenthesize the right-hand side of the statements before evaluating them.
boolean b;
int m = 5, k = 0, j = 1;
(a)
b = m > k + j;
(b)
b = m * m != m * j;
(c)
b = m <= 5 && m % 2 == 1;
(d)
b = m < k || k < j;
(e)
b = --m == 2 * ++j;

18. More Expression Evaluation.

For each of the following expressions, if it is valid, determine the value of the variable on the left-hand side (if not, change it to a valid expression):
char c = 'a' ;
 int  m = 95;
(a)
c = c + 5;
(b)
c = 'A' + 'B';
(c)
m = c + 5;
(d)
c = (char) m + 1;
(e)
m = 'a' - 32;

19. Write Java Expressions.

Translate each of the following expressions into Java:
(a)
Area equals pi times the radius squared.
(b)
Area is assigned pi times the radius squared.
(c)
Volume is assigned pi times radius cubed divide by h.
(d)
If m and n are equal, then m is incremented by one; otherwise n is incremented.
(e)
If m is greater than n times 5, then square m and double n; otherwise square n and double m.

20. Trace the Java Code.

What would be output by the following code segment?
int m = 0, n = 0, j = 0, k = 0;
m = 2 * n++;
System.out.println("m= " + m + " n= " + n);
j += ( --k * 2 );
System.out.println("j= " + j + " k= " + k);

Writing Methods.

Each of the problems that follow asks you to write a method. Of course, as you are developing the method in a stepwise fashion, you should test it. Here’s a simple application program that you can use for this purpose:
public class MethodTester {
    public static int square(int n) {
        return n * n;
    }
    public static void main(String args[]) {
        System.out.println("5 squared = " + square(5));
    }
}
Just replace the square() method with your method. Note that you must declare your method static if you want to call it directly from main() as we do here.
21. Sales Tax Method.
Write a method to calculate the sales tax for a sale item. The method should take two double parameters, one for the sales price and the other for the tax rate. It should return a double. For example, calcTax(20.0, 0.05) should return 1.0.
22. Day of Week Method.
Challenge: Suppose you’re writing a program that tells what day of the week someone’s birthday falls on this year. Write a method that takes an int parameter, representing what day of the year it is, and returns a String like ``Monday.’’ For example, for 2004, a leap year, the first day of the year was on Thursday. The thirty-second day of the year (February 1, 2004) was a Sunday, so getDayOfWeek(1) should return “Thursday” and getDayOfWeek(32) should return “Sunday.”
Hint.
If you divide the day of the year by 7, the remainder will always be a number between 0 and 6, which can be made to correspond to days of the week.
23. Day of Year Method.
Challenge: As part of the birthday program, you’ll want a method that takes the month and the day as parameters and returns what day of the year it is. For example, getDay(1,1) should return 1; getDay(2,1) should return 32; and getDay(12,31) should return 365.
Hint.
If the month is 3, and the day is 5, you have to add the number of days in January plus the number of days in February to 5 to get the result: 31 + 28 + 5 = 64.
24. Convert to Lowercase Method.
Write a Java method that converts a char to lowercase. For example, toLowerCase('A') should return `a’. Make sure you guard against method calls like toLowerCase('a').
25. Shift Encode Method.
Challenge: Write a Java method that shifts a char by n places in the alphabet, wrapping around to the start of the alphabet, if necessary. For example, shift('a',2) should return `c’; shift('y',2) should return `a’. This method can be used to create a Caesar cipher, in which every letter in a message is shifted by n places---hfu ju? (Refer to Chapter~1 exercises for a refresher on Caesar cipher.)
26. Boolean to String Method.
Write a method that converts its boolean parameter to a String. For example, boolToString(true) should return ``true.’’

27. Rectangular Cube Program.

Write a Java application that first prompts the user for three numbers, which represent the sides of a rectangular cube, and then computes and outputs the volume and the surface area of the cube.

28. Sort Three Numbers Program.

Write a Java application that prompts the user for three numbers and then outputs the three numbers in increasing order.

29. Is Divisible Program.

Write a Java application that inputs two integers and then determines whether the first is divisible by the second.
Hint.
Use the modulus operator.

30. Print Table Program.

Write a Java application that prints the following table:
N   SQUARE   CUBE
1   1        1
2   4        8
3   9        27
4   16       64
5   25       125

31. Conversion GUI Program.

Design and write a Java GUI that converts kilometers to miles and vice versa. Use a JTextField for I/O and JButtons for the various conversion actions.

32. Calculate CD GUI Program.

Design and write a GUI that allows a user to calculate the maturity value of a CD. The user should enter the principal, interest rate, and years, and the applet should then display the maturity value. Make use of the BankCD class covered in this chapter. Use separate JTextFields for the user’s inputs and a separate JTextField for the result.

33. Day of Week Birthday GUI Program.

Design and write a GUI that lets the user input a birth date (month and day) and reports what day of the week it falls on. Use the getDayOfWeek() and getDay() methods that you developed in previous exercises.

34. Compute Grades GUI Program.

Design and write a GUI that allows the users to input their exam grades for a course and computes their average and probable letter grade. The applet should contain a single JTextField for inputting a grade and a single JTextField for displaying the average and letter grade. The program should keep track internally of how many grades the student has entered. Each time a new grade is entered, it should display the current average and probable letter grade.

35. Temperature Units Class UML.

One of the reviewers of this text has suggested an alternative design for the Temperature class (Figure 5.7.6). According to this design, the class would contain an instance variable, say, temperature, and access methods that operate on it. The access methods would be:
setFahrenheit(double)
getFahrenheit():double
setCelsius(double)
getCelsius():double
One way to implement this design is to store the temperature in the Kelvin scale and then convert from and to Kelvin in the access methods. The formula for converting Kelvin to Celsius is
K = C + 273.15
Draw a UML class diagram representing this design of the Temperature class. Which design is more object oriented, this one or the one used in Figure 5.7.6?

36. Temperature Units Class Code.

Write an implementation of the Temperature class using the design described in the previous exercise.
You have attempted of activities on this page.