comp sci test 4 (writing classes)

Ace your homework & exams now with Quizwiz!

Which of the following code segments would successfully create a new Student object? Student one = new Student(328564, 11); Student two = new Student(238783); int id = 392349;int grade = 11;Student three = new Student(id,

I, II, and III

Which of the following code segments can replace /* missing code */ to ensure that the withdraw method works as intended?

III only

Where would you find the formal parameters?

In the documentation.

What is the purpose of overloading a class' constructor?

It allows the user to set the values of different combinations of the instance variables when the object is created.

If you do not implement a constructor for your class,

Java creates one for you and gives all instance variables default values

What would be printed by this code snippet?String language = "Java";String opinion = " is fun!";System.out.println(language + opinion);

Java is fun!

public double calculate(double x, double y, double a, double b) { return /* missing code */; } Which of the following can replace /* missing code */ so that the method works as intended?

Math.sqrt(Math.pow(x + y, 2) / Math.abs(a - b))

Which of the following is a benefit of using a mutator method?

Mutator methods can verify the new value is a valid value for the instance variable

Static methods can access

Only other static instance variables and class methods

The purpose of a wrapper class is to

"Wrap" a primitive value to convert it to an object

public Glasses(Prescription thePrescription) { script = thePrescription; } What is the output of the following code snippet?

(-1.5, -1.5) (-1.5, -1.5)

public class Person { private String name; private int age; private boolean adult; public Person (String n, int a) { name = n; age = a; if (age >= 18) { adult = true; } else { adult = false; } } } Which of the following statements will create a Person object that represents an adult person?

Person p = new Person ("Homer", 23);

Which of the following is true?

Primitives are returned by value. Objects are returned by reference.

public int pick(boolean test, int x, int y) { if (test) return x; else return y; } What value is returned by the following method call? pick(false, pick(true, 0, 1), pick(true, 6, 7))

6

Accessors and mutators are used to

Allow private data to be accessed outside of the class and be safely modified.

A String variable called color to represent the color of the car An int variable called year to represent the year the car was made A String variable called make to represent the manufacturer of the car A String variable called model to represent the model of the car The object vehicle will be declared as type Car. Which of the following descriptions is accurate?

An attribute of the vehicle object is color.

String oldStr = "ABCDEF"; String newStr = oldStr.substring(1, 3) + oldStr.substring(4); System.out.println(newStr); What is printed as a result of executing the code segment?

BCEF

Why can't this be used in static methods?

Static methods are not called using an object. Thus, this would be null.

Which of the following describes the difference between static methods and instance methods?

Static methods can be called without using an object while instance methods need to be called on an object

public class Something { private static int count = 0; public Something() { count += 5; } public static void increment() { count++; } } The following code segment appears in a method in a class other than Something. Something s = new Something(); Something.increment();

The code segment creates a Something object s. The class Something's static variable count is initially 0, then increased by 5, then increased by 1.

Which of the following is NOT a characteristic of a mutator?

The method returns the value of an instance variable

public class Password { private String password; public Password (String pwd) { password = pwd; } public void reset(String new_pwd) { password = new_pwd; } } Consider the following code segment, which appears in a method in a class other than Password. The code segment does not compile.

The reset method does not return a value that can be printed.

What is the this keyword used to reference?

The this keyword references the object that called the method.

public class ItemInventory { private int numItems; public ItemInventory(int num) { numItems = num; } public updateItems(int newNum) { numItems = newNum; } } Which of the following best identifies the reason the class does not compile?

The updateItems method is missing a return type.

What is the difference between a getter method and an accessor method?

There is no difference. They refer to the same idea.

Power ability = friend.getPower(); ability.setName("X-Ray Vision");

X-Ray Vision

The value that a method outputs is called

a return value.

Which of the following statements correctly stores the return value of goingUp when it is called on the Elevator object called hotel?

boolean up = hotel.goingUp();

Each of the methods below can be found in the Rectangle class. Which of the following methods would have access to the parameter object's private data and methods?

public void copy(Rectangle other)

Which of the following methods is implemented correctly with respect to the method's return type?

public String getColor(){ return "Red";}

What would be printed the first time printPhrases was called from main? public class PrintQuestion { private static String phrase = "Hello World!"; public static void printPhrases() { String phrase = "hi"; System.out.println(phrase); phrase = "hello"; } }

hi

Which of the following can be used to replace / * missing code * / so that advance will correctly update the time?

hours = hours + minutes / 60; minutes = minutes % 60;

Which of the following correctly uses the this keyword?

public boolean isSame(Bird other) { return this.name.equals(other.name); }

The following statement appears in a method in a class other than Tester. It is intended to create a new Tester object t with its attributes set to 10 and 20. Tester t = new Tester(10, 20); Which of the following can be used to replace /* missing constructor */ so that the object t is correctly created?

public Tester(int first, int second) { num1 = first; num2 = second; }

Which of the following is a correctly written method for the class below?

public void addFiveMinutes{ length = length + 5;}

double d1 = 10.0; Double d2 = 20.0; Double d3 = new Double(30.0); double d4 = new Double(40.0); System.out.println(d1 + d2 + d3.doubleValue() + d4); What, if anything, is printed when the code segment is executed?

100.0

What does it mean to be a client of a class?

Being a client of a class means that we can use its methods and functionality without necessarily understanding how it works.

What is the difference between instance variables and static variables?

Each object has its own copy of the instance variables, but all objects share a copy of the static variables

public class Pineapple{ private boolean isRipe; private String color; private double weight; // Rest of class goes here} When we use this class to create Pineapple objects, which of the following is guaranteed to be true?

Every Pineapple object will have the same attributes.

Which of the following is NOT a valid way to overload this constructor? For brevity, only the signature is given.Pineapple(String color)

FancyPineapple(String color, int age)

What would the value of the static variable phrase be after the first time printPhrases was called from main? public class PrintQuestion { private static String phrase = "Hello World!"; public static void printPhrases() { String phrase = "hi"; System.out.println(phrase); phrase = "hello"; } }

Hello World!

public class Info { private String name; private int number; public Info(String n, int num) { name = n; number = num; } public void changeName(String newName) { name = newName; } public int addNum(int n) { num += n; return num; } } Which of the following best explains why the class will not compile?

The variable num is not defined in the addNum method.

You are using a class as a client. What would you need to know in order to create an object of the class you intend to use?

You need to know the formal parameters in order to pass in actual parameters.

The return type of an accessor method

must match the type of of the instance variable being accessed

Which of the following statements, if located in a method in the Student class, will determine the average of all of the student's grades except for the lowest grade and store the result in the double variable newAverage ?

newAverage = (sumOfGrades() - lowestGrade()) / (numberOfGrades() - 1);

Which of the following is NOT a proper use of the keyword this?

to access the private variables of other objects of the same class

The purpose of an accessor method is

to return the value of an instance variable

What happens when a int is autoboxed?

A int is autoboxed when it is converted to a Integer

int one = 1; int two = 2; String zee = "Z"; System.out.println(one + two + zee); What is printed as a result of executing the code segment?

3Z

public class MenuItem { private double price; public MenuItem(double p) { price = p; } public double getPrice() { return price; } public void makeItAMeal() { Combo meal = new Combo(this); price = meal.getComboPrice(); } } public class Combo { private double comboPrice; public Combo(MenuItem item) { comboPrice = item.getPrice() + 1.5; } public double getComboPrice() { return comboPrice; } } The following code segment appears in a class other than MenuItem or Combo. MenuItem one = new MenuItem(5.0); one.makeItAMeal(); System.out.println(one.getPrice());

6.5

What would be printed by the following code snippet?String lastName = "Vu";String otherLastName = "Lopez";int comparison = lastName.compareTo(otherLastName);System.out.println(comparison);

A positive number because "Vu" comes after "Lopez" in lexicographical order.

What is an instance method?

An instance method is a piece of code called on a specific instance (an object) of the class.

What is an object in Java?

An object is something that contains both state and behavior.

for (int i = 0; i < 5; i++) { int k = (int) (Math.random() * 10 + 1); if (k >= Element.max_value) { Element e = new Element(k); } } Which of the following best describes the behavior of the code segment?

Between 1 and 5 Element objects are created, and Element.max_value is increased for at least one object created.

Class members that should be public are I. Constructors II. Instance Variables III. Accessors/Mutators IV. Methods the class uses for itself, but the user does not need V. Methods the user needs to manipulate the objects of the class

I, III, V

public class Toy { private String name; private double price; public Toy(String n, double p) { name = n; price = p; } public void raisePrice(double surcharge) // Line 12 { return price + surcharge; // Line 14 } Which of the following changes should be made so that the class definition compiles without error and the method raisePrice works as intended?

Replace line 14 with price += surcharge;

public class Bugs { private int population; public Bugs(int p) { population = p; } public int getPopulation() { return p; } } Which of the following best explains why the getPopulation method does NOT work as intended?

The instance variable population should be returned instead of p, which is local to the constructor.

public boolean isSaltWater() { if (saltWater) { return "Salt Water"; } else { return "Fresh Water"; } } } Which of the following best explains the reason why the class will not compile?

The value returned by the isSaltWater method is not compatible with the return type of the method.

Which of the following types can be permanently modified in a method when it is passed as a parameter to a method?

any user defined class

An object's state is defined by the object's

instance variables and their values

public int function1(int i, int j) { return i + j; } public int function2(int i, int j) { return j - i; } Which of the following statements, if located in a method in the same class, will initialize the variable x to 11?

int x = function1(4, 5) + function2(1, 3);

The return type of an mutator method

is usually void

public class TemperatureReading implements Comparable { private double temperature; private int month, day, year; public int compareTo(Object obj) { TemperatureReading other = (TemperatureReading) obj; /* missing code */ } // There may be instance variables, constructors, and methods that are not shown. } Consider the following code segments that are potential replacements for /* missing code */. Double d1 = new Double(temperature); Double d2 = new Double(other.temperature); return d1.compareTo(d2); if (temperature < other.temperature) return -1; else if (temperature == other.temperature) return 0; else return 1; III. return (int) (temperature - other.temperature); Which of the code segments could be used to replace /* missing code */ so that compareTo can be used to order TemperatureReading objects by increasing temperature value?

not: . I and III only

ExamScore es = new ExamScore("12345", 80.0); es.bonus(5); System.out.println(es.getScore()); What is printed as a result of executing the code segment?

not: 85

A reference variable holds a special value. What is this special value?

not: A reference variable holds a special value. What is this special value? maybe: The memory address of an object

What is the scope of private methods and private instance variables?

not: Any class using an object of the declaring class maybe: the method it was declared

public class Circle { private double radius; public double computeArea() { private double pi = 3.14159; public double area = pi * radius * radius; return area; } // Constructor not shown. } Which of the following best explains why the computeArea method will cause a compilation error?

not: Local variables used inside a method must be declared before the method header.

public void changeIt(int[] arr, int index, int newValue) { arr[index] += newValue; } Which of the following code segments, if located in a method in the same class as changeIt, will cause the array myArray to contain {0, 5, 0, 0} ?

not: int[] myArray = new int[4]; changeIt(myArray, 2, 5);

It is considered good practice to

not: never pass objects as parameters only set when the post condition is true

public class Car { /* missing code */ } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class?

private String make; private String model; public Car(String myMake, String myModel) { /* implementation not shown */ }

The Glasses class represents a pair of eyeglasses. One of its instance variables is a Prescription object called script. The Prescription object has instance variables that stores the prescription for the left and right eye. Which of the following constructors for the Glasses class correctly sets the script instance variable correctly? Assume any method calls are valid.

public Glasses(Prescription thePrescription){ script = new Prescription(thePrescription.getLeft(),thePrescription.getRight());}

Which of the following code segments should replace /* missing code */ so that the calculateFee method will work as intended?

return (days * dailyRate) + (miles * mileageRate);

When the call test ( ) is executed, what are the values of s and n at the point indicated by / * End of method * / ?

s / n world / 6

Where must a static variable be initialized?

same time it is declared

public class Shark{ // Attributes private String habitat; private int age; public Shark(String region, int sharkAge) { habitat = region; age = sharkAge; }}

sharkAge

Which of the following is the correct /* implementation */ code for the constructor in the Card class?

suit = cardSuit;value = cardValue;

Which variables are in scope at the point labeled // POINT A? In other words, which variables exist at that point in the code? public class ScopeQuiz { private int count = 0; public void printPointSums() { int sum = 0; // POINT A for(int i = 0; i < 10; i++) { sum += i; } int result = sum + count; } }

sum and count

Suppose there is a local variable declared in the method of a particular class. The local variable's scope is

the method in which is it declared

The purpose of a mutator method is

to safely modify an instance variable

What method must a class implement in order to concatenate an object of the class with a String object?

toString

timecards

total.advance(timeCards[k].getHours(), timeCards[k].getMinutes();


Related study sets

Ch 18 - Case Study: Diets for Disease Prevention

View Set

Honors Psychology Unit 6: Social Cognition, Emotion, and Persuasion

View Set

5.8 Reactions to the Industrial Economy

View Set

Espanol - Temas y preguntas para el examen oral

View Set

History of Rock 'n Roll Final Study Guide

View Set

ORDER: 1-55 (TEST 1), 56-115 (TEST 2),

View Set