Java OOP Exercises
Java OOP Exercises
Introduction to
Classes and
You will see something new.
Objects
Two things. And I call them
Thing One and Thing Two.
—Dr. Theodor Seuss Geisel
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
2 Chapter 3 Introduction to Classes and Objects
Self-Review Exercises
3.1 Fill in the blanks in each of the following:
a) A house is to a blueprint as a(n) is to a class.
ANS: object.
b) Each class declaration that begins with keyword must be stored in a file that
has exactly the same name as the class and ends with the .java file-name extension.
ANS: public.
c) Every class declaration contains keyword followed immediately by the class’s
name.
ANS: class.
d) Keyword creates an object of the class specified to the right of the keyword.
ANS: new.
e) Each parameter must specify both a(n) and a(n) .
ANS: type, name.
f) By default, classes that are compiled in the same directory are considered to be in the
same package—known as the .
ANS: default package.
g) When each object of a class maintains its own copy of an attribute, the field that repre-
sents the attribute is also known as a(n) .
ANS: instance variable.
h) Java provides two primitive types for storing floating-point numbers in memory—
and .
ANS: float, double.
i) Variables of type double represent floating-point numbers.
ANS: double-precision.
j) Scanner method returns a double value.
ANS: nextDouble.
k) Keyword public is a(n) .
ANS: access modifier.
l) Return type indicates that a method will perform a task but will not return
any information when it completes its task.
ANS: void.
m) Scanner method reads characters until a newline character is encountered,
then returns those characters as a String.
ANS: nextLine.
n) Class String is in package .
ANS: java.lang.
o) A(n) is not required if you always refer to a class with its fully qualified class
name.
ANS: import declaration.
p) A(n) is a number with a decimal point, such as 7.33, 0.0975 or 1000.12345.
ANS: floating-point number.
q) Variables of type float represent floating-point numbers.
ANS: single-precision.
r) The format specifier is used to output values of type float or double.
ANS: %f.
s) Types in Java are divided into two categories— types and types.
ANS: primitive types, reference types.
3.2 State whether each of the following is true or false. If false, explain why.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Self-Review Exercises 3
a) By convention, method names begin with an uppercase first letter and all subsequent
words in the name begin with a capital first letter.
ANS: False. By convention, method names begin with a lowercase first letter and all subse-
quent words in the name begin with a capital first letter.
b) An import declaration is not required when one class in a package uses another in the
same package.
ANS: True.
c) Empty parentheses following a method name in a method declaration indicate that the
method does not require any parameters to perform its task.
ANS: True.
d) Variables or methods declared with access modifier private are accessible only to meth-
ods of the class in which they are declared.
ANS: True.
e) A primitive-type variable can be used to invoke a method.
ANS: False. A primitive-type variable cannot be used to invoke a method—a reference to
an object is required to invoke the object’s methods.
f) Variables declared in the body of a particular method are known as instance variables
and can be used in all methods of the class.
ANS: False. Such variables are called local variables and can be used only in the method in
which they are declared.
g) Every method’s body is delimited by left and right braces ({ and }).
ANS: True.
h) Primitive-type local variables are initialized by default.
ANS: False. Primitive-type instance variables are initialized by default. Each local variable
must explicitly be assigned a value.
i) Reference-type instance variables are initialized by default to the value null.
ANS: True.
j) Any class that contains public static void main( String args[] ) can be used to exe-
cute an application.
ANS: True.
k) The number of arguments in the method call must match the number of parameters in
the method declaration’s parameter list.
ANS: True.
l) Floating-point values that appear in source code are known as floating-point literals and
are type float by default.
ANS: False. Such literals are of type double by default.
3.3 What is the difference between a local variable and a field?
ANS: A local variable is declared in the body of a method and can be used only from the
point at which it is declared through the end of the method declaration. A field is de-
clared in a class, but not in the body of any of the class’s methods. Also, fields are
accessible to all methods of the class. (We will see an exception to this in Chapter 8,
Classes and Objects: A Deeper Look.)
3.4 Explain the purpose of a method parameter. What is the difference between a parameter
and an argument?
ANS: A parameter represents additional information that a method requires to perform its
task. Each parameter required by a method is specified in the method’s declaration.
An argument is the actual value for a method parameter. When a method is called,
the argument values are passed to the method so that it can perform its task.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4 Chapter 3 Introduction to Classes and Objects
Exercises
3.5 What is the purpose of keyword new? Explain what happens when this keyword is used in
an application.
ANS: The purpose of keyword new is to create an object of a class. When keyword new is
used in an application, first a new object of the class to the right of new is created, then
the class’s constructor is called to ensure that the object is initialized properly.
3.6 What is a default constructor? How are an object’s instance variables initialized if a class has
only a default constructor?
ANS: A default constructor is a constructor provided by the compiler when the program-
mer does not specify any constructors in the class. When a class has only the default
constructor, its instance variables are initialized to their default values. Variables of
types char, byte, short, int, long, float and double are initialized to 0, variables of
type boolean are initialized to false, and reference-type variables are initialized to
null.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 5
Use your modified class in a test application that demonstrates the class’s new capabilities.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6 Chapter 3 Introduction to Classes and Objects
3.12 Modify class Account (Fig. 3.13) to provide a method called debit that withdraws money
from an Account. Ensure that the debit amount does not exceed the Account’s balance. If it does,
the balance should be left unchanged and the method should print a message indicating "Debit
amount exceeded account balance." Modify class AccountTest (Fig. 3.14) to test method debit.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 7
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8 Chapter 3 Introduction to Classes and Objects
26 withdrawalAmount );
27 account1.debit( withdrawalAmount ); // subtract amount from account1
28
29 // display balances
30 System.out.printf( "account1 balance: $%.2f\n",
31 account1.getBalance() );
32 System.out.printf( "account2 balance: $%.2f\n\n",
33 account2.getBalance() );
34
35 System.out.print( "Enter withdrawal amount for account2: " );
36 withdrawalAmount = input.nextDouble(); // obtain user input
37 System.out.printf( "\nsubtracting %.2f from account2 balance\n",
38 withdrawalAmount );
39 account2.debit( withdrawalAmount ); // subtract amount from account2
40
41 // display balances
42 System.out.printf( "account1 balance: $%.2f\n",
43 account1.getBalance() );
44 System.out.printf( "account2 balance: $%.2f\n",
45 account2.getBalance() );
46 } // end main
47
48 } // end class AccountTest
3.13 Create a class called Invoice that a hardware store might use to represent an invoice for an
item sold at the store. An Invoice should include four pieces of information as instance variables—
a part number (type String), a part description (type String), a quantity of the item being pur-
chased (type int) and a price per item (double). Your class should have a constructor that initializes
the four instance variables. Provide a set and a get method for each instance variable. In addition,
provide a method named getInvoiceAmount that calculates the invoice amount (i.e., multiplies the
quantity by the price per item), then returns the amount as a double value. If the quantity is not
positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0. Write a
test application named InvoiceTest that demonstrates class Invoice’s capabilities.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 9
3
4 public class Invoice
5 {
6 private String partNumber;
7 private String partDescription;
8 private int quantity;
9 private double pricePerItem;
10
11 // four-argument constructor
12 public Invoice( String part, String description, int count,
13 double price )
14 {
15 partNumber = part;
16 partDescription = description;
17
18 if ( count > 0 ) // determine whether count is positive
19 quantity = count; // valid count assigned to quantity
20
21 if ( price > 0.0 ) // determine whether price is positive
22 pricePerItem = price; // valid price assigned to pricePerItem
23 } // end four-argument Invoice constructor
24
25 // set part number
26 public void setPartNumber( String part )
27 {
28 partNumber = part;
29 } // end method setPartNumber
30
31 // get part number
32 public String getPartNumber()
33 {
34 return partNumber;
35 } // end method getPartNumber
36
37 // set description
38 public void setPartDescription( String description )
39 {
40 partDescription = description;
41 } // end method setPartDescription
42
43 // get description
44 public String getPartDescription()
45 {
46 return partDescription;
47 } // end method getPartDescription
48
49 // set quantity
50 public void setQuantity( int count )
51 {
52 if ( count > 0 ) // determine whether count is positive
53 quantity = count; // valid count assigned to quantity
54
55 if ( count <= 0 ) // determine whether count is zero or negative
56 quantity = 0; // invalid count; quantity set to 0
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10 Chapter 3 Introduction to Classes and Objects
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 11
23 invoice1.setQuantity( 3 );
24 invoice1.setPricePerItem( 19.49 );
25
26 // display invoice1 with new data
27 System.out.println( "\nUpdated invoice information" );
28 System.out.printf( "Part number: %s\n", invoice1.getPartNumber() );
29 System.out.printf( "Description: %s\n",
30 invoice1.getPartDescription() );
31 System.out.printf( "Quantity: %d\n", invoice1.getQuantity() );
32 System.out.printf( "Price: %.2f\n", invoice1.getPricePerItem() );
33 System.out.printf( "Invoice amount: %.2f\n",
34 invoice1.getInvoiceAmount() );
35
36 Invoice invoice2 = new Invoice( "5678", "Paint Brush", -5, -9.99 );
37
38 // display invoice2
39 System.out.println( "\nOriginal invoice information" );
40 System.out.printf( "Part number: %s\n", invoice2.getPartNumber() );
41 System.out.printf( "Description: %s\n",
42 invoice2.getPartDescription() );
43 System.out.printf( "Quantity: %d\n", invoice2.getQuantity() );
44 System.out.printf( "Price: %.2f\n", invoice2.getPricePerItem() );
45 System.out.printf( "Invoice amount: %.2f\n",
46 invoice2.getInvoiceAmount() );
47
48 // change invoice2's data
49 invoice2.setQuantity( 3 );
50 invoice2.setPricePerItem( 9.49 );
51
52 // display invoice2 with new data
53 System.out.println( "\nUpdated invoice information" );
54 System.out.printf( "Part number: %s\n", invoice2.getPartNumber() );
55 System.out.printf( "Description: %s\n",
56 invoice2.getPartDescription() );
57 System.out.printf( "Quantity: %d\n", invoice2.getQuantity() );
58 System.out.printf( "Price: %.2f\n", invoice2.getPricePerItem() );
59 System.out.printf( "Invoice amount: %.2f\n",
60 invoice2.getInvoiceAmount() );
61
62 } // end main
63
64 } // end class InvoiceTest
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12 Chapter 3 Introduction to Classes and Objects
3.14 Create a class called Employee that includes three pieces of information as instance vari-
ables—a first name (type String), a last name (type String) and a monthly salary (double). Your
class should have a constructor that initializes the three instance variables. Provide a set and a get
method for each instance variable. If the monthly salary is not positive, set it to 0.0. Write a test
application named EmployeeTest that demonstrates class Employee’s capabilities. Create two Em-
ployee objects and display each object’s yearly salary. Then give each Employee a 10% raise and dis-
play each Employee’s yearly salary again.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 13
17 monthlySalary = salary;
18 } // end three-argument Employee constructor
19
20 // set Employee's first name
21 public void setFirstName( String first )
22 {
23 firstName = first;
24 } // end method setFirstName
25
26 // get Employee's first name
27 public String getFirstName()
28 {
29 return firstName;
30 } // end method getFirstName
31
32 // set Employee's last name
33 public void setLastName( String last )
34 {
35 lastName = last;
36 } // end method setLastName
37
38 // get Employee's last name
39 public String getLastName()
40 {
41 return lastName;
42 } // end method getLastName
43
44 // set Employee's monthly salary
45 public void setMonthlySalary( double salary )
46 {
47 if ( salary >= 0.0 ) // determine whether salary is positive
48 monthlySalary = salary;
49 } // end method setMonthlySalary
50
51 // get Employee's monthly salary
52 public double getMonthlySalary()
53 {
54 return monthlySalary;
55 } // end method getMonthlySalary
56
57 } // end class Employee
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14 Chapter 3 Introduction to Classes and Objects
3.15 Create a class called Date that includes three pieces of information as instance variables—a
month (type int), a day (type int) and a year (type int). Your class should have a constructor that
initializes the three instance variables and assumes that the values provided are correct. Provide a set
and a get method for each instance variable. Provide a method displayDate that displays the month,
day and year separated by forward slashes (/). Write a test application named DateTest that dem-
onstrates class Date’s capabilities.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 15
14 day = dayValue;
15 year = yearValue;
16 } // end three-argument constructor
17
18 // set the month
19 public void setMonth( int monthValue )
20 {
21 month = monthValue;
22 } // end method setMonth
23
24 // return the month
25 public int getMonth()
26 {
27 return month;
28 } // return month
29
30 // set the day
31 public void setDay( int dayValue )
32 {
33 day = dayValue;
34 } // end method setDay
35
36 // return the day
37 public int getDay()
38 {
39 return day;
40 } // return day
41
42 // set the year
43 public void setYear( int yearValue )
44 {
45 year = yearValue;
46 } // end method setYear
47
48 // return the year
49 public int getYear()
50 {
51 return year;
52 } // return year
53
54 // display the date
55 public void displayDate()
56 {
57 System.out.printf( "%d/%d/%d", getMonth(), getDay(), getYear() );
58 } // end method displayDate
59 } // end class Date
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
16 Chapter 3 Introduction to Classes and Objects
7 {
8 Date date1 = new Date( 7, 4, 2004 );
9
10 System.out.print( "The initial date is: " );
11 date1.displayDate();
12
13 // change date values
14 date1.setMonth( 11 );
15 date1.setDay( 1 );
16 date1.setYear( 2003 );
17
18 System.out.print( "\nDate with new values is: " );
19 date1.displayDate();
20
21 System.out.println(); // output a newline
22 } // end main
23 } // end class DateTest
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
GUI and Graphics Case Study Exercise Solution 17
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.