Solutions Manual To Objects First With Java A Practical in

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Solutions manual to Objects First with Java – A practical Introduction using BlueJ

By-Afzaal Ahmad Zeeshan

1
Index
Table of Contents

Preface..................................................................................................................................................2
Chapter 1: Objects and classes..........................................................................................................3-4

 Solution to Exercises based on chapter....................................................................................5-10

Chapter 2: Understanding class definitions ..................................................................................11

 Solution to Exercises based on chapter..................................................................................12-32

Final words.........................................................................................................................................33

2
Preface
Object-oriented programming is a major subject in every computer science degree that trains the
students to write good application software based on object-oriented programming pattern. There is
not any problem with using either language to teach the concept, or to use which-so-ever programming
language guidance book. The main concern should always be with the concepts and understanding that
a book can provide to the students. Most of the times, the content of a book is well suited for one
environment when in another environment it never matters at all. Similarly, we are being taught Object-
oriented programming using a book, “Objects First with Java”. The book is a good source for students
who want to get a good grasp of Java programming language and simple software development
techniques with “this uses that” basis.

I understand the book is just “too much” and for a student, who has to study other 5+ subjects. Reading
a book of 100+ pages is really very tough task. That is why, this solution will also provide a straight-
forward understanding and explanation of the concepts being taught in the chapters.

The book has some complex exercises and requires some time to be understood. I have solved those
exercises and thus I am writing a solution manual for those who didn’t understand the questions and
exercises. I hope, while writing, that this solution manual would clarify the ambiguity in minds of my
fellow students and to those who get this solution for their study purposes.

In this book, you will be given an overview of the chapter, a little explanation for the concepts that are
being taught, IDE being used and then later you will be given answers to the questions that are
presented in the exercise for the students to try them out. But, I recommend that you not only copy the
content, instead you should think about the questions and you should try to solve them. If they are
tough, get help from this book and later try them yourself.

Finally, if you still don’t get the points, my personal recommendation is that you share your problem
with your instructor and ask them to explain the concepts to you again. For more understanding about
Object-oriented programming, you may also get my free eBook for theoretical object-oriented
programming from C# Corner publications.

If you found any error, or for any other contact purposes, you may contact me at my personal email
account: justin17862@gmail.com. Keep it straight-forward.

Thank you,

Afzaal Ahmad Zeeshan

3
Chapter 1: Objects and classes
This is the first chapter in the book and gets the students started with the initial topics, concepts that
are going to be used in the book onwards. In this chapter, the major topics that are covered are:

1. Objects
2. Classes
3. Methods
4. Parameters

Before we dig deeper, I want you to have a little understanding of these subjects. If you already know
what they are, you can skip this to the exercise below. If you need some understanding and instruction,
please read the sections below as they describe these terminologies in short forms.

Objects and classes


Objects and classes can be interchanged with each other, the common difference between them is that
one exists in source code and other exists in RAM; executable (or executing) program. Now that we have
laid down the foundation for the objects and classes, it is easy to continue from here to understand that
class is just the structure for the object in RAM. For example, the following code:
/**
* A sample class for teaching purposes.
*
* @author Afzaal Ahmad Zeeshan
* @version 1.0
*/
public class Program
{
// Create fields here.
private int field;

/**
* Constructor for objects of class Program
*/
public Program()
{
// Object creating logic
}

public void Func() {


// Code to perform here...
}
}

The above class is just the structure for the way our object would be in the RAM. In the RAM, there
would be a memory address where a field would be stored and then the procedures (function, methods,
and behaviors) would be stored to be called. Definitely, programmers would update these commands
and structures to get their programs working. However, once compiled, they are the “objects” in the
memory. So, we can conclude:

4
“Classes are the structures defined in a source code that guide the object definition in the RAM.”

Methods and parameters


In the previous code, recall that we had a method called, “Func()”. These are special blocks of code that
are called “as required”. Unlike sequential programming, function calls are used extensively in object-
oriented programming to allow programmers to follow the “Don’t repeat yourself” pattern of
programming.

Keeping it simple, parameters are values that are used to control how the code in the method executes.
There is no limit or requirement of parameters in Java. You can include parameters, or exclude them
from the code as you require them to.
public void functionName (DataType paramName, DataType2 paramName2) {
// Code here...
}

We can then use the parameters in the methods to control how the code executes. That is not it,
parameters once asked, are required to be passed when we have to call the functions.

We conclude:

“Methods are code statements that are executed as required, and parameters are conditions that control
the way code statements are executed.”

You can then consider them as required if wanted, and ignored if code has no limitations.

5
Solution to Exercises
This solution manual is for theoretical questions, or the questions that can (or are to) be solved using
theoretical understanding of the object-oriented programming concepts. The questions that require
practical procedures, practical performance are skipped out of this book. Where required, their
explanation would be provided for guidance.

1.1 Create another circle. Then create a square. (And the rest of “create a new object” type
questions)
In BlueJ, to create a new object you can use the “new Object” function.

1. Right click the class in the class diagram.


2. Select “new Class”
3. (Optional) Pass any parameters required.

Your “new object for that class” would be generated and can be found in the bottom tray.

1.2 What happens if you call moveDown twice? Or three times? What happens if you call
makeInvisible twice?
By definition of these functions, moveDown function has a field mutation for every call. Thus, if you
trigger moveDown function twice, it would move the object twice. Because it updates the location in X
and Y axes. Similarly, when triggering it third time, it would move 1 point down in Y axis.

On the other hand, makeInvisible doesn’t rely on the field because Boolean data type can only store one
value in either direction and one value in other. So if you continue to update the value in one direction,
say positive, it would always have a value of either 1 or zero. That is why, the object is not altered in its
visibility and it always invisible.

1.3 Try invoking the moveVertical, slowMoveVertical, and changeSize methods before you read
on. Find out how you can use moveHorizontal to move the circle 70 pixels to the left.
As their names state, they will move the objects vertically or horizontally. The function with “slow” in its
name is used to animate the object movement. So if you want to move the objects slowly, you would be
using these functions.

Change Size function is used to change the size of the item. This function has different parameters list in
different objects. That is why, a circle would just ask for radius whereas triangle would ask for height
and width.

To move a circle 70 pixel to the left, we would use the following code, on the instance named “sun”:
sun.moveHorizontal(-70);

The negative value would move it in negative axis.

1.4 Invoke the changeColor method on one of your circle objects and enter the string "red". This
should change the color of the circle. Try other colors.
I leave the “red” up to you.

6
Read that the function requires a parameter of type String. The value of String type are all wrapped
around using double quotes, “”. In this case, I have passed “yellow” which would change the color for
this graphics object to yellow.

1.5 This is a very simple example, and not many colors are supported. See what happens when
you specify a color that is not known.
Suppose we use a color that is not listed in the “valid colors”. Just for test, we use “purple”. The result is
it updates the color to black. This behavior is specified in the following code of Canvas class:
public void setForegroundColor(String colorString)
{
if(colorString.equals("red")) {
graphic.setColor(new Color(235, 25, 25));
}
else if(colorString.equals("black")) {
graphic.setColor(Color.black);
}
else if(colorString.equals("blue")) {
graphic.setColor(new Color(30, 75, 220));
}
else if(colorString.equals("yellow")) {
graphic.setColor(new Color(255, 230, 0));
}
else if(colorString.equals("green")) {
graphic.setColor(new Color(80, 160, 60));
}
else if(colorString.equals("magenta")) {
graphic.setColor(Color.magenta);
}
else if(colorString.equals("white")) {
graphic.setColor(Color.white);
}
else {
graphic.setColor(Color.black);
}
}

7
Thus, the graphical object which is set with an invalid color would have black color.

1.6 Invoke the changeColor method, and write the color into the parameter field without the
quotes. What happens?
As already mentioned, the error would be generated. The problem is that String values are required to
be in quotes. Otherwise, they are considered to be variables or object instances.

1.10 Select Show Terminal from the View menu. This shows another window that BlueJ uses for
text output. Then select Record method calls from the terminal’s Options menu. This function
will cause all our method calls (in their textual form) to be written to the terminal. Now create a
few objects, call some of their methods, and observe the output in the terminal window.
Just remember, before you do. Make sure you have checked, “Record Method Calls” option. Each
method would be logged there so that you can see which methods were called.

1.11 Select Show Code Pad from the View menu. This should display a new pane next to the
object bench in your main BlueJ window. This pane is the Code Pad. You can type Java code here.
Instead of executing the code by right-clicking, try to type in the instance name and function name in
this section. Practically use it.

1.14 How do you think the Picture class draws the picture?
There is a special function called “draw” in the class definition. This function is called when the picture is
to be drawn on the canvas object. The code is written that draws the graphical objects on the canvas.

The technical part comes when the function of “makeVisible” is called. That is when objects are
rendered on the canvas item. Picture object itself doesn’t communicate with the canvas object, instead
it forces the items to render themselves by calling their functions.

1.16 In the source code of class Picture, find the part that actually draws the picture. Change it
so that the sun will be blue rather than yellow.
As previously mentioned, the function that draws the items is “draw”. Change the code for the sun
object,
sun = new Circle();
sun.changeColor("blue");
sun.moveHorizontal(100);
sun.moveVertical(-40);
sun.changeSize(80);
sun.makeVisible();

This would now render the sun as blue.

1.18 Add a sunset to the single-sun version of Picture. That is, make the sun go down slowly.
The following code for the sun object, named sun1, would make it render as setting down slowly instead
of moving to another location rapidly.
sun1 = new Circle();
sun1.changeColor("red");
sun1.moveHorizontal(50);
sun1.moveVertical(-40);

8
sun1.changeSize(80);
sun1.makeVisible();
sun1.slowMoveVertical(-50);

You should compile the code again and see that it works.

1.19 We now want the sunset in a separate method, so that we can call draw and see the picture
with the sun up, and then call sunset (a separate method!) to make the sun go down.
We can change the way our both functions are designed, we first of all, create a new function called,
sunset and write the following code in it:
public void sunset() {
sun1.slowMoveVertical(-50);
}

// In the draw function


sun1 = new Circle();
sun1.changeColor("red");
sun1.moveHorizontal(50);
sun1.moveVertical(-40);
sun1.changeSize(80);
sun1.makeVisible();

// Call the sunset function


sunset();

Now you can continue to write other stuff.

1.20 Make a person walk up to the house after the sunset.


We can now use the function to move an object item horizontally. The code is similar to what we had
above. The only difference is that we need to move the object horizontally, instead of vertically.
person.slowMoveHorizontal(-100); // Assume -100 is required.

This would make the person move 100 pixel in negative X axis, slowly.

1.21 Create an object of class Student. You will notice that this time you are prompted not only
for a name of the instance, but also for some other parameters. Fill them in before clicking OK.
If you see an error, make sure that your data is wrapped in quotes to make it String data and not a
variable call.

1.22 Create some student objects. Call the getName method on each object. Explain what is
happening.
It returns the name of the student in an inspector for the method result.

1.24 Call the numberOfStudents method of that class. What does it do?
Same as what getName did. It returns the number of students we wanted in the class.

9
1.27 Create three students with the following details:
Snow White, student ID: A00234, credits: 24
Lisa Simpson, student ID: C22044, credits: 56
Charlie Brown, student ID: A12003, credits: 6
Then enter all three into a lab and print a list to the screen.
To create these students, you will use the same constructors but pass different values. Once they are
created, you will use the “addCredits” function and pass the value for these credits for each of the
student object.

For demonstration, create a new Student and pass the values for the first student, “Snow White”.

After this, you should execute the method, “addCredits” and pass the value 24 (in integer!) to it. Then
execute the function, “void print()” in the context menu. You will see the following window.

Repeat the steps to add other three students to the list.

1.29 Set the instructor, room, and time for a lab, and print the list to the terminal window to
check that these new details appear.
We are provided with these functions too. Update the fields using the functions provided. After that,
use the same function to print the values on the screen.

1.31 What are the types of the following values?


1. Integer
2. String

10
3. Integer
4. Integer
5. Boolean
6. String
7. Double

1.32 What would you have to do to add a new field, for example one called name, to a circle
object?
To add a new field, you will have to update the code. Typically, the field of “name” would have the type
of String. So the field would look something like this:
private String name;

This would add a new field to the class (in which it was created).

1.33 Write the signature for a method named send that has one parameter of type String, and
does not return a value.
public void send (String message) { }

1.34 Write the signature for a method named average that has two parameters, both of type int,
and returns an int value.
public int average(int a, int b) { }

1.35 Look at the book you are reading right now. Is it an object or a class? If it is a class, name
some objects. If it is an object, name its class.
It is an object of class called, “Book”.

1.36 Can an object have several different classes? Discuss.


No, an object is an instance of a class. In Java, an object can at once be related to just one class. In
advanced Java, there is a common concept of “Inheritance”, in which, an object may have multiple
parent types. But still an object would just be an instance of a single class.

11
Chapter 2: Understanding class definitions
In chapter 1, the foundation was laid down. In this chapter the concepts are broadened and a lot of new
items are added including return types, parameters, accessor, mutator, compound assignment
statements etc. All of these are actually the basics about programming, yet they have been a bit
modified in the realm of Java programming language. Basically, what this chapter covers is:

1. Fields
2. Methods
a. Accessors
b. Mutators
3. Constructors
4. Assignment and conditional statements
5. Parameters

The topic also covers a few of the concepts about constructors, fields and random stuff in Java
programming; which has nothing to do with Object-oriented programming, e.g. conditional statement.
However, the concepts of accessors, mutators, parameter types are much of interest for students. In
this part, I will explain those facts clearly so that in questions you no longer have any trouble learning
from them.

Before we dig any deeper, let me clarify a few of these points.

Fields and methods


An object is defined is, “everything that has a property and can perform some function is called an
object”. In Java, properties are called fields and functions are called methods or behaviors. Anything that
can differentiate two objects are their fields and every object has similar behaviors, methods. These
methods can have different actions on environments based on their fields.

Accessors and mutators


Methods are then further divided in sections. Accessors and mutators, if you have ever programmed in
C++, C# or other similar languages. You would know that there are few functions involved, called,
getters and setters. These are used to either “get the value”, or “set the value”.

Accessors are the functions that are used to get the values from the objects. Like their names. Accessors
typically have the same return type as the returning field and only return the field.

Mutators are used to update the values, mutate the values, like to update their names. Mutators have a
return type of void and perform an action to update the field. Mutators may also request a parameter
for the value to be set.

For the rest of the items, I would recommend that you get the Object-oriented programming guide that I
have already talked about. I have explained the remaining as well as these previously talked concepts, in
details with differences in tabular form.

12
Solution to Exercises
Just like previous chapter, you will be provided with theoretical answers, and practical parts would be
given tips for so that you can easily perform them on your own devices and machines. The purpose of
this book is not to help you with homework, but to get you started to solve the problems easily.

2.2 What value is returned if you get the machine’s balance after it has printed a ticket?
In the code, there is a line at the end of the function for printing the ticket, which clears the balance.
That line would remove every possible cent available in the balance and that is why, when you will get
the balance it will be zero.

2.3 Experiment with inserting different amounts of money before printing tickets. Do you notice
anything strange about the machine’s behavior? What happens if you insert too much money
into the machine – do you receive any refund? What happens if you do not insert enough and
then try to print a ticket?
In the current code solution, the machine doesn’t actually provide any refund and also doesn’t actually
check if the money is enough before printing the ticket.

The solution to this problem (error) is provided in the later sections in the book. Continue to the further
parts, and you will see the code that solves these problems with the ticket machine.

2.5 Create another ticket machine for tickets of a different price; remember that you have to
supply this value when you create the machine object. Buy a ticket from that machine. Does the
printed ticket look any different from those printed by the first machine?
Because the machines were constructed with different values, the machines would have different
behavior in generating the ticket. This can be seen in the printed ticket, the price would be different.

The differences can also be seen when inspecting the object using the inspector.

2.6 Write out what you think the outer wrappers of the Student and LabClass classes might look
like; do not worry about the inner part.
The outer wrappers of a class are the syntax for writing the declaration of the class. In the above cases,
the declaration or wrappers would be like this:
public class LabClass { }

public class Student { }

These are the wrappers, without any inner implementation, constructors and fields.

2.7 Does it matter whether we write public class TicketMachine or class public TicketMachine?
Java is a case-sensitive and compiled language. That is why the names, keywords, case and the order in
which they occur matters a lot in Java. If they are incompatible, then there is an error in compilation
process.

The order of class wrapper is always,

1. Access level; public or private, private for inner classes.


2. Keyword for class
3. Name of the class; must be same as the file.

13
If the order is not met, there is an error in compilation. I recommend that you tinker with this in the IDE
itself to understand a little more about the order of the commands and language syntax.

On the other hand, if you remove out the public keyword from the declaration there will be no error in
the code. That is because, Java will itself create the class to be public because it is the outer class (or the
default class) in that Java source file. But the order of class and the name of the class are always
required and in the same order.

2.9 Put back the word public, and then check whether it is possible to leave out the word class by
trying to compile again. Make sure that both words are put back as they were originally before
continuing.
No, class keyword is required because Java can edit the access level of the objects, classes and functions.
But Java will never guess the type of the objects being created. A class required the keyword class, so
does an interface require a keyword of interface.

If you try to compile without having the class keyword in it, you will get an error. Once you put the class
keyword back, your code will compile successfully.

2.11 What are the two features of the constructor that make it look significantly different from
the methods of the class?
By definition, a constructor is a function that is executed when an object is being created. It is defined
as:
public ClassName () {
// Inner logic
}
This can be used to write down the differences,

1. Constructors don’t have a return type.


2. They have similar name as the class has.
3. They start with a capital letter. Whereas, by convention, in Java, functions have a smaller first
letter.

2.12 What do you think is the type of each of the following fields?
1. int
2. Student
3. Server

2.13 What are the names of the following fields?


1. alive
2. tutor
3. game

2.14 From what you know about the naming conventions for classes, which of the type names in
Exercises 2.12 and 2.13 would you say are class names?
The common different to note in both the names is that class names start with a capital letter, whereas
the variables and identifiers for methods start with the first letter small.

14
2.15 In the following field declaration from the TicketMachine class private int price; does it
matter which order the three words appear in?
Yes, as we have already mentioned that Java is compiled language and the structure of the program
matters a lot. If you tinker with the location of these three keywords, then your compilation would fail.
The declaration must always be in this form.

1. Access level
2. Data type
3. Name

2.16 Is it always necessary to have a semicolon at the end of a field declaration?


Yes, Java inherits this common thing from C and C++. Semicolon is called a statement terminator and is
used to create a new command when Java is being compiled down to bytecode.

2.17 Write in full the declaration for a field of type int whose name is status.
private int status;

2.18 To what class does the following constructor belong?


public Student(String name)
The constructor has a property, that its name is same as the class. That is why, this belongs to the class
Student.

2.19 How many parameters does the following constructor have, and what are their types?
public Book(String title, double price)
It has 2 parameters of type String and double.

2.20 Can you guess what types some of the Book class’s fields might be, from the parameters in
its constructor? Can you assume anything about the names of its fields?
Although Java enforces encapsulation, but we can “assume” and guess the names of the fields when we
are working with the objects. But their types are same; the ones used in the constructor itself.

2.21 Suppose that the class Pet has a field called name that is of type String. Write an assignment
statement in the body of the following constructor so that the name field will be initialized with
the value of the constructor’s parameter.
public Pet(String petsName) {
name = petsName
}
2.22 The following object creation will result in the constructor of the Date class being called.
Can you write the constructor’s header?
new Date("March", 23, 1861)
The constructor belongs to Date class. We can define the constructor as:
public Date(String month, int date, int year) { }

2.23 Compare the header and body of the getBalance method with the header and body of the
getPrice method. What are the differences between them?
There is no difference in them. Because there signature and the return statement is similar. The
difference in returning value is not counted.

15
2.24 If a call to getPrice can be characterized as “What do tickets cost?” how would you
characterize a call to getBalance?
“What is the remaining balance in the machine?”

2.25 If the name of getBalance is changed to getAmount, does the return statement in the body
of the method also need to be changed for the code to compile?
No, because the names of the functions and the insider statements have no relation using the identifier
that we use.

2.26 Write an accessor method getTotal in the TicketMachine class. The new method should return the
value of the total field.
public int getTotal() {
return total;
}

2.27 Try removing the return statement from the body of getPrice. What error message do you
see now when you try compiling the class?
It would say, not all code paths return a value and the error message would be, “missing return
statement”. That is because the method with a return type other than void, must return a value.

2.28 Compare the method headers of getPrice and printTicket in Code 2.1. Apart from their
names, what is the main difference between them?
The signatures are different. getPrice has a return type of integer, whereas printTicket is of void return.

2.29 Do the insertMoney and printTicket methods have return statements? Why do you think
this might be? Do you notice anything about their headers that might suggest why they do not
require return statements?
They do not have, and they do not require any because their return type is set to void.

2.30 Create a ticket machine with a ticket price of your choosing. Before doing anything else, call
the getBalance method on it. Now call the insertMoney method (Code 2.6) and give a non-zero
positive amount of money as the actual parameter. Now call getBalance again. The two calls to
getBalance should show different outputs, because the call to insertMoney had the effect of
changing the machine’s state via its balance field.
That is because the function insertMoney is used to update the balance currently in the machine.
Initially the machine has zero balance but later it gets an increment in the balance equal to the amount
passed as parameter.

2.31 How can we tell from just its header that setPrice is a method and not a constructor?
public void setPrice(int cost)
Because it has a return type.

2.32 Complete the body of the setPrice method so that it assigns the value of its parameter to
the price field.

public void setPrice(int cost) {

16
price = cost;
}

2.33 Complete the body of the following method, whose purpose is to add the value of its
parameter to a field named score.
public void increase(int points) {
score += points;
}

2.34 Is the increase method a mutator? If so, how could you demonstrate this?
Yes, the function increase is a mutator because it mutates the field score by updating its value.

2.35 Complete the following method, whose purpose is to subtract the value of its parameter
from a field named price.

public void discount(int amount) {


price -= amount;
}

2.36 Write down exactly what will be printed by the following statement:
My cat has green eyes.

2.37 Add a method called prompt to the TicketMachine class. This should have a void return type
and take no parameters. The body of the method should print the following single line of output:
Please insert the correct amount of money.
public void prompt() {
System.out.println(“Please insert the correct amount of money.”);
}
2.38 What do you think would be printed if you altered the fourth statement of printTicket so
that price also has quotes around it, as follows?
# price cents

2.39 What about the following version?


# price cents

2.40 Could either of the previous two versions be used to show the price of tickets in different
ticket machines? Explain your answer.
No, because the price must be printed as a variable in the string. The previous versions of code had
quoted price and not as a variable symbol. That is why, previous both codes cannot be used for printing
the ticket.

2.41 Add a showPrice method to the TicketMachine class. This should have a void return type
and take no parameters. The body of the method should print: The price of a ticket is xyz cents.
public void showPrice() {

17
System.out.println(“The price of a ticket is ” + price + “ cents.”);
}
2.42 Create two ticket machines with differently priced tickets. Do calls to their showPrice
methods show the same output, or different? How do you explain this effect?
Yes, because the initial pricing for a ticket was different. That is why when the methods would be called
they will have different values for the machine.

2.43 Modify the constructor of TicketMachine so that it no longer has a parameter. Instead, the
price of tickets should be fixed at 1,000 cents. What effect does this have when you construct
ticket-machine objects within BlueJ?
public TicketMachine() {
price = 1000;
balance = 0;
total = 0;
}
The difference that machines would now have is that all of the machines would all have a fixed price for
1000 cents. The BlueJ editor will no longer ask for a value to be passed when a new object will be
created.

2.45 Implement a method, empty, that simulates the effect of removing all money from the
machine. This method should have a void return type, and its body should simply set the total
field to zero. Does this method need to take any parameters? Test your method by creating a
machine, inserting some money, printing some tickets, checking the total, and then emptying
the machine. Is the empty method a mutator or an accessor?
public void empty() {
title = 0;
}
The behavior would be that whenever the function would be called it would clear the value of the
money in the machine. The method is a mutator because it changes the value of a field in the object.

2.46 Check that the behavior we have discussed here is accurate by creating a TicketMachine
instance and calling insertMoney with various actual parameter values. Check the balance both
before and after calling insertMoney. Does the balance ever change in the cases when an error
message is printed? Try to predict what will happen if you enter the value zero as the parameter,
and then see if you are right.
In the cases when there is an error, the control does not modify the fields of the objects. The value of
zero will not be accepted because of the condition that works only if the amount passed is more than
zero.

2.47 Predict what you think will happen if you change the test in insertMoney to use the greater-
than or equal-to operator: if(amount >= 0) Check your predictions by running some tests. What
difference does it make to the behavior of the method?
The condition would be true even if the balance is to be added with a value of zero. The code will have a
successful execution to add zero to the value. Which is not a practical way of adding money to the
balance.

18
2.48 Rewrite the if-else statement so that the error message is printed if the boolean expression
is true but the balance is increased if the expression is false. You will obviously have to rewrite
the condition to make things happen this way around.
if(amount < 1) {
System.out.println(“Use a positive amount.”);
} else {
balance += amount;
}

This would now add the value if the condition is false. Otherwise, it would render the error message.

2.49 In the figures project we looked at in Chapter 1 we used a boolean field to control a feature
of the circle objects. What was that feature? Was it well suited to being controlled by a type with
only two different values?
We used that field to control the visibility of the objects. Of course that was well suited because an
object is either visible or is not visible. Thus there is no reason to have extra values and possibilities for
an object’s visibility.

2.50 In this version of printTicket, we also do something slightly different with the total and
balance fields. Compare the implementation of the method in Code 2.1 with that in Code 2.8 to
see whether you can tell what those differences are. Then check your understanding by
experimenting within BlueJ.
The major difference is that the code now checks the balance of the user. If there is enough balance

then the ticket is printed. Otherwise, an error message is shown. Also, in the terminating lines the

balance is not zeroed out instead it is set to any refundable amount that is available.

2.51 Is it possible to remove the else part of the if statement in the printTicket method (i.e.,
remove the word else and the block attached to it)? Try doing this and seeing if the code still
compiles. What happens now if you try to print a ticket without inserting any money?
The code compiles because there is no error in the syntax of the Java source code. The logical error
arises because it will do nothing and your users won’t know what is going wrong.

2.52 After a ticket has been printed, could the value in the balance field ever be set to a negative
value by subtracting price from it? Justify your answer.
No, because the ticket would only be printed if the balance is at least equal to the price or more than
that. Otherwise, if the balance is less, the ticket is not printed at all.

2.54 Write an assignment statement that will store the result of multiplying two variables, price
and discount, into a third variable, saving.
int saving = price * discount;

2.55 Write an assignment statement that will divide the value in total by the value in count and
store the result in mean.
double mean = total / count;

19
2.56 Write an if statement that will compare the value in price against the value in budget. If
price is greater than budget, then print the message “Too expensive”; otherwise print the
message “Just right”.
if(price > budget) {
System.out.println(“Too expensive.”);
} else {
System.out.println(“Just right.”);
}
2.57 Modify your answer to the previous exercise so that the message includes the value of your
budget if the price is too high.
if(price > budget) {
System.out.println(“Too expensive, budget is ” + budget);
} else {
System.out.println(“Just right.”);
}
2.58 Why does the following version of refundBalance not give the same results as the original?
public int refundBalance() { balance = 0; return balance; }
What tests can you run to demonstrate that it does not?
Because no matter what the value balance has, it is always cleared out. That is why it will not give same
results as they are expected.

2.59 What happens if you try to compile the TicketMachine class with the following version of
refundBalance?
public int refundBalance() { return balance; balance = 0; }
What do you know about return statements that helps to explain why this version does not
compile?
There would be an error in compilation. Compiler would give an error message of, “unreachable code
statement”.

The return statement is used to return the control to the calling body, from where the function was
called. That is why when a return statement is called, the next statements in the code are never
executed. Java compiler is notifying the programmer about this behavior of the program and is forcing
them to fix it.

2.60 What is wrong with the following version of the constructor of TicketMachine?
public TicketMachine(int cost) {
int price = cost;
balance = 0;
total = 0;
}
This is a bit tricky part in the code. The code seems similar to what we had in the previous sections, even
in the complex ticket machine code.

The problem is that if you see more clearly, you will find that the cost is not being inserted in the price
field, instead there is a new local variable being created called price. In Java, a new variable can be
added to a scope of function which would override the underlying field of the object.

20
The behavior would be that now the underlying field will not be updated. Instead the value will be
copied in the price variable, which will be deleted from the memory as soon as the constructor scope is
finished.

2.61 Add a new method, emptyMachine, that is designed to simulate emptying the machine of
money. It should reset total to be zero but also return the value that was stored in total before it
was reset.
public int emptyMachine() {
int temp = total;
total = 0;
return temp;
}
2.62 Rewrite the printTicket method so that it declares a local variable, amountLeftToPay. This
should then be initialized to contain the difference between price and balance. Rewrite the test
in the conditional statement to check the value of amountLeftToPay. If its value is less than or
equal to zero, a ticket should be printed; otherwise, an error message should be printed stating
the amount left to pay. Test your version to ensure that it behaves in exactly the same way as
the original version. Make sure that you call the method more than once, when the machine is in
different states, so that both parts of the conditional statement will be executed on separate
occasions.
public void printTicket() {
int amountLeftToPay = price – balance;
if (amountLeftToPay <= 0) {
// Simulate the printing of a ticket.
System.out.println("##################");
System.out.println("# The BlueJ Line");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("##################");
System.out.println();
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance – price;
} else {
System.out.println("You must insert at least: " + (price – balance) + " cents.");
}
}

Try this code out in the BlueJ IDE to see the behavior in real.

21
2.63 Suppose we wished a single TicketMachine object to be able to issue tickets of different
prices. For instance, users might press a button on the physical machine to select a discounted
ticket price. What further methods and/or fields would need to be added to TicketMachine to
allow this kind of functionality? Do you think that many of the existing methods would need to
be changed as well?
Yes, the current functions would need to be updated, starting with the constructor itself. Currently the
constructor asks for a price, then we will remove that parameter and initialize the ticket without a
predefined price.
public TicketMachine() {

price = 0;

total = 0;

balance = 0;

Then we may want to create a function that would store the type and price of the ticket to be printed.
One way of doing this is to pass the price as a parameter to the function.

We would require to add a new field to store the cumulative price with the discount in it.

2.64 List the name and return type of this method:


Name of the function: getCode

Return type of the function: String

2.65 List the name of this method and the name and type of its parameter:
Name of this function: setCredits

Type of the parameter: Int

Name of the parameter: creditValue

2.66 Write out the outer wrapping of a class called Person. Remember to include the curly
brackets that mark the start and end of the class body, but otherwise leave the body empty.
public class Person { }

2.67 Write out definitions for the following fields:


1. private String name;
2. private int age;
3. private String code;
4. private int credits;

2.68 Write out a constructor for a class called Module. The constructor should take a single
parameter of type String called moduleCode. The body of the constructor should assign the
value of its parameter to a field called code. You don’t have to include the definition for code,
just the text of the constructor.
public Module(String moduleCode) {

code = moduleCode;

22
}

2.69 Write out a constructor for a class called Person. The constructor should take two
parameters. The first is of type String and is called myName. The second is of type int and is
called myAge. The first parameter should be used to set the value of a field called name, and the
second should set a field called age. You don’t have to include the definitions for the fields, just
the text of the constructor.
public Person(String myName, int myAge) {

name = myName;

age = myAge;

2.70 Correct the error in this method:


The error is with the return type of the function and the return statement in the function. We would
either change the function signature to
public int getAge() {

return age;

Or otherwise we need to remove the return statement.

2.71 Write an accessor method called getName that returns the value of a field called name,
whose type is String.
public String getName () {

return name;

2.72 Write a mutator method called setAge that takes a single parameter of type int and sets the
value of a field called age.
public void setAge(int a) {

age = a;

2.73 Write a method called printDetails for a class that has a field of type String called name. The
printDetails method should print out a string of the form “The name of this person is”, followed
by the value of the name field. For instance, if the value of the name field is “Helen”, then
printDetails would print: The name of this person is Helen
public void printDetails() {

System.out.println(“The name of this person is ” + name);

23
2.74 Draw a picture of the form shown in Figure 2.3, representing the initial state of a Student
object following its construction, with the following actual parameter values:
new Student("Benjamin Jonson", "738321")
Use the inspector to render the form. You can then draw that image yourself.

2.75 What would be returned by getLoginName for a student with name "Henry Moore" and id
"557214"?
It would get the value of Henry Moore from index 0 to 4, and then the ID value too, appended. Output
will be: “Henr557”.

2.76 Create a Student with name "djb" and id "859012". What happens when getLoginName is
called on this student? Why do you think this is?
The name is only 3 characters long, which means Java can only navigate to 2nd index. But the code asks
for 3rd and 4th index too. Thus, an error will be shown; the error name is clear, that the index was out of
bounds.

2.77 Add conditional statements to the constructor of Student to print an error message if either
the length of the fullName parameter is less than four characters or the length of the studentId
parameter is less than three characters. However, the constructor should still use those
parameters to set the name and id fields, even if the error message is printed.
public Student(String fullName, String studentID) {

if(fullName.length() < 4 || studentID.length() < 3) {

System.out.println(“Full name of the ID of the student is invalid.”);

name = fullName;

id = studentID;

credits = 0;

This would print the error message, but it would still use them as the values.

2.78 Modify the getLoginName method of Student so that it always generates a login name,
even if either the name or the id field is not strictly long enough. For strings shorter than the
required length, use the whole string.
public String getLoginName() {

if(name.length() > 4 & id.length() > 3) {

return name.substring(0,4) + id.substring(0,3);

} else {

return name + id;

24
This function would determine if the lengths of the strings is enough, otherwise it would return the full
name and the ID of the student object.

2.79 Consider the following expressions. Try to predict their results, and then type them in the
Code Pad to check your answers.
1. 102
2. “catfish”
3. “cat9” (with cast)
4. “12cat” (with cast)
5. “cat39” (with cast)
6. “f”
7. Error, 8 is not a valid index.

2.81 Use the following code, TicketMachine t2 = t1; What would be result of t2.getBalance();
As we have already mentioned, the objects are “pass by reference”. So when there is an assignment
operation of two objects. The result is not a value passing, instead the references are passed.

Thus, when you will execute that function, the balance from that RAM address would be returned,
which would be of the t1 object. But since we had the reference combined, the results are similar to
calling the function from either of the objects.

2.82 Add the following:


t1.insertMoney(500);
What would you expect the following to return? Think carefully about this before you try it, and
be sure to use the t2 variable this time. t2.getBalance() Did you get the answer you expected?
Can you find a connection between the variables t1 and t2 that would explain what is
happening?
Just as we previously said, both objects are interconnected with each other using the RAM address. That
is why, an update to the values is not trigger for one object. Instead that update is called for the
memory address. Since both of them are targeting the same address, updates are depicted in them
both.

The connection is the RAM address that they share.

2.83 Add two accessor methods to the class—getAuthor and getTitle—that return the author
and title fields as their respective results. Test your class by creating some instances and calling
the methods.
public String getAuthor() {

return author;

public String getTitle() {

return title;

25
Add this code to the class, then compile and try the objects in BlueJ itself. You should try objects of
different author values and different titles.

2.84 Add two methods, printAuthor and printTitle, to the outline Book class. These should print
the author and title fields, respectively, to the terminal window.
public void printAuthor() {

System.out.println(author);

public void printAuthor() {

System.out.println(author);

Try them out in the IDE.

2.85 Add a field, pages, to the Book class to store the number of pages. This should be of type
int, and its initial value should be passed to the single constructor, along with the author and title
strings. Include an appropriate getPages accessor method for this field.
Exercise 2.X Are the Book objects you have implemented immutable? Justify your answer.
private int pages;

public Book(String bookAuthor, String bookTitle, int bookPages) {

author = bookAuthor;

title = bookTitle;

pages = bookPages;

public int getPages() {

return pages;

Immutability means that the properties cannot be updated. Yes, these properties are immutable.

2.86 Add a method, printDetails, to the Book class. This should print details of the author, title,
and pages to the terminal window
public void printDetails() {

System.out.println(“Title: ” + title + “, Author: “ + author + “, Pages: “ + pages);

26
2.87 Add a further field, refNumber, to the Book class. This field can store a reference number
for a library, for example. It should be of type String and initialized to the zero length string ("") in
the constructor, as its initial value is not passed in a parameter to the constructor. Instead,
define a mutator for it with the following header:
public void setRefNumber(String ref)
The body of this method should assign the value of the parameter to the refNumber field. Add a
corresponding getRefNumber accessor to help you check that the mutator works correctly.

private String refNumber;

public Book(String bookAuthor, String bookTitle, String bookPages) {

author = bookAuthor;

title = bookTitle;

pages = bookPages;

refNumber = “”;

public void setRefNumber(String ref) {

refNumber = ref;

public String getRefNumber() {

return refNumber;

You should create a new object after adding this code to the class definition. Try them out and see how
it works.

2.88 Modify your printDetails method to include printing the reference number. However, the
method should print the reference number only if it has been set—that is, the refNumber string
has a non-zero length. If it has not been set, then print the string "ZZZ" instead.
public void printDetails() {

if(refNumber.length() > 0) {

System.out.println(“Title: ” + title + “, Author: “ + author + “, Pages: “ + pages

+ “, Ref number: ” + refNumber);

} else {

System.out.println(“Title: ” + title + “, Author: “ + author + “, Pages: “ + pages

+ “, Ref number: ZZZ”);

27
2.89 Modify your setRefNumber mutator so that it sets the refNumber field only if the
parameter is a string of at least three characters. If it is less than three, then print an error
message and leave the field unchanged.
public void setRefNumber(String ref) {

if(ref.length() > 2) {

refNumber = ref;

} else {

System.out.println(“Parameter must have 3 characters at least.”);

2.90 Add a further integer field, borrowed, to the Book class. This keeps a count of the number
of times a book has been borrowed. Add a mutator, borrow, to the class. This should update the
field by 1 each time it is called. Include an accessor, getBorrowed, that returns the value of this
new field as its result. Modify printDetails so that it includes the value of this field with an
explanatory piece of text.
private int borrowed;

public void borrow() {

borrowed += 1;

public int getBorrowed() {

return borrowed;

public void printDetails() {

if(refNumber.length() > 0) {

System.out.println(“Title: ” + title + “, Author: “ + author + “, Pages: “ + pages

+ “, Ref number: ” + refNumber);

} else {

System.out.println(“Title: ” + title + “, Author: “ + author + “, Pages: “ + pages

+ “, Ref number: ZZZ”);

if(borrowed > 0) {

System.out.println(“The book is borrowed.”);

28
2.91 Add a further boolean field, courseText, to the Book class. This records whether or not a
book is being used as a text book on a course. The field should be set through a parameter to the
constructor and the field is immutable. Provide an accessor method for it called isCourseText.
private Boolean courseText;

public Book(String bookAuthor, String bookTitle, String bookPages) {

author = bookAuthor;

title = bookTitle;

pages = bookPages;

refNumber = “”;

public boolean isCourseText() {

return courseText;

2.92 Create a new project, heater-exercise, within BlueJ. Edit the details in the project
description—the text note you see in the diagram. Create a class, Heater, that contains a single
field, temperature whose type is double-precision floating point. Define a constructor that takes
no parameters. The temperature field should be set to the value 15.0 in the constructor. Define
the mutators warmer and cooler, whose effect is to increase or decrease the value of
temperature by 5.0° respectively. Define an accessor method to return the value of
temperature.
Below is the code for that program. I will assume that you have created the project and the class. Once
that is done, continue to write the following code in the class file.
/**

* The heater class is used to make the room cooler or warmer provided a given temperature.

* @author Afzaal Ahmad Zeeshan

* @version 1.0

*/

public class Heater

// instance variables - replace the example below with your own

private double temperature;

/**

* Constructor for objects of class Heater

29
* Updates the value to 15.0 degree.

*/

public Heater()

// initialise instance variables

temperature = 15.0;

// Accessor

public double getTemperature() {

return temperature;

// Mutators

public void cooler() {

temperature -= 5;

public void warmer() {

temperature += 5;

That is it.

30
2.93 Modify your Heater class to define three new doubleprecision floating point fields: min,
max, and increment. The values of min and max should be set by parameters passed to the
constructor. The value of increment should be set to 5.0 in the constructor. Modify the
definitions of warmer and cooler so that they use the value of increment rather than an explicit
value of 5.0. Before proceeding further with this exercise, check that everything works as before.

Now modify the warmer method so that it will not allow the temperature to be set to a value
greater than max. Similarly modify cooler so that it will not allow temperature to be set to a
value less than min. Check that the class works properly. Now add a method, setIncrement, that
takes a single parameter of the appropriate type and uses it to set the value of increment. Once
again, test that the class works as you would expect it to by creating some Heater objects within
BlueJ. Do things still work as expected if a negative value is passed to the setIncrement method?
Add a check to this method to prevent a negative value from being assigned to increment.
Entire code for this program is provided below.
/**

* The heater class used to control the heat in the room.

* @author Afzaal Ahmad Zeeshan

* @version 1.0

*/

public class Heater

// instance variables - replace the example below with your own

private double temperature;

// Additional fields

private double min;

private double max;

private double increment;

/**

* Constructor for objects of class Heater

* Updates the value to 15.0 degree.

*/

public Heater(double _min, double _max)

31
// initialise instance variables

temperature = 15.0;

// Setters

min = _min;

max = _max;

increment = 5;

// Accessor

public double getTemperature() {

return temperature;

public void setIncrement(double inc) {

if(inc > 0) {

increment = inc;

} else {

System.out.println("Value must be positive.");

// Mutators

public void cooler() {

if(temperature > min) {

temperature -= 5;

} else {

System.out.println("Min temperature reached.");

public void warmer() {

32
if(temperature < max) {

temperature += 5;

} else {

System.out.println("Max temperature reached.");

This code should be copied to the project’s class file. Then you will test the objects in the IDE itself.
Notice if there is anything that needs to be changed.

33
Final words
This guide contains explanation for the chapters, their contents and then provides ideas and
explanations to the answers. You should always consider testing with them.

BlueJ IDE can be used to test these codes and understand how Java manipulate the objects in the
memory and how statements are executed.

34

You might also like