ap csa semseter 1

studied byStudied by 0 people
0.0(0)
Get a hint
Hint

How many times does the following loop iterate?// x has been initialized with a positive int valueint count = 0;while (count < x){ count++;} a x times b x + 1 times c Infinite number of times d The condition is never true so this loop never executes. e x - 1 times

1 / 947

flashcard set

Earn XP

Description and Tags

948 Terms

1

How many times does the following loop iterate?// x has been initialized with a positive int valueint count = 0;while (count < x){ count++;} a x times b x + 1 times c Infinite number of times d The condition is never true so this loop never executes. e x - 1 times

Infinite number of times

New cards
2

e

e

New cards
3

At a certain high school students receive letter grades based on the following scale. Which of the following code segments will assign the correct string to gradefor a given integer score ? A II only B III only C I and II only D I and III only E I, II, and III

D I and III only

New cards
4

Consider the following Boolean expressions. I. A && B II. !A && !B Which of the following best describes the relationship between values produced by expression I and expression II? A Expression I and expression II evaluate to different values for all values of A and B. B Expression I and expression II evaluate to the same value for all values of A and B. C Expression I and expression II evaluate to the same value only when A and B are the same. D Expression I and expression II evaluate to the same value only when A and B differ. E Expression I and expression II evaluate to the same value whenever A is true.

D Expression I and expression II evaluate to the same value only when A and B differ.

New cards
5

Consider the following code segment. if (false && true || false) { if (false || true && false) { System.out.print("First"); } else { System.out.print("Second"); } }

if (true || true && false) { System.out.print("Third"); }

What is printed as a result of executing the code segment? A First B Second C Third D FirstThird E SecondThird

C Third

New cards
6

Assume that object references one, two, and three have been declared and instantiated to be of the same type. Assume also that one == two evaluates to true and that two.equals(three) evaluates to false. Consider the following code segment. if (one.equals(two)) { System.out.println("one dot equals two"); } if (one.equals(three)) { System.out.println("one dot equals three"); } if (two == three) { System.out.println("two equals equals three"); } What, if anything, is printed as a result of executing the code segment? A one dot equals two B one dot equals two one dot equals three C one dot equals three two equals equals three D one dot equals two one dot equals three two equals equals three E Nothing is printed.

A one dot equals two

New cards
7

Consider the following code segment. if (a < b || c != d) { System.out.println("dog"); } else { System.out.println("cat"); } Assume that the int variables a, b, c, and d have been properly declared and initialized. Which of the following code segments produces the same output as the given code segment for all values of a, b, c, and d ? A if (a < b && c != d) { System.out.println("dog"); } else { System.out.println("cat"); } B if (a < b && c != d) { System.out.println("cat"); } else { System.out.println("dog"); } C if (a > b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); } D if (a >= b || c == d) { System.out.println("cat"); } else { System.out.println("dog"); } E if (a >= b && c == d) { System.out.println("cat"); } else { System.out.println("dog"); }

E if (a >= b && c == d) { System.out.println("cat"); } else { S

New cards
8

A school that does not have air conditioning has published a policy to close school when the outside temperature reaches or exceeds 95°F. The following code segment is intended to print a message indicating whether or not the school is open, based on the temperature. Assume that the variable degrees has been properly declared and initialized with the outside temperature. if (degrees > 95) { System.out.println("School will be closed due to extreme heat"); } else { System.out.println("School is open"); } Which of the following initializations for degrees, if any, will demonstrate that the code segment may not work as intended? A degrees = 90; B degrees = 94; C degrees = 95; D degrees = 96; E The code will work as intended for all values of degrees.

C degrees = 95;

New cards
9
Consider the following two code segments where the int variable choice has been properly declared and initialized.
Code Segment A
if (choice \> 10)
{
System.out.println("blue");
}
else if (choice < 5)
{
System.out.println("red");
}
else
{
System.out.println("yellow");
}
Code Segment B
if (choice \> 10)
{
System.out.println("blue");
}
if (choice < 5)
{
System.out.println("red");
}
else
{
System.out.println("yellow");
}
Assume that both code segments initialize choice to the same integer value. Which of the following best describes the conditions on the initial value of the variable choice that will cause the two code segments to produce different output?
A choice < 5
B choice \>\= 5 and choice <\= 10
C choice \> 10
D choice \== 5 or choice \== 10
E There is no value for choice that will cause the two code segments to produce different output.

C choice > 10

New cards
10

Consider the following code segment. double regularPrice = 100; boolean onClearance = true; boolean hasCoupon = false;

double finalPrice = regularPrice; if(onClearance) { finalPrice -= finalPrice * 0.25; } if(hasCoupon) { finalPrice -= 5.0; } System.out.println(finalPrice); What is printed as a result of executing the code segment? A 20.0 B 25.0 C 70.0 D 75.0 E 95.0

D 75.0

New cards
11

Consider the following code segment. int x = 7; if (x < 7) { x = 2 * x; } if (x % 3 == 1) { x = x + 2; } System.out.print(3 * x); What is printed as a result of executing the code segment? A 7 B 9 C 14 D 21 E 27

E 27

New cards
12

Assume that the boolean variables a and b have been declared and initialized. Consider the following expression. (a && (b || !a)) == a && b Which of the following best describes the conditions under which the expression will evaluate to true? A Only when a is true B Only when b is true C Only when both a and b are true D The expression will never evaluate to true. E The expression will always evaluate to true.

B Only when b is true

New cards
13

Consider the following code segment. String str1 = new String("Advanced Placement"); String str2 = new String("Advanced Placement");

if (str1.equals(str2) && str1 == str2) { System.out.println("A"); } else if (str1.equals(str2) && str1 != str2) { System.out.println("B"); } else if (!str1.equals(str2) && str1 == str2) { System.out.println("C"); } else if (!str1.equals(str2) && str1 != str2) { System.out.println("D"); } What, if anything, is printed when the code segment is executed? A A B B C C D D E Nothing is printed.

B B

New cards
14

Consider the following code segment in which the int variable x has been properly declared and initialized. if (x % 2 == 1) { System.out.println("YES"); } else { System.out.println("NO"); } Assuming that x is initialized to the same positive integer value as the original, which of the following code segments will produce the same output as the original code segment? I. if (x % 2 == 1) { System.out.print("YES"); } if (x % 2 == 0) { System.out.println("NO"); }

II. if (x % 2 == 1) { System.out.println("YES"); } else if (x % 2 == 0) { System.out.println("NO"); } else { System.out.println("NONE"); }

III. boolean test = x % 2 == 0; if (test) { System.out.println("YES"); } else { System.out.println("NO"); }

A I only B II only C III only D I and II only E I, II, and III

D I and II only

New cards
15

Consider the following code segment. String alpha = new String("APCS"); String beta = new String("APCS"); String delta = alpha;

System.out.println(alpha.equals(beta)); System.out.println(alpha == beta); System.out.println(alpha == delta); What is printed as a result of executing the code segment? A false false false B false false true C true false false D true false true E true true true

D true false true

New cards
16

Consider the following code segment. int start = 4; int end = 5; boolean keepGoing = true;

if (start < end && keepGoing) { if (end > 0) { start += 2; end++; } else { end += 3; } }

if (start < end) { if (end == 0) { end += 2; start++; } else { end += 4; } } What is the value of end after the code segment is executed? A 5 B 6 C 9 D 10 E 16

B 6

New cards
17
Consider the following Boolean expression in which the int variables x and y have been properly declared and initialized.
(x <\= 10) \== (y \> 25)
Which of the following values for x and y will result in the expression evaluating to true ?
A x \= 8 and y \= 25
B x \= 10 and y \= 10
C x \= 10 and y \= 30
D x \= 15 and y \= 30
E x \= 25 and y \= 30

C x = 10 and y = 30

New cards
18

Consider the following statement, which assigns a value to b1. boolean b1 = true && (17 % 3 == 1); Which of the following assigns the same value to b2 as the value stored in b1 ? A boolean b2 = false || (17 % 3 == 2); B boolean b2 = false && (17 % 3 == 2); C boolean b2 = true || (17 % 3 == 1); D boolean b2 = (true || false) && true; E boolean b2 = (true && false) || true;

B boolean b2 = false && (17 % 3 == 2);

New cards
19

Consider the following code segment. int a = 10; int b = 5 * 2; System.out.print(a == b); What is printed as a result of executing the code segment? A 5 B 10 C 10 == 10 D true E false

D true

New cards
20

Consider the following code segments, which are each intended to convert grades from a 100-point scale to a 4.0-point scale and print the result. A grade of 90 or above should yield a 4.0, a grade of 80 to 89 should yield a 3.0, a grade of 70 to 79 should yield a 2.0, and any grade lower than 70 should yield a 0.0. Assume that grade is an int variable that has been properly declared and initialized. Code Segment I double points = 0.0; if (grade > 89) { points += 4.0; } else if (grade > 79) { points += 3.0; } else if (grade > 69) { points += 2.0; } else { points += 0.0; } System.out.println(points); Code Segment II double points = 0.0; if (grade > 89) { points += 4.0; } if (grade > 79) { grade += 3.0; } if (grade > 69) { points += 2.0; } if (grade < 70) { points += 0.0; } System.out.println(points); Which of the following statements correctly compares the values printed by the two methods? A The two code segments print the same value only when grade is below 80. B The two code segments print the same value only when grade is 90 or above or grade is below 80. C The two code segments print the same value only when grade is 90 or above. D Both code segments print the same value for all possible values of grade. E The two code segments print different values for all possible values of grade.

A The two code segments print the same value only when grade is below 80.

New cards
21

Consider the following code segment. int x = 3; int y = -1;

if (x - 2 > y) { x -= y; } if (y + 3 >= x) { y += x; }

System.out.print("x = " + x + " y = " + y);

What is printed as a result of the execution of the code segment? A x = -1 y = -1 B x = 2 y = 1 C x = 3 y = 2 D x = 4 y = -1 E x = 4 y = 3

D x = 4 y = -1

New cards
22

Assume that the boolean variables a, b, c, and d have been declared and initialized. Consider the following expression. !( !( a && b ) || ( c || !d )) Which of the following is equivalent to the expression? A ( a && b ) && ( !c && d ) B ( a || b ) && ( !c && d ) C ( a && b ) || ( c || !d ) D ( !a || !b ) && ( !c && d ) E !( a && b ) && ( c || !d )

A ( a && b ) && ( !c && d )

New cards
23

Consider the following statement. boolean x = (5 < 8) == (5 == 8); What is the value of x after the statement has been executed? A 3 B 5 C 8 D true E false

E false

New cards
24

Consider the following code segment, which is intended to simulate a random process. The code is intended to set the value of the variable event to exactly one of the values 1, 2, or 3, depending on the probability of an event occurring. The value of event should be set to 1 if the probability is 70 percent or less. The value of event should be set to 2 if the probability is greater than 70 percent but no more than 80 percent. The value of event should be set to 3 if the probability is greater than 80 percent. The variable randomNumber is used to simulate the probability of the event occurring. int event = 0;

if (randomNumber <= 0.70) { event = 1; } if (randomNumber <= 0.80) { event = 2; } else { event = 3; } The code does not work as intended. Assume that the variable randomNumber has been properly declared and initialized. Which of the following initializations for randomNumber will demonstrate that the code segment will not work as intended? A randomNumber = 0.70; B randomNumber = 0.80; C randomNumber = 0.85; D randomNumber = 0.90; E randomNumber = 1.00;

A randomNumber = 0.70;

New cards
25

The following method is intended to return true if and only if the parameter val is a multiple of 4 but is not a multiple of 100 unless it is also a multiple of 400. The method does not always work correctly. public boolean isLeapYear(int val) { if ((val % 4) == 0) { return true; } else { return (val % 400) == 0; } } Which of the following method calls will return an incorrect response? A isLeapYear(1900) B isLeapYear(1984) C isLeapYear(2000) D isLeapYear(2001) E isLeapYear(2010)

A isLeapYear(1900)

New cards
26

Consider the following method. 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)) A 0 B 1 C 3 D 6 E 7

D 6

New cards
27

Consider the following code segment. int x = 7; int y = 4; boolean a = false; boolean b = false;

if (x > y) { if (x % y >= 3) { a = true; x -= y; } else { x += y; } }

if (x < y) { if (y % x >= 3) { b = true; x -= y; } else { x += y; } } What are the values of a, b, and x after the code segment has been executed? A a = true, b = true, x = -1 B a = true, b = false, x = 3 C a = true, b = false, x = 7 D a = false, b = true, x = 3 E a = false, b = false, x = 11

C a = true, b = false, x = 7

New cards
28

Which of the following is NOT a relational operator?

?

New cards
29

What does this Java expression evaluate to?

true

New cards
30

Consider the code snippet below. String name = "Karel"; String checkName = new String("Karel"); boolean nameMatches = name == checkName; Note that we forced Java to create a new String object by using new and calling the String constructor.Recall that if you set two String variables to the same String literal, Java tries to be efficient and uses the same object. With this in mind, what will the value of nameMatches be?

false

New cards
31

What is the difference between == and =?

= is used for assignment, while == is used to check for equality.

New cards
32

Which of the following symbols is the "not equal" symbol?

!=

New cards
33

Why do we use if statements in Java?

To do something only if a condition is true

New cards
34

Which if statement is written properly?

if(boolean expression) { // code to execute // code to execute }

New cards
35

What is the output of this program? int phLevel = 9; if(phLevel < 7) { System.out.println("It is acidic!"); } if(phLevel > 7) { System.out.println("It is basic!"); } if(phLevel == 7) { System.out.println("It is neutral!"); }

It is basic!

New cards
36

What is the output of this program? int numTreeRings = 50; System.out.println("How old is the tree?"); if(numTreeRings > 10) { System.out.println("Still young!"); } if(numTreeRings > 40) { System.out.println("Pretty old!"); } if(numTreeRings > 150) { System.out.println("Very old!"); }

How old is the tree?Still young!Pretty old!

New cards
37

What is the output of this program? int numTreeRings = 50; System.out.println("How old is the tree?"); if(numTreeRings < 20) { System.out.println("Still young!"); } if(numTreeRings < 50) { System.out.println("Pretty old!"); } if(numTreeRings < 100) { System.out.println("Very old!"); }

How old is the tree?Very old!

New cards
38

Consider the following code snippet if ( x == y) { // Statement A } else { // Statement B } "` Which statement will be executed if x = 3 and y = 3?

Statement A

New cards
39

Consider the following code snippet if ( x == y) { // Statement A } else { // Statement B } "` Which statement will be executed if x = 15 and y = 20?

Statement B

New cards
40

Choose the answer that will always produce the same output as the if-else statement below. Assume that grams is an int variable that has been declared and initialized earlier in the program. if ( grams < 130) { System.out.println("Your hamster is a healthy weight"); } else { System.out.println("Your hamster is overweight"); }

if(grams < 130) { System.out.println("Your hamster is a healthy weight"); } if(grams >= 130) { System.out.println("Your hamster is overweight"); }

New cards
41

String firstName = "Karel"; String lastName = "The Dog"; if(firstName.length() > lastName.length()) { System.out.println(firstName + " is longer than " + lastName); } else { System.out.println(lastName + " is longer than " + firstName); }

The Dog is longer than Karel

New cards
42

Which of the following statements is true?

An if- else if statement must always start with an if statement.

New cards
43

What is the output of the following code snippet? char combo = 'B'; if(combo == 'A') { System.out.println("Tamale it is!"); } else if (combo == 'B') { System.out.println("Quesadilla it is!"); } else { System.out.println("That is not a combo of ours"); }

Quesadilla it is!

New cards
44

What is the output of the following code snippet? double ticketPrice = 12.75; if(ticketPrice > 15) { System.out.println("Too expensive!"); } else if(ticketPrice > 10) { System.out.println("Typical"); } else if(ticketPrice > 5) { System.out.println("Great deal!"); } else { System.out.println("Must be a scam"); }

Typical

New cards
45

The following code snippet should print the letter grade associated with the integer value in grade.However, the if .- else if statements are in the wrong order. (A) else if (grade < 80) { System.out.println("C"); } (B) else { System.out.println("A"); } (C) if(grade < 70) { System.out.println("D"); } (D) else if (grade < 90) { System.out.println("B"); } What order should these statements be in such that the letter grade is A if the grade is above 90, B if the grade is between 80 and 90, C if the grade is between 70 and 80, and D if the grade is less than 70?

C, A, D, B

New cards
46

Which of the below is a logical operator?

!

New cards
47

What does this Java expression evaluate to? true && !false

true

New cards
48

In the following line of code: boolean shortCircuit = true || (5 / 0 == 0); Will the 5 / 0 == 0 operation be evaluated?

No

New cards
49

In the following line of code: boolean shortCircuit = true && (5 / 0 == 0); Will the 5 / 0 == 0 operation be evaluated?

Yes

New cards
50

What value of x would make this boolean expression evaluate to false? (x < 10) && (x != 5)

Any value greater than or equal to 10

New cards
51

Which of the following logical statements is equivalent to !(A && B) Where A and B are boolean values

!A || !B

New cards
52

Which of the following logical statements is equivalent to !(A || B) Where A and B are boolean values

!A && !B

New cards
53

What boolean value is held in the following boolean variable if hasBike is true and hasHelmet is false? boolean cannotBike = !(hasBike && hasHelmet);

True

New cards
54

What boolean value is held in the following boolean variable if hasHeadlight is true and hasBikelight is false? boolean cannotNightBike = !(hasHeadlight || hasBikelight);

False

New cards
55

Given the following Circle class public class Circle { private int radius; public Circle(int theRadius) { radius = theRadius; } public void setRadius(int newRadius) { radius = newRadius; } public int getRadius() { return radius; } public boolean equals(Circle other) { return radius == other.getRadius(); } } What is the output of the following code snippet? Circle one = new Circle(10); Circle two = new Circle(10); System.out.println(one == two);

false

New cards
56

Given the following Circle class public class Circle { private int radius; public Circle(int theRadius) { radius = theRadius; } public void setRadius(int newRadius) { radius = newRadius; } public int getRadius() { return radius; } public boolean equals(Circle other) { return radius == other.getRadius(); } } What is the output of the following code snippet? public void run() { Circle one = new Circle(5); Circle two = new Circle(10); foo(two); System.out.println(one.equals(two)); } public void foo(Circle x) { x.setRadius(5); }

true

New cards
57

What is the proper way to compare String values in Java?

The .equals() String method

New cards
58

Which of the following Boolean expressions will yield true after the code snippet executes? String str1 = new String("Karel"); String str2 = "CodeHS"; String str3 = "Karel"; str2 = str1;

str1 == str2 && str1.equals(str3)

New cards
59

Reference equality uses the equality operator (==) and compares the references (addresses in memory) of two objects.

True

New cards
60

Logical equality compares the data of the objects.

True

New cards
61

The Car class will contain two string attributes for a car's make and model. The class will also contain a constructor. public class Car { /* missing code / } Which of the following replacements for / missing code */ is the most appropriate implementation of the class?

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

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

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

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

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

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

New cards
62

The Date class below will contain three int attributes for day, month, and year, a constructor, and a setDate method. The setDate method is intended to be accessed outside the class. public class Date { /* missing code / } Which of the following replacements for / missing code / is the most appropriate implementation of the class? A. private int day; private int month; private int year; private Date() { / implementation not shown / } private void setDate(int d, int m, int y) { / implementation not shown */ }

B. private int day; private int month; private int year; public Date() { /* implementation not shown / } private void setDate(int d, int m, int y) { / implementation not shown */ }

C. private int day; private int month; private int year; public Date() { /* implementation not shown / } public void setDate(int d, int m, int y) { / implementation not shown */ }

D. public int day; public int month; public int year; private Date() { /* implementation not shown / } private void setDate(int d, int m, int y) { / implementation not shown */ }

E. public int day; public int month; public int year; public Date() { /* implementation not shown / } public void setDate(int d, int m, int y) { / implementation not shown */ }

C. private int day; private int month; private int year; public Date() { /* implementation not shown / } public void setDate(int d, int m, int y) { / implementation not shown */ }

New cards
63

The Player class below will contain two int attributes and a constructor. The class will also contain a method getScore that can be accessed from outside the class. public class Player { /* missing code / } Which of the following replacements for / missing code / is the most appropriate implementation of the class? A. private int score; private int id; private Player(int playerScore, int playerID) { / implementation not shown / } private int getScore() { / implementation not shown */ }

B. private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown / } private int getScore() { / implementation not shown */ }

C. private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown / } public int getScore() { / implementation not shown */ }

D. public int score; public int id; public Player(int playerScore, int playerID) { /* implementation not shown / } private int getScore() { / implementation not shown */ }

E. public int score; public int id; public Player(int playerScore, int playerID) { /* implementation not shown / } public int getScore() { / implementation not shown */ }

C. private int score; private int id; public Player(int playerScore, int playerID) { /* implementation not shown / } public int getScore() { / implementation not shown */ }

New cards
64

Consider the following Bugs class, which is intended to simulate variations in a population of bugs. The population is stored in the method's int attribute. The getPopulation method is intended to allow methods in other classes to access a Bugs object's population value; however, it does not work as intended. 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? A. The getPopulation method should be declared as private. B. The return type of the getPopulation method should be void. C. The getPopulation method should have at least one parameter. D. The variable population is not declared inside the getPopulation method. E. The instance variable population should be returned instead of p, which is local to the constructor.

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

New cards
65

Consider the following class definition. public class FishTank { private double numGallons; private boolean saltWater;

public FishTank(double gals, boolean sw) { numGallons = gals; saltWater = sw; }

public double getNumGallons() { return numGallons; }

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? A. The variable numGallons is not declared in the getNumGallons method. B. The variable saltWater is not declared in the isSaltWater method. C. The isSaltWater method does not return the value of an instance variable. D. The value returned by the getNumGallons method is not compatible with the return type of the method. E. The value returned by the isSaltWater method is not compatible with the return type of the method.

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

New cards
66

Consider the following class definition. The class does not compile. public class Player { private double score;

public getScore() { return score; }

// Constructor not shown } The accessor method getScore is intended to return the score of a Player object. Which of the following best explains why the class does not compile? A. The getScore method should be declared as private. B. The getScore method requires a parameter. C. The return type of the getScore method needs to be defined as double. D. The return type of the getScore method needs to be defined as String. E. The return type of the getScore method needs to be defined as void.

C. The return type of the getScore method needs to be defined as double.

New cards
67

Consider the following class definition. public class RentalCar { private double dailyRate; // the fee per rental day private double mileageRate; // the fee per mile driven

public RentalCar(double daily, double mileage) { dailyRate = daily; mileageRate = mileage; }

public double calculateFee(int days, int miles) { /* missing code / } } The calculateFee method is intended to calculate the total fee for renting a car. The total fee is equal to the number of days of the rental, days, times the daily rental rate plus the number of miles driven, miles, times the per mile rate. Which of the following code segments should replace / missing code */ so that the calculateFee method will work as intended? A. return dailyRate + mileageRate; B. return (daily * dailyRate) + (mileage * mileageRate); C. return (daily * days) + (mileage * miles); D. return (days * dailyRate) + (miles * mileageRate); E. return (days + miles) * (dailyRate + mileageRate);

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

New cards
68

Consider the following class, which uses the instance variable balance to represent a bank account balance. public class BankAccount { private double balance;

public double deposit(double amount) { /* missing code / } } The deposit method is intended to increase the account balance by the deposit amount and then return the updated balance. Which of the following code segments should replace / missing code */ so that the deposit method will work as intended? A. amount = balance + amount; return amount; B. balance = amount; return amount; C. balance = amount; return balance; D. balance = balance + amount; return amount; E. balance = balance + amount; return balance;

E. balance = balance + amount; return balance;

New cards
69

Consider the BankAccount class below. public class BankAccount { private final String ACCOUNT_NUMBER; private double balance;

public BankAccount(String acctNumber, double beginningBalance) { ACCOUNT_NUMBER = acctNumber; balance = beginningBalance; }

public boolean withdraw(double withdrawAmount) { /* missing code / } } The class contains the withdraw method, which is intended to update the instance variable balance under certain conditions and return a value indicating whether the withdrawal was successful. If subtracting withdrawAmount from balance would lead to a negative balance, balance is unchanged and the withdrawal is considered unsuccessful. Otherwise, balance is decreased by withdrawAmount and the withdrawal is considered successful. Which of the following code segments can replace / missing code */ to ensure that the withdraw method works as intended? I. if (withdrawAmount > balance) { return "Overdraft"; } else { balance -= withdrawAmount; return true; } II. if (withdrawAmount > balance) { return false; } else { balance -= withdrawAmount; return balance; } III. if (withdrawAmount > balance) { return false; } else { balance -= withdrawAmount; return true; } A. I only B. II only C. III only D. I and II only E. I, II, and III

C. III only

New cards
70

Consider the following class declaration. 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? A. Local variables declared inside a method cannot be declared as public or private. B. Local variables declared inside a method must all be private. C. Local variables declared inside a method must all be public. D. Local variables used inside a method must be declared at the end of the method. E. Local variables used inside a method must be declared before the method header.

A. Local variables declared inside a method cannot be declared as public or private.

New cards
71

Consider the following class definition. 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? A. The class is missing an accessor method. B. The instance variables name and number should be designated public instead of private. C. The return type for the Info constructor is missing. D. The variable name is not defined in the changeName method. E. The variable num is not defined in the addNum method.

E. The variable num is not defined in the addNum method.

New cards
72

The class Worker is defined below. The class includes the method getEarnings, which is intended to return the total amount earned by the worker. public class Worker { private double hourlyRate; private double hoursWorked; private double earnings;

public Worker(double rate, double hours) { hourlyRate = rate; hoursWorked = hours; }

private void calculateEarnings() { double earnings = 0.0; earnings += hourlyRate * hoursWorked; }

public double getEarnings() { calculateEarnings(); return earnings; } } The following code segment appears in a method in a class other than Worker. The code segment is intended to print the value 800.0, but instead prints a different value because of an error in the Worker class. Worker bob = new Worker(20.0, 40.0); System.out.println(bob.getEarnings()); Which of the following best explains why an incorrect value is printed? A. The private variables hourlyRate and hoursWorked are not properly initialized. B. The private variables hourlyRate and hoursWorked should have been declared public. C. The private method calculateEarnings should have been declared public. D. The variable earnings in the calculateEarnings method is a local variable. E. The variables hourlyRate and hoursWorked in the calculateEarnings method are local variables.

D. The variable earnings in the calculateEarnings method is a local variable.

New cards
73

The Fraction class below will contain two int attributes for the numerator and denominator of a fraction. The class will also contain a method fractionToDecimal that can be accessed from outside the class. public class Fraction { /* missing code */

// constructor and other methods not shown } Which of the following replacements for /* missing code */ is the most appropriate implementation of the class? A. private int numerator; private int denominator; private double fractionToDecimal() { return (double) numerator / denominator; }

B. private int numerator; private int denominator; public double fractionToDecimal() { return (double) numerator / denominator; }

C. public int numerator; public int denominator; private double fractionToDecimal() { return (double) numerator / denominator; }

D. public double fractionToDecimal() { private int numerator; private int denominator; return (double) numerator / denominator; }

E. public double fractionToDecimal() { public int numerator; public int denominator; return (double) numerator / denominator; }

B. private int numerator; private int denominator; public double fractionToDecimal() { return (double) numerator / denominator; }

New cards
74

The Thing class below will contain a String attribute, a constructor, and the helper method, which will be kept internal to the class. public class Thing { /* missing code / } Which of the following replacements for / missing code */ is the most appropriate implementation of the class?

A. private String str; private Thing(String s) { /* implementation not shown / } private void helper() { / implementation not shown */ }

B. private String str; public Thing(String s) { /* implementation not shown / } private void helper() { / implementation not shown */ }

C. private String str; public Thing(String s) { /* implementation not shown / } public void helper() { / implementation not shown */ }

D. public String str; private Thing(String s) { /* implementation not shown / } public void helper() { / implementation not shown */ }

E. public String str; public Thing(String s) { /* implementation not shown / } public void helper() { / implementation not shown */ }

B. private String str; public Thing(String s) { /* implementation not shown / } private void helper() { / implementation not shown */ }

New cards
75

The Employee class will contain a String attribute for an employee's name and a double attribute for the employee's salary. Which of the following is the most appropriate implementation of the class?

A. public class Employee { public String name; public double salary; // constructor and methods not shown }

B. public class Employee { public String name; private double salary; // constructor and methods not shown }

C. public class Employee { private String name; private double salary; // constructor and methods not shown }

D. private class Employee { public String name; public double salary; // constructor and methods not shown }

E. private class Employee { private String name; private double salary; // constructor and methods not shown }

C. public class Employee { private String name; private double salary; // constructor and methods not shown }

New cards
76

Consider the following definition of the class Student. public class Student { private int grade_level; private String name; private double GPA;

public Student (int lvl, String nm, double gr) { grade_level = lvl; name = nm; GPA = gr; } } Which of the following object initializations will compile without error?

A. Student max = new Student ("Max", 10, 3.75);

B. Student max = new Student (3.75, "Max", 10);

C. Student max = new Student (3.75, 10, "Max");

D. Student max = new Student (10, "Max", 3.75);

E. Student max = new Student (10, 3.75, "Max");

D. Student max = new Student (10, "Max", 3.75);

New cards
77

Consider the following class definition. Each object of the class Employee will store the employee's name as name, the number of weekly hours worked as wk_hours, and hourly rate of pay as pay_rate. public class Employee { private String name; private int wk_hours; private double pay_rate;

public Employee(String nm, int hrs, double rt) { name = nm; wk_hours = hrs; pay_rate = rt; }

public Employee(String nm, double rt) { name = nm; wk_hours = 20; pay_rate = rt; } } Which of the following code segments, found in a class other than Employee, could be used to correctly create an Employee object representing an employee who worked for 20 hours at a rate of $18.50 per hour? I. Employee e1 = new Employee("Lili", 20, 18.5); II. Employee e2 = new Employee("Steve", 18.5); III. Employee e3 = new Employee("Carol", 20);

A. I only B. III only C. I and II only D. I and III only E. I, II, and III

C. I and II only

New cards
78

Consider the following class definition. public class Person { private String name;

/* missing constructor / } The statement below, which is located in a method in a different class, creates a new Person object with its attribute name initialized to "Washington". Person p = new Person("Washington"); Which of the following can be used to replace / missing constructor */ so that the object p is correctly created?

A. private Person() { name = n; }

B. private Person(String n) { name = n; }

C. public Person() { name = n; }

D. public Person(String n) { name = n; }

E. public Person(String name) { String n = name; }

D. public Person(String n) { name = n; }

New cards
79

Consider the following method substringFound, which is intended to return true if a substring, key, is located at a specific index of the string phrase. Otherwise, it should return false. public boolean substringFound(String phrase, String key, int index) { String part = phrase.substring(index, index + key.length()); return part.equals(key); } Which of the following is the best precondition for index so that the method will return the appropriate result in all cases and a runtime error can be avoided? A. 0 <= index < phrase.length()

B. 0 <= index < key.length()

C. 0 <= index < phrase.length() + key.length()

D. 0 <= index < phrase.length() - key.length()

E. 0 <= index < phrase.length() - index

D. 0 <= index < phrase.length() - key.length()

New cards
80
The method addItUp(m, n) is intended to print the sum of the integers greater than or equal to m and less than or equal to n. For example, addItUp(2, 5) should return the value of 2 + 3 + 4 + 5.
/* missing precondition */
public static int addItUp(int m, int n)
{
int sum \= 0;
for (int j \= m; j <\= n; j++)
{
sum +\= j;
}
return sum;
}
Which of the following is the most appropriate precondition for the method?
A.
/* Precondition: m <\= n */

B.
/* Precondition: n <\= m */

C.
/* Precondition: m \>\= 0 and n \>\= 0 */

D.
/* Precondition: m <\= 0 and n <\= 0 */

E.
/* Precondition: m <\= 0 and n \>\= 0 */

A. /* Precondition: m <= n */

New cards
81

Consider the following method. /* missing precondition / public void someMethod(int j, int k, String oldString) { String newString = oldString.substring(j, k); System.out.println("New string: " + newString); } Which of the following is the most appropriate precondition for someMethod so that the call to substring does not throw an exception? A. / Precondition: 0 <= oldString.length() / B. / Precondition: 0 < j and 0 < k / C. / Precondition: 0 <= j and 0 <= k / D. / Precondition: j <= k / E. / Precondition: 0 <= j <= k <= oldString.length() */

E. /* Precondition: 0 <= j <= k <= oldString.length() */

New cards
82

Consider the following class declaration. public class Student { private String name; private int age;

public Student(String n, int a) { name = n; age = a; }

public boolean isOlderThan5() { if (age > 5) { return true; } } } Which of the following best describes the reason this code segment will not compile? A. The return type for the isOlderThan5 method should be void. B. The return type for the isOlderThan5 method should be String. C. The return type for the isOlderThan5 method should be int. D. The isOlderThan5 method is missing a return statement for the case when age is less than or equal to 5. E. The isOlderThan5 method should receive the variable age as a parameter.

D. The isOlderThan5 method is missing a return statement for the case when age is less than or equal to 5.

New cards
83

Consider the following class definition. public class Pet { private String name; private int age;

public Pet(String str, int a) { name = str; age = a; }

public getName() { return name; } } Which choice correctly explains why this class definition fails to compile? A. The class is missing a mutator method. B. The class is missing an accessor method. C. The accessor method is missing a return type. D. The accessor method returns a variable other than an instance variable. E. The instance variables should be designated public instead of private.

C. The accessor method is missing a return type.

New cards
84

Consider the following class. public class Help { private int h;

public Help(int newH) { h = newH; }

public double getH() { return h; } } The getH method is intended to return the value of the instance variable h. The following code segment shows an example of creating and using a Help object. Help h1 = new Help(5); int x = h1.getH(); System.out.println(x); Which of the following statements best explains why the getH method does not work as intended? A. The getH method should have a double parameter. B. The getH method should have an int parameter. C. The getH method should return newH instead of h. D. The getH method should have a return type of int. E. The getH method should have a return type of void.

D. The getH method should have a return type of int.

New cards
85

Consider the following class definition. The method appendIt is intended to take the string passed as a parameter and append it to the instance variable str. For example, if str contains "week", the call appendIt("end") should set str to "weekend". The method does not work as intended. public Class StringThing { private String str;

public StringThing(String myStr) { str = myStr; }

public void appendIt(String s) // line 10 { str + s; // line 12 } } Which of the following changes should be made so that the appendIt method works as intended? A. In line 10, the appendIt method should be declared as return type String. B. Line 12 should be changed to str = s + str;. C. Line 12 should be changed to str = str + s;. D. Line 12 should be changed to return s + str;. E. Line 12 should be changed to return str + s;.

C. Line 12 should be changed to str = str + s;.

New cards
86

Consider the class definition below. The method levelUp is intended to increase a Superhero object's strength attribute by the parameter amount. The method does not work as intended. public class Superhero { private String name; private String secretIdentity; private int strength;

public Superhero(String realName, String codeName) { name = realName; secretIdentity = codeName; strength = 5; }

public int levelUp(int amount) // line 14 { strength += amount; // line 16 } } Which of the following changes should be made so that the levelUp method works as intended? A. In line 14, levelUp should be declared as type void. B. In line 14, amount should be declared as type void. C. Line 16 should be changed to strength + amount;. D. Line 16 should be changed to return strength + amount;. E. Line 16 should be changed to return amount;.

A. In line 14, levelUp should be declared as type void.

New cards
87

Consider the following class definition, which represents two scores using the instance variables score1 and score2. The method reset is intended to set to 0 any score that is less than threshold. The method does not work as intended. public class TestClass { private int score1; private int score2;

public TestClass(int num1, int num2) { score1 = num1; score2 = num2; }

public void reset(int threshold) { if (score1 < threshold) // line 14 { score1 = 0; // line 16 } else if (score2 < threshold) // line 18 { score2 = 0; } } } Which of the following changes can be made so that the reset method works as intended? A. In lines 14 and 18, change < to >. B. In lines 14 and 18, change < to <=. C. In line 16, change score1 to num1 and in line 18, change score2 to num2. D. In line 18, change else if to if. E. In line 18, change else if to else.

D. In line 18, change else if to if.

New cards
88

Consider the following class. The method getTotalSalaryAndBonus is intended to return an employee's total salary with the bonus added. The bonus should be doubled when the employee has 10 or more years of service. public class Employee { private String name; private double salary; private int yearsOfService;

public Employee(String n, double sal, int years) { name = n; salary = sal; yearsOfService = years; }

public double getTotalSalaryAndBonus(double bonus) { /* missing code / } } Which of the following could replace / missing code */ so that method getTotalSalaryAndBonus will work as intended? A. if (years >= 10) { bonus *= 2; } return salary + bonus;

B. if (yearsOfService >= 10) { bonus *= 2; } return salary + bonus;

C. return salary + bonus; D. if (years >= 10) { bonus *= 2; } return sal + bonus;

E. if (yearsOfService >= 10) { bonus *= 2; } return sal + bonus;

B. if (yearsOfService >= 10) { bonus *= 2; } return salary + bonus;

New cards
89

Consider the following class declaration. The changeWeather method is intended to update the value of the instance variable weather and return the previous value of weather before it was updated. public class WeatherInfo { private String city; private int day; private String weather;

public WeatherInfo(String c, int d, String w) { city = c; day = d; weather = w; }

public String changeWeather(String w) { /* missing code / } } Which of the following options should replace / missing code */ so that the changeWeather method will work as intended? A. Sting prev = w; return weather;

B. String prev = weather; return w;

C. String prev = w; return prev;

D weather = w; String prev = weather; return prev;

E. String prev = weather; weather = w; return prev;

E. String prev = weather; weather = w; return prev;

New cards
90

Consider the following class definition. public class BoolTest { private int one;

public BoolTest(int newOne) { one = newOne; }

public int getOne() { return one; }

public boolean isGreater(BoolTest other) { /* missing code / } } The isGreater method is intended to return true if the value of one for this BoolTest object is greater than the value of one for the BoolTest parameter other, and false otherwise. The following code segments have been proposed to replace / missing code /. return one > other.one; return one > other.getOne(); return getOne() > other.one; Which of the following replacements for / missing code */ can be used so that isGreater will work as intended? A. I only

B. II only

C. III only

D. I and II only

E. I, II and III

E. I, II and III

New cards
91

Consider the following class definition. public class Gadget { private static int status = 0;

public Gadget() { status = 10; }

public static void setStatus(int s) { status = s; } } The following code segment appears in a method in a class other than Gadget. Gadget a = new Gadget(); Gadget.setStatus(3); Gadget b = new Gadget(); Which of the following best describes the behavior of the code segment? A. The code segment does not compile because the setStatus method should be called on an object of the class Gadget, not on the class itself. B. The code segment does not compile because the static variable status is not properly initialized. C. The code segment creates two Gadget objects a and b. The class Gadget's static variable status is set to 10, then to 3, and then back to 10. D. The code segment creates two Gadget objects a and b. After executing the code segment, the object a has a status value of 3 and the object b has a status value of 3. E. The code segment creates two Gadget objects a and b. After executing the code segment, the object a has a status value of 3 and the object b has a status value of 10.

C. The code segment creates two Gadget objects a and b. The class Gadget's static variable status is set to 10, then to 3, and then back to 10.

New cards
92

Consider the following class definition. public class Beverage { private int numOunces; private static int numSold = 0;

public Beverage(int numOz) { numOunces = numOz; }

public static void sell(int n) { /* implementation not shown */ } } Which of the following best describes the sell method's level of access to the numOunces and numSold variables? A. Both numOunces and numSold can be accessed and updated. B. Both numOunces and numSold can be accessed, but only numOunces can be updated. C. Both numOunces and numSold can be accessed, but only numSold can be updated. D. numSold can be accessed but not updated; numOunces cannot be accessed or updated. E. numSold can be accessed and updated; numOunces cannot be accessed or updated.

E. numSold can be accessed and updated; numOunces cannot be accessed or updated.

New cards
93

The following class is used to represent shipping containers. Each container can hold a number of units equal to unitsPerContainer. public class UnitsHandler { private static int totalUnits = 0; private static int containers = 0; private static int unitsPerContainer = 0;

public UnitsHandler(int containerSize) { unitsPerContainer = containerSize; }

public static void update(int c) { containers = c; totalUnits = unitsPerContainer * containers; } } The following code segment appears in a method in a class other than UnitsHandler. Assume that no other code segments have created or modified UnitsHandler objects. UnitsHandler large = new UnitsHandler(100); UnitsHandler.update(8); Which of the following best describes the behavior of the code segment? A. The code segment does not compile, because it is not possible to create the object large from outside the UnitsHandler class. B. The code segment does not compile, because it attempts to change the values of private variables from outside the UnitsHandler class. C. The code segment does not compile, because the update method should be called on the object large instead of on the UnitsHandler class. D. The code segment creates a UnitsHandler object called large and sets the static variable unitsPerContainer to 100. The static variables containers and totalUnits each retain the default value 0. E. The code segment creates a UnitsHandler object called large and sets the static variables unitsPerContainer, containers, and totalUnits to 100, 8, and 800, respectively.

E. The code segment creates a UnitsHandler object called large and sets the static variables unitsPerContainer, containers, and totalUnits to 100, 8, and 800, respectively.

New cards
94

Consider the following class, which models a bank account. The deposit method is intended to update the account balance by a given amount; however, it does not work as intended. public class BankAccount { private String accountOwnerName; private double balance; private int accountNumber;

public BankAccount(String name, double initialBalance, int acctNum) { accountOwnerName = name; balance = initialBalance; accountNumber = acctNum; }

public void deposit(double amount) { double balance = balance + amount; } } What is the best explanation of why the deposit method does not work as intended? A. The deposit method must have a return statement. B. In the deposit method, the variable balance should be replaced by the variable initialBalance. C. In the deposit method, the variable balance is declared as a local variable and is different from the instance variable balance. D. The method header for the deposit method should be public void deposit(amount). E. The variable balance must be passed to the deposit method.

C. In the deposit method, the variable balance is declared as a local variable and is different from the instance variable balance.

New cards
95

Consider the following class declaration. public class Student { private String firstName; private String lastName; private int age;

public Student(String firstName, String lastName, int age) { firstName = firstName; lastName = lastName; age = age; }

public String toString() { return firstName + " " + lastName; } } The following code segment appears in a method in a class other than Student. It is intended to create a Student object and then to print the first name and last name associated with that object. Student s = new Student("Priya", "Banerjee", -1); System.out.println(s); Which of the following best explains why the code segment does not work as expected? A. The code segment will not compile because an object cannot be passed as a parameter in a call to println. B. The code segment will not compile because firstName, lastName, and age are names of instance variables and cannot be used as parameter names in the constructor. C. The code segment will not compile because the constructor needs to ensure that age is not negative. D. The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the instance variables inside the constructor. E. The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the local variables inside the constructor.

E. The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the local variables inside the constructor.

New cards
96

Consider the following class definition. public class ClassP { private String str;

public ClassP(String newStr) { String str = newStr; } } The ClassP constructor is intended to initialize the str instance variable to the value of the formal parameter newStr. Which of the following statements best describes why the ClassP constructor does not work as intended? A. The constructor should have a return type of String. B. The constructor should have a return type of void. C. The instance variable str should be designated public. D. The variable str should be designated public in the constructor. E. The variable str should not be declared as a String in the constructor.

E. The variable str should not be declared as a String in the constructor.

New cards
97

Consider the following class definition. public class Contact { private String contactName; private String contactNumber;

public Contact(String name, String number) { contactName = name; contactNumber = number; }

public void doSomething() { System.out.println(this); }

public String toString() { return contactName + " " + contactNumber; } } The following code segment appears in another class. Contact c = new Contact("Alice", "555-1234"); c.doSomething(); c = new Contact("Daryl", ""); c.doSomething(); What is printed as a result of executing the code segment? A. Daryl B. Daryl 555-1234 C. Alice 555-1234 Daryl D. Alice 555-1234 Daryl 555-1234 E. this this

C. Alice 555-1234 Daryl

New cards
98

Consider the following class definition. public class Person { private String name; private int feet; private int inches;

public Person(String nm, int ft, int in) { name = nm; feet = ft; inches = in; }

public int heightInInches() { return feet * 12 + inches; }

public String getName() { return name; }

public String compareHeights(person other) { if (this.heightInInches() < other.heightInInches()) { return name; } else if (this.heightInInches() > other.heightInInches()) { return other.getName(); } else return "Same" } } The following code segment appears in a method in a class other than Person. Person andy = new Person("Andrew", 5, 6); Person ben = new Person("Benjamin", 6, 5); System.out.println(andy.compareHeights(ben)); What, if anything, is printed as a result of executing the code segment? A. Andrew B. Benjamin C. Same D. Nothing is printed because the method heightInInches cannot be called on this. E. Nothing is printed because the compareHeights method in the Person class cannot take a Person object as a parameter.

A. Andrew

New cards
99

Consider the following class definition. public class Email { private String username;

public Email(String u) { username = u; }

public void printThis() { System.out.println(this); }

public String toString() { return username + "@example.com"; } } The following code segment appears in a method in another class. Email e = new Email("default"); e.printThis(); What, if anything, is printed as a result of executing the code segment? A. e

B. default

C. e@example.com

D. default@example.com

E. Nothing is printed because the class will not compile.

D. default@example.com

New cards
100

Consider the following Party class. The getNumOfPeople method is intended to allow methods in other classes to access a Party object's numOfPeople instance variable value; however, it does not work as intended. Which of the following best explains why the getNumOfPeople method does NOT work as intended?

A. The getNumOfPeople method should be declared as public.

New cards

Explore top notes

note Note
studied byStudied by 11 people
Updated ... ago
5.0 Stars(1)
note Note
studied byStudied by 4 people
Updated ... ago
5.0 Stars(1)
note Note
studied byStudied by 9 people
Updated ... ago
5.0 Stars(1)
note Note
studied byStudied by 9921 people
Updated ... ago
4.6 Stars(25)
note Note
studied byStudied by 7 people
Updated ... ago
5.0 Stars(1)
note Note
studied byStudied by 2 people
Updated ... ago
5.0 Stars(1)
note Note
studied byStudied by 10 people
Updated ... ago
5.0 Stars(1)
note Note
studied byStudied by 90 people
Updated ... ago
5.0 Stars(2)

Explore top flashcards

flashcards Flashcard45 terms
studied byStudied by 134 people
Updated ... ago
5.0 Stars(1)
flashcards Flashcard53 terms
studied byStudied by 1 person
Updated ... ago
5.0 Stars(1)
flashcards Flashcard334 terms
studied byStudied by 8 people
Updated ... ago
5.0 Stars(1)
flashcards Flashcard20 terms
studied byStudied by 5 people
Updated ... ago
5.0 Stars(1)
flashcards Flashcard30 terms
studied byStudied by 6 people
Updated ... ago
5.0 Stars(1)
flashcards Flashcard60 terms
studied byStudied by 58 people
Updated ... ago
5.0 Stars(1)
flashcards Flashcard37 terms
studied byStudied by 27 people
Updated ... ago
5.0 Stars(2)
flashcards Flashcard21 terms
studied byStudied by 50 people
Updated ... ago
5.0 Stars(3)