Exercises


[Page 242 (continued)]

Note

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


Exercise 5.1

Explain the difference between the following pairs of terms:

  1. Representation and action.

  2. Binary operator and unary operation.

  3. Class constant and class variable.

  4. Helper method and class method.

  5. Operator overloading and method overloading.

  6. Method call and method composition.

  7. Type conversion and type promotion.


[Page 243]
Exercise 5.2

For each of the following data types, list how many bits are used in its representation and how many values can be represented:

  1. int

  2. char

  3. byte

  4. long

  5. double

Exercise 5.3

Fill in the blanks.

  1. Methods and variables that are associated with a class rather than with its instances must be declared ______.

  2. When an operation involves values of two different types, one value must be ______ before the expression can be evaluated.

  3. Constants should be declared ______.

  4. Variables that take true and false as their possible values are known as ______.

Exercise 5.4

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

Exercise 5.5

Assuming that o1 is true, o2 is false, and o3 is false, evaluate each of the following expressions:

  1. o1 || o2 && o3

  2. o1 L o2

  3. !o1 && !o2

Exercise 5.6

Arrange the following operators in precedence order:

+ - () * / % < == 


Exercise 5.7

Arrange the following operators into a precedence hierarchy:

*,++, %, == 


Exercise 5.8

Parenthesize and evaluate each of the following expressions (if an expression is invalid, mark it as such):

  1. 11 / 3 % 2 == 1

  2. 11 / 2 % 2 > 0

  3. 15 % 3 >= 21 %

  4. 12.0 / 4.0 >= 12 / 3

  5. 15 / 3 == true


[Page 244]
Exercise 5.9

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; 


  1. m = ++k + j;

  2. m += ++k * j;

  3. m %= ++k + ++j;

  4. m = m - k - j;

  5. m = ++m;

Exercise 5.10

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; 


  1. b = m > k + j;

  2. b = m * m != m * j;

  3. b = m <= 5 && m % 2 == 1;

  4. b = m < k || k < j;

  5. b = --m == 2 * ++j;

Exercise 5.11

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; 


  1. c = c + 5;

  2. c = 'A' + 'B';

  3. m = c + 5;

  4. c = (char) m + 1;

  5. m = 'a' - 32;

Exercise 5.12

Translate each of the following expressions into Java:

  1. Area equals pi times the radius squared.

  2. Area is assigned pi times the radius squared.

  3. Volume is assigned pi times radius cubed divided by h.

  4. If m and n are equal, then m is incremented by one; otherwise n is incremented.

  5. If m is greater than n times 5, then square m and double n; otherwise square n and double m.


[Page 245]
Exercise 5.13

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); 


Each of the problems that follow asks you to write a method. Test the method as you develop it in a stepwise fashion. 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));     } } 


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.

Exercise 5.14

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.

Exercise 5.15

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.)

Exercise 5.16

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.)

Exercise 5.17

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').


[Page 246]
Exercise 5.18

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 placeshfuju? (Refer to the Chapter 1 exercises for a refresher on Caesar cipher.)

Exercise 5.19

Write a method that converts its boolean parameter to a String. For example, boolToString(true) should return "true".

Exercise 5.20

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

Exercise 5.21

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

Exercise 5.22

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

Exercise 5.23

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 


Exercise 5.24

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.

Exercise 5.25

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.

Exercise 5.26

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.

Exercise 5.27

Design and write a GUI that allows users to input their exam grades for a course and computes their averages and probable letter grades. 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 each student has entered. Whenever a new grade is entered, it should display the current average and probable letter grade.


[Page 247]
Exercise 5.28

One of the reviewers of this text has suggested an alternative design for the Temperature class (Fig. 5.5). 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), and 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.5?

Exercise 5.29

Write an implementation of the Temperature class using the design described in the preceding exercise.




Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net