Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Chapter 4 Defining Classes I – absolute java test bank


 

Download  file with the answers

Not a member!
Create a FREE account here to get access and download this file with answers


Chapter 4
Defining Classes I
 Multiple Choice
1) The new operator:
(a) allocates memory
(b) is used to create an object of a class
(c) associates an object with a variable that names it.
(d) All of the above.

2) A method that performs some action other than returning a value is called a __________ method.
(a) null
(b) void
(c) public
(d) private

3) The body of a method that returns a value must contain at least one _________ statement.
(a) void
(b) invocation
(c) thows
(d) return

4) A variable whose meaning is confined to an object of a class is called:
(a) instance variable
(b) local variable
(c) global variable
(d) none of the above

5) A variable whose meaning is confined to a method definition is called an/a
(a) instance variable
(b) local variable
(c) global variable
(d) none of the above

6) In Java, a block is delimited by:
(a) ( )
(b) /* */
(c) “ “
(d) { }

7) In Java, call-by-value is only used with:
(a) objects
(b) primitive types
(c) this
(d) all of the above

8) The parameter this refers to
(a) instance variables
(b) local variables
(c) global variables
(d) the calling object

9) When the parameters in a method have the same as instance variables you can differentiate them by using the _____ parameter.
(a) String
(b) hidden
(c) default
(d) this

10) Two methods that are expected to be in all Java classes are:
(a) getName and setName
(b) toString and equals
(c) compareTo and charAt
(d) toLowerCase and toUpperCase

11) A program whose only task is to test a method is called a:
(a) driver program
(b) stub
(c) bottom-up test
(d) recursive method

12) Java has a way of officially hiding details of a class definition. To hide details, you mark them as _________.
(a) public
(b) protected
(c) private
(d) all of the above

13) A set method is:
(a) an accessor method
(b) a mutator method
(c) a recursive method
(d) none of the above

14) Accessor methods:
(a) return something equivalent to the value of an instance variable.
(b) promotes abstraction
(c) both A and B
(d) none of the above

15) A more eloquent approach in implementing mutator methods is to return a ________ value.
(a) int
(b) char
(c) boolean
(d) double

16) A _________ states what is assumed to be true when the method is called.
(a) prescript
(b) postscript
(c) precondition
(d) postcondition

17) The name of a method and the list of ________ types in the heading of the method definition is called the method signature.
(a) parameter
(b) argument
(c) return
(d) primitive

 True/False
1) An object of class A is an instance of class A.

2) An invocation of a method that returns a value can be used as an expression any place that a value of the Type_Returned can be used.

3) The Java language supports global variables.

4) In a method invocation, there must be exactly the same number of arguments in parentheses as there are formal parameters in the method definition heading.

5) When you give a command to run a Java program, the runtime system invokes the class constructor.

6) Inside a Java method definition, you can use the keyword this as a name for the calling object.

7) Boolean expressions may be used to control if-else or while statements.

8) The modifier private means that an instance variable can be accessed by name outside of the class definition.

9) It is considered good programming practice to validate a value passed to a mutator method before setting the instance variable.

10) Mutator methods can return integer values indicating if the change of the instance variable was a success.

11) Method overloading is when two or more methods of the same class have the same name but differ in number or types of parameters.

12) Java supports operator overloading.

13) Only the default constructor has the this parameter.

 Short Answer/Essay
1) Write a Java method that prints the phrase “Five purple people eaters were seen munching Martians”.
Answer:
/** void method that prints a phrase */
public void printPhrase()
{
System.out.println(“Five purple people eaters were seen munching Martians!”);
}
2) What is the purpose of the new operator?
Answer: The new operator is used to create an object of a class and associate the object with the variable that names it. Memory is also allocated for that object.
3) Write a Java method that returns the value of PI, where PI = 3.1415926535.
Answer:
/** method that returns the value of PI */
public double piValue()
{
return 3.1415926535;
}
4) Define the terms arguments and parameters. How are they different?
Answer: Parameters, also referred to as formal parameters, are used to define the list of variables included in the parenthesis in a method signature. An argument is the value actually sent to the method upon invocation. The terms parameters and argument are very similar in meaning and are often used interchangeably by programmers. The terms differ slightly in that an argument is the actual value that replaces the parameter within the method.
5) Write a method called power the computes xn where x and n and positive integers. The method has two integer parameters and returns a value of type long.
Answer:
/** x and n are nonnegative integers */
public long power(int x, int n)
{
long result = 1;
/** check for positive numbers */
if((x >= 0) && (n >= 0))
{
/** raise x to the nth power */
for(int i = n; i > 0; i–)
result *= x;
}
else
{
result = 0;
System.out.println(“Fatal error…….positive integers required!”);
}
return result;
}
6) Write a method called Greeting that displays a personalized greeting given a first name.
Answer:
/** method to display a personalized greeting */
public static void greeting(String name)
{
System.out.println(“Hello ” + name);
}
7) Discuss a situation in which it is appropriate to use the this parameter.
Answer: One common situation that requires the use of the this parameter occurs when you have parameters of the method with the same name as the instance variables of the class. Otherwise, if an instance variable is referenced directly by name within its class, this is understood.
8) Write a method called isEqual that returns a Boolean value. The method compares two integers for equality.
Answer:
/** method to compare to integers for equality */
public static boolean isEqual(int x, int y)
{
return x == y;
}
9) Discuss the public and private modifiers in context of methods and instance variables.
Answer: The modifiers public and private can both be used with methods and instance variables. Any instance variable can be labeled either public or private. The modifier public means that there are no restrictions on where the instance variable can be used. The modifier private means that the instance variable cannot be accessed by name outside of the class definition.
The modifiers public and private before a method definition have a similar meaning. If the method is labeled public, there are no restrictions on its usage. If the method is labeled private, the method can only be used in the definition of another method of the same class.
Normal good programming practices require that all instance variables be private and typically most methods be public.

10) Create a class named Appointment that contains instance variables startTime, endTime, dayOfWeek (valid values are Sunday through Saturday), and a date which consists of a month, day and year. All times should be in military time, therefore it is appropriate to use integers to represent the time. Create the appropriate accessor and mutator methods.
Answer:
public class Appointment
{
private int startTime;
private int endTime;
private String dayOfWeek;
private String month;
private int day;
private int year;
/** Mutator methods */
public void setStartTime(int st)
{
/** valid range for military time is 0-2400 */
if((st >= 0) && (st <= 2400)) startTime = st; } public void setEndTime(int et) { /** valid range for military time is 0-2400 */ if((et >= 0) && (et <= 2400)) endTime = et; } public void setDayOfWeek(String dow) { /** Valid values are the strings Sunday – Saturday */ if(checkDayOfWeek(dow)) dayOfWeek = dow; else System.out.println(“Fatal error….invalid day of week value!”); } public void setMonth(String m) { /** Valid values are strings January – December */ if(checkMonth(m)) month = m; else System.out.println(“Fatal error…invalid month value!”); } public void setDay(int d) { /** Valid days in a date are the integers 1 – 31 */ if((d >= 1) && (d <= 31)) day = d; } public void setYear(int y) { if(y >= 0)
year = y;
}
/** Accessor methods */
public int getStartTime()
{
return startTime;
}
public int getEndTime()
{
return endTime;
}
public String getDayOfWeek()
{
return dayOfWeek;
}
public String getMonth()
{
return month;
}
public int getDay()
{
return day;
}
public int getYear()
{
return year;
}
/** Facilitator methods */
private boolean checkDayOfWeek(String d)
{
if(d.equalsIgnoreCase(“Sunday”) || d.equalsIgnoreCase(“Monday”) ||
d.equalsIgnoreCase(“Tuesday”) || d.equalsIgnoreCase(“Wednesday”) ||
d.equalsIgnoreCase(“Thursday”) || d.equalsIgnoreCase(“Friday”) ||
d.equalsIgnoreCase(“Saturday”) || d.equalsIgnoreCase(“Sunday”))
return true;
else
return false;
}
private boolean checkMonth(String month)
{
if(month.equalsIgnoreCase(“January”) || month.equalsIgnoreCase(“February”) ||
month.equalsIgnoreCase(“March”) || month.equalsIgnoreCase(“April”) ||
month.equalsIgnoreCase(“May”) || month.equalsIgnoreCase(“June”) ||
month.equalsIgnoreCase(“July”) || month.equalsIgnoreCase(“August”) ||
month.equalsIgnoreCase(“September”) ||
month.equalsIgnoreCase(“October”) ||
month.equalsIgnoreCase(“November”) || month.equalsIgnoreCase(“December”))
return true;
else
return false;
}
}

11) Discuss the importance of accessor and mutator methods and how they apply to the abstraction concept.
Answer: It is considered good programming practice to make all instance variables private, but there are times when the values of the instance variables need to be accessed or updated. Accessor methods allow you to obtain the data, while mutator methods allow you to change the data in a class object. A mutator method can verify the validity of a value before updating the instance variable.
12) Write preconditions and postconditions for the power method you wrote in question #4.
Answer:
/** Precondition: All instance variables of the calling object have values.
Postcondition: A positive integer value equal to x to the power n is returned.
*/
13) Add two constructors to the Appointment class created in question #9. Include a default constructor and a constructor to initialize an Appointment to suitable arguments.
Answer:
/** Class constructors */
public Appointment()
{
startTime = 0;
endTime = 0;
dayOfWeek = “”;
month = “”;
day = 0;
year = 0;
}

public Appointment(int st, int et, String dow, String m, int d, int y)
{
setStartTime(st);
setEndTime(et);
setDayOfWeek(dow);
setMonth(m);
setDay(d);
setYear(y);
}

14) Write a complete Java class that uses the console window to prompt the user for a sentence to parse. Use the StringTokenizer class to echo the tokens back to the console.

import java.util.Scanner;
import java.util.StringTokenizer;

public class Parser
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
System.out.print(“Enter a sentence and I’ll display each word you entered: “);
String sentence = keyboard.nextLine();
//Parse the string into tokens and echo back to the user
StringTokenizer tk = new StringTokenizer(sentence, ” “);
System.out.println(“Here are the tokens: “);
while(tk.hasMoreTokens())
{
System.out.println(tk.nextToken());
}
}
}
15) Write a Java class that represents a Student with instance variables name, id, and gpa. Include constructors, accessor, mutator and any facilitator methods you may need.
Answer:
public class Student
{
private String name;
private String id;
private double gpa;

/** Constructors */
public Student()
{
name = null;
id = null;
gpa = 0.0;
}
public Student(String n, String i, double g)
{
name = n;
id = i;
gpa = g;
}
/** Accessor methods */
public String getName()
{
return name;
}
public String getID()
{
return id;
}
public double getGPA()
{
return gpa;
}

/** Mutator methods */
public void setName(String n)
{
name = n;
}

public void setID(String i)
{
id = i;
}

public void setGPA(double g)
{
if((g >= 0) && (g <= 4)) gpa = g; } /** Facilitator methods */ public String toString() { return (name + ” ” + id + ” ” + gpa); } public boolean equals(Student s) { return ((name.equalsIgnoreCase(s.name)) && (id.equalsIgnoreCase(s.id)) && (s.gpa == gpa)); } } 16) Write a driver program to test your Student class created in question #14. Answer: public class StudentTest { public static void main(String args[]) { Student firstStudent = new Student(); Student secondStudent = new Student(“Wally Wonders”, “xyz557”, 2.54); System.out.println(“First Student statistics: “); System.out.println(firstStudent.getName() + ” ” + firstStudent.getID() + ” ” + firstStudent.getGPA()); System.out.println(“Second Student statistics: “); System.out.println(secondStudent.getName() + ” ” + secondStudent.getID() + ” ” + secondStudent.getGPA()); firstStudent.setName(“Sharon Smith”); firstStudent.setID(“wyh886”); firstStudent.setGPA(3.99); System.out.println(firstStudent); System.out.println(secondStudent); System.out.println(“Comparing student objects, evalutes to ” + firstStudent.equals(secondStudent)); } } 17) Rewrite the following method using the this parameter. public void setDay(int d) { //Valid days in a date are the integers 1 – 31 if((d >= 1) && (d <= 31)) day = d; } public boolean setDay(int day) { if((day >=1) && (day <= 31))
{
this.day = day;
return true;
}
else
{
return false;
}
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!