Multiple Choice
1) The individual variables that together make up the array are referred to as:
(a) indexed variables
(b) subscripted variables
(c) elements of the array
(d) all of the above
Answer: D
2) What is the correct expression for accessing the 5th element in an array named colors?
(a) colors[3]
(b) colors[4]
(c) colors[5]
(d) colors[6]
Answer: B
3) Consider the following array:
myArray[0] | 7 |
myArray[1] | 9 |
myArray[2] | -3 |
myArray[3] | 6 |
myArray[4] | 1 |
myArray[5] | -1 |
What is the value of myArray[myArray[1] – myArray[0]]
(a) 7
(b) 9
(c) -3
(d) 6
Answer: C
4) The subscript of the first indexed variable in an array is:
(a) 0
(b) 1
(c) 2
(d) 3
Answer: A
5) The correct syntax for accessing the length of an array named Numbers is:
(a) Numbers.length()
(b) Numbers.length
(c) both A and B
(d) none of the above
Answer: B
6) An ArrayIndexOutOfBounds error is a:
(a) compiler error
(b) syntax error
(c) logic error
(d) all of the above
Answer: C
7) Which of the following initializer lists correctly initializes the indexed variables of an array named myDoubles?
(a) double myDoubles[double] = {0.0, 1.0, 1.5, 2.0, 2.5};
(b) double myDoubles[5] = new double(0.0, 1.0, 1.5, 2.0, 2.5);
(c) double[] myDoubles = {0.0, 1.0, 1.5, 2.0, 2.5};
(d) array myDoubles[double] = {0.0, 1.0, 1.5, 2.0, 2.5};
Answer: C
8) The base type of an array may be all of the following but:
(a) string
(b) boolean
(c) long
(d) all of these may be a base type of an array.
Answer: D
9) The correct syntax for passing an array as an argument in a method is:
(a) a[]
(b) a()
(c) a
(d) a[0]..a[a.length]
Answer: C
10) Partially filled arrays require:
(a) a variable to track the number of array positions used
(b) the use of local variables
(c) the use of global variables
(d) all of the above
Answer: A
11) Java provides a looping mechanism for objects of a collection. This looping mechanism is called a __________ loop.
(a) While
(b) For
(c) For each
(d) All of the above
Answer: C
12) A _________ can occur if a programmer allows an accessor method to return a reference to an array instance variable.
(a) short circuit
(b) privacy leak
(c) partially filled array
(d) syntax error
Answer: B
13) The name of the sorting algorithm that locates the smallest unsorted value in an array and places it in the next sorted position of the array is called:
(a) bubble sort
(b) merge sort
(c) radix sort
(d) selection sort
Answer: D
14) A value of an enumerated type is similar to a/an:
(a) Instance variable
(b) Object of a class
(c) Named constant
(d) None of the above
Answer: C
15) An array with more than one index is called a/an:
(a) partially filled array
(b) multidimensional array
(c) bidirectional array
(d) one dimensional array
Answer: B
16) A type of array in which different rows can have different number of columns is called a/an:
(a) partially filled array
(b) ragged array
(c) initialized array
(d) none of the above
Answer: B
17) A ________ loop is a good way to step through the elements of an array and perform some program action on each indexed variable.
(a) while
(b) do…while
(c) for
(d) all of the above
Answer: C
n True/False
1) An array is a collection of variables all of the same type.
Answer: True
2) An array has only one public instance variable, which is named length.
Answer: True
3) An arrays length instance variables value can be changed by a program.
Answer: False
4) An array of chars is the same as a String in Java.
Answer: False
5) An array name references a memory address.
Answer: True
6) You can only use array indexed variables as arguments to methods.
Answer: False
7) A method can not change the values stored in the indexed variables of an array argument.
Answer: False
8) A collection class is a class whose objects store a collection of values.
Answer: True
9) You may cycle through elements of a collection object using a for loop.
Answer: False
10) In a vararg specification the ellipsis is not part of the Java syntax.
Answer: False
11) A variable of an enumerated type can have the special value null.
Answer: True
12) Java allows you to declare arrays with more than one index.
Answer: True
13) A one dimensional array is also called an array of arrays.
Answer: False
14) Arrays are objects that are created with new just like class objects.
Answer: True
n Short Answer/Essay
1) Write a Java statement that declares and creates an array of Strings named Breeds. Your array should be large enough to hold the names of 100 dog breeds.
- String[] Breeds = new String[100];
2) Declare and create an integer array that will contain the numbers 1 through 100. Use a for loop to initialize the indexed variables.
int[] wholeNumbers = new int[100];
for(int i = 0; i < 100; ++i)
wholeNumbers[i] = i + 1;
3) What are three ways you can use the square brackets [ ] with an array name?
- First, the square brackets can be used to create a type name, such as double[] score. Second, the square brackets can be used with an integer value as part of the special syntax Java uses to create a new array, as in score = new double[5]. The third use of square brackets is to name an indexed variable of the array, such as score[1].
4) Given the following character array
char[] h = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’};
Write a Java statement that will create a new String object from the character array.
- String s = new String(h);
5) Write a Java method that takes an integer array as a formal parameter and returns the sum of integers contained within the array.
public int sumArray(int[] a)
{
int sum = 0;
for(int i =0; i < a.length; i++)
sum += a[i];
return sum;
}
6) How are arrays tested to see if they contain the same contents?
- The best way to test two arrays to see if the contents are the same is to write a method that accomplishes the task. This method would iterate through each array comparing indexed variables. If arrays are tested for equality using the == operator, you are only testing to see if the arrays reference the same memory location. It is quite common for two arrays to reference different memory locations, but contain the same elements.
7) Explain what the main methods array parameter, args, is used for.
- Args allows the program to obtain input from the command line at runtime. To take advantage of this feature, the program is invoked with the java command, followed by the program name, and a list of arguments. Java stores these arguments in the args[] array.
8) Write a Java method as well as any facilitator methods needed to perform a sort on an array of whole numbers in descending order.
/**
Precondition: The array has values.
Action: Sorts a so that a[0] >= a[1] >= … >= a[a.length]
*/
public static void selectionSort(int[] a)
{
int indexOfLargest;
for(int i=0; i < a.length; ++i)
{
indexOfLargest = LargestIndex(i, a);
swap(i, indexOfLargest, a);
}
}
/**
Returns the index of the largest value among
a[start], a[start + 1], … a[a.length-1]
*/
private static int LargestIndex(int start, int[] a)
{
int max = a[start];
int indexOfMax = start;
for(int i=start + 1; i < a.length; i++)
{
if(a[i] > max)
{
max = a[i];
indexOfMax = i;
}
}
return indexOfMax;
}
/**
Precondition: i and j are legal indices for the array a.
Postcondition: Values of a[i] and a[j] have been interchanged
*/
private static void swap(int i, int j, int[] a)
{
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
9) Discuss how you could represent a table of related records using a multidimensional array.
- If a multidimensional array is viewed as a structure with rows and columns, one can easily see how it can be used to represent a table of related records. For example, a person has a name, street address, city, state and zip code. An array with 5 columns and as many rows as needed can be created to handle such a structure. To retrieve the information regarding a specific person, the array can be probed at a specific row iterating through the columns to retrieve the information.
10) Declare and create a multidimensional array to hold the first and last names of 10 people.
- String[][] Names = new String[10][2];
11) Declare and create a 10 x 10 multidimensional array of doubles.
- Double[][] myDoubles = new Double[10][10];
12) Initialize the array created in number 11 above to -1.0.
for(int row = 0; row < myDoubles.length; row++)
for(int column = 0; column < myDoubles[row].length; column++)
myDoubles[row][column] = -1.0;
13) Write a complete Java console application that prompts the user for a series of quiz scores. The user should type -1 to signify that the input of quiz scores is complete. Your program should then average the scores and display the result back to the user.
import java.util.*;
public class Average
{
public static void main(String args[])
{
Scanner stdin = new Scanner(System.in);
int quizGrade = 0;
int quizTotal = 0;
int quizCount = 0;
while(quizGrade != -1)
{
System.out.println(“Enter the quiz grade or -1 to exit”);
quizGrade = stdin.nextInt();
quizTotal += quizGrade;
quizCount++;
}
System.out.println(“The quiz average is ” +
QuizAverage(quizTotal, quizCount));
}
public static double QuizAverage(int total, int count)
{
return total/count;
}
}
14) What is the output of the following code?
int[] numbers = new int[10];
for(int i=0; i < numbers.length; ++i)
numbers[i] = i * 2;
for(int i=0; i < numbers.length; ++i)
System.out.print(numbers[i] + ” “);
System.out.println();
15) What is the output of the following code?
int[] numbers = new int[10];
for(int i=0; i < numbers.length; ++i)
numbers[i] = i * 2;
for(int i=0; i < numbers.length; ++i)
System.out.print(numbers[i] / 2 + ” “);
System.out.println();
16) Write Java statements to create a collection of integers, and to initialize each element of the collection to -1 using a for each statement.
int[] x = new int[10];
for(int element: x)
element = -1;
17) Create a Java method that will take any number of double arguments and return the smallest of the group.
public static double min(double… arg)
{
if(arg.length == 0)
{
System.out.println(“Fatal Error: minimum of zero values.”);
System.exit(0);
}
double smallest = arg[0];
for(int i = 1; i < arg.length; i++)
if(arg[i] < smallest)
smallest = arg[i];
return smallest;
}
18) Write a Java statement that creates an enumerated type called months that contains the twelve different months in a year.
enum Months {JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER,
DECEMBER};
19) Write a Java statement that prints the month July to the console window from the enumerated list crated in question number 18 above.
System.out.println(Months.JULY);
Chapter 7
Inheritance
n Multiple Choice
1) Inheritance is the process by which a new class – known as a _________ – is created from another class, called the _____________.
(a) base class, derived class
(b) derived class, base class
(c) inherited class, base class
(d) base class, inherited class
Answer: B
2) Inheritance promotes code ___________.
(a) reinvention
(b) reuse
(c) repeats
(d) all of the above
Answer: B
3) The keyword extends indicates:
(a) encapsulation
(b) polymorphism
(c) inheritance
(d) none of the above
Answer: C
4) A derived class is also called a
(a) sub class
(b) super class
(c) base class
(d) all of the above
Answer: A
5) A super class is also called a
(a) derived class
(b) dominant class
(c) sub class
(d) base class
Answer: D
6) What does a derived class automatically inherit from the base class?
(a) instance variables
(b) static variables
(c) public methods
(d) all of the above
Answer: D
7) If the final modifier is added to the definition of a method, this means:
(a) The method may be redefined in the derived class.
(b) The method may be redefined in the sub class.
(c) The method may not be redefined in the derived class.
(d) None of the above.
Answer: C
8) A base class is synonymous with a:
(a) Child class
(b) Parent class
(c) Derived class
(d) Sub class
Answer: B
9) The special syntax for invoking a constructor of the base class is:
(a) super()
(b) base()
(c) parent()
(d) child()
Answer: A
10) An object of a derived class has the type of the derived class, and it also has the type of the base class, and more generally, has the type of every one of its ___________ classes.
(a) descendant
(b) child
(c) ancestor
(d) sub
Answer: C
11) In using the keyword this in place of super(), the invocation of this must be the ___________ action taken by the constructor.
(a) first
(b) last
(c) it does not matter
(d) none of the above
Answer: A
12) A method or instance variable modified by protected:
(a) can not be accessed by name inside its own class definitions.
(b) can not be accessed by name inside any class derived from it.
(c) can not be accessed by name in the definition of any class in the same package.
(d) can not be accessed by name in any other class (that is, other than classes named in a-c.).
Answer: D
13) If an instance variable is not modified by public, protected or private then it is said to have:
(a) Package access
(b) Default access
(c) Friendly access
(d) All of the above
Answer: D
14) The class __________ is an ancestor class of all Java classes.
(a) String
(b) Object
(c) Math
(d) JFrame
Answer: B
15) The Object class contains the method:
(a) getClass()
(b) toString()
(c) equals()
(d) all of the above
Answer: D
16) The equals method for a class should have _________ as the type of its one parameter.
(a) String
(b) Object
(c) Integer
(d) Double
Answer: B
n True/False
1) A derived class contains only public instance variables and public methods from the base class.
Answer: False
2) Inheritance refers to a very specialized form of a class.
Answer: False
3) A derived class is a class defined by adding instance variables and methods to an existing class.
Answer: True
4) When you define a derived class, you give only the added instance variables and the added methods as well as all the methods from the base class.
Answer: False
5) The keyword extends indicates polymorphism.
Answer: False
6) Overriding is when a derived class redefines a method from the base class.
Answer: True
7) A constructor for a derived class begins with an invocation of a constructor for the base class.
Answer: True
8) The call to the base class constructor (super) must always be the last action taken in a constructor definition.
Answer: False
9) You may substitute the keyword this for super() to call a constructor of the derived class.
Answer: True
10) An instance variable (or method) that is private in a base class is accessible by name in the definition of a method in any other class.
Answer: False
11) Private methods of the base class are not available for use by derived classes.
Answer: True
n Short Answer/Essay
1) Explain what a call to super() does in a constructor of a derived class.
- When super() is used in a constructor of a derived class, the matching constructor in the immediate base class is invoked.
2) Define a base class to represent a Clock. Your class should have instance variables for hours, minutes and seconds.
public class Clock
{
private int hour;
private int minute;
private int second;
public Clock()
{
//initialize to default values
hour = 0;
minute = 0;
second = 0;
}
public Clock(int h, int m, int s)
{
setHour(h);
setMinute(m);
setSecond(s);
}
/**
Valid integers for hour is in the range of 0 – 24
*/
public void setHour(int h)
{
if((h >= 0) && (h <= 24))
hour = h;
else
System.out.println(“Fatal error: invalid hour”);
}
/**
Valid integers for minute is in the range 0 – 59
*/
public void setMinute(int m)
{
if((m >= 0) && (m <= 59))
minute = m;
else
System.out.println(“Fatal error: invalid minute”);
}
/**
Valid integers for second is in the range 0 – 59
*/
public void setSecond(int s)
{
if((s >= 0) && (s <= 59))
second = s;
else
System.out.println(“Fatal error: invalid second”);
}
public int getHour()
{
return hour;
}
public int getMinute()
{
return minute;
}
public int getSecond()
{
return second;
}
//Facilitator methods
public String toString()
{
return “The current time is: ” + hour + “:” + minute + “:” + second;
}
public boolean equals(Object o)
{
if(o == null)
return false;
else if(getClass() != o.getClass())
return false;
else
{
Clock otherClock = (Clock) o;
return((hour == otherClock.hour) && (minute == otherClock.minute)
&& (second == otherClock.second));
}
}
}
3) Define a derived class to represent an alarm clock. Use the Clock class, created in number 2 above, as your base class.
/**
An alarm clock should include a time to sound the alarm as well as methods
to set the alarm.
*/
public class AlarmClock extends Clock
{
public int alarmHour;
public int alarmMinute;
public int alarmSecond;
public AlarmClock()
{
super();
alarmHour = 0;
alarmMinute = 0;
alarmSecond = 0;
}
public AlarmClock(int theHour, int theMinute, int theSecond,
int alarmH, int alarmM, int alarmS)
{
super(theHour, theMinute, theSecond);
setAlarmHour(alarmH);
setAlarmMinute(alarmM);
setAlarmSecond(alarmS);
}
public void setAlarmHour(int alarmH)
{
if((alarmH >= 0) && (alarmH <= 24))
alarmHour = alarmH;
else
System.out.println(“Fatal error: invalid alarm hour”);
}
public void setAlarmMinute(int alarmM)
{
if((alarmM >= 0) && (alarmM <= 59))
alarmMinute = alarmM;
else
System.out.println(“Fatal error: invalid alarm minute”);
}
public void setAlarmSecond(int alarmS)
{
if((alarmS >= 0) && (alarmS <= 59))
alarmSecond = alarmS;
else
System.out.println(“Fatal error: invalid alarm second”);
}
public int getAlarmHour()
{
return alarmHour;
}
public int getAlarmMinute()
{
return alarmMinute;
}
public int getAlarmSecond()
{
return alarmSecond;
}
public String getCurrentAlarmTime()
{
return “The alarm is set to ” + alarmHour + “:” + alarmMinute + “:” +
alarmSecond;
}
//Facilitators
public String toString()
{
return “The current time is ” + getHour() + “:” + getMinute() + “:” +
getSecond() + “nThe alarm is set to ” + getAlarmHour() + “:” +
getAlarmMinute() + “:” + getAlarmSecond();
}
public boolean equals(Object o)
{
if(o == null)
return false;
else if(getClass() != o.getClass())
return false;
else
{
AlarmClock otherClock = (AlarmClock) o;
return((getHour() == otherClock.getHour()) && (getMinute() ==
otherClock.getMinute()) && (getSecond() ==
otherClock.getSecond()) && (alarmHour ==
otherClock.alarmHour) && (alarmMinute ==
otherClock.alarmMinute) &&
(alarmSecond == otherClock.alarmSecond));
}
}
}
4) Create a test driver to test the functionality of your AlarmClock class created in number 3 above.
public class ClockTest
{
/** Test driver to exercise the AlarmClock class */
public static void main(String args[])
{
AlarmClock myClock = new AlarmClock(12, 30, 0, 6, 30, 0);
System.out.println(myClock.toString());
//Change the alarm time
myClock.setAlarmHour(7);
System.out.println(myClock.toString());
//Create another AlarmClock object and test equals
AlarmClock mySecondClock = new AlarmClock();
if(myClock.equals(mySecondClock))
System.out.println(“The AlarmClocks are equal!”);
else
System.out.println(“The AlarmClocks are not equal!”);
}
}
5) Explain how parent and child classes are related to base and derived classes.
- A base class is often called the parent class, and a derived class is often called a child class.
6) Explain the difference between method overloading and method overriding.
- Overriding refers to redefining a method definition in a derived class. When a method definition is overridden, the new method definition has the exact same number and types of parameters. An overloaded method has the same name as another method in the class, but number and/or type of parameters differ.
7) What is an “is a” relationship? How does it apply to the world of objects?
- An “is a” relationship represents the principal of inheritance. Specifically, an “is a” relationship refers to the fact that every object not only is of its own type, but is also of the type of its ancestor classes. This is a reflection of what occurs in the everyday world.
8) What is a “has a” relationship?
- A “has a” relationship is a composition. It allows one to create closes that are composed of other classes.
9) What is encapsulation?
- Encapsulation is synonymous with data and detail hiding. Java supports such hiding through the private modifier.
10) Explain the modifiers public, protected and private.
- The public modifier signifies that an instance variable or method is inherited freely by the derived class. The protected modifier signifies that an instance variable or method is available by name inside its own class definition, as well as by any class derived from it or in the same package. The private modifier signifies that an instance variable or method is not available outside of its class definition.
11) What is package access?
- If an instance variable or method is not modified by public, protected or private, then it is said to have package access. Package access means that the instance variable or method can be accessed by name inside the definition of any class in the same package, but not outside of the package.
12) Write Java statements that compares Objects, O1 and O2, using the getClass() method.
if(O1.getClass() == O2.getClass())
System.out.println(“Same class!”);
else
System.out.println(“Not the same class!”);
13) What does the instanceof operator do?
- The instanceof operator checks to see if an object is of the type given as its second argument.
14) What are the different ways in which you can check the class of an Object?
- The method getClass() as well as the operator instanceof may be used to check the class type of an Object.
15) Create a class to represent a Rectangle. Your class should contain instance variables for length and width, as well as member method to calculate the area and perimeter.
public class Rectangle
{
private double length;
private double width;
public Rectangle()
{
length = 0;
width = 0;
}
public Rectangle(double l, double w)
{
setLength(l);
setWidth(w);
}
public void setLength(double l)
{
if(l >= 0)
length = l;
else
System.out.println(“Fatal error: Length may not be negative!”);
}
public void setWidth(double w)
{
if(w >= 0)
width = w;
else
System.out.println(“Fatal error: Width may not be negative!”);
}
public double getLength()
{
return length;
}
public double getWidth()
{
return width;
}
public double getArea()
{
return length * width;
}
public double getPerimeter()
{
return 2 * (length + width);
}
public String toString()
{
return “Length = ” + length + “nWidth = ” + width;
}
public boolean equals(Object o)
{
if(o == null)
return false;
else if(getClass() != o.getClass())
return false;
else
{
Rectangle otherRectangle = (Rectangle) o;
return((length == otherRectangle.length) &&
(width == otherRectangle.width));
}
}
}
16) Create a test driver to test the functionality of your Rectangle class created in number 14 above.
public class RectangleTest
{
public static void main(String args[])
{
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(5,6);
Rectangle r3 = r2;
System.out.println(r1.toString() + “n” + r2.toString() +
“n” + r3.toString());
r1.setLength(8);
r1.setWidth(10);
System.out.println(“The area of r1 = ” + r1.getArea());
System.out.println(“The perimeter of r1 = ” + r1.getPerimeter());
if(r1.equals(r2))
System.out.println(“r1 and r2 are equal!”);
else
System.out.println(“r1 and r2 are not equal!”);
if(r2.equals(r3))
System.out.println(“The area of r2 and r3 = ” + r2.getArea());
else
System.out.println(“r2 and r3 are not equal!”);