AP Computer Science Midterm

¡Supera tus tareas y exámenes ahora con Quizwiz!

False

Given int answer = 5; then after answer %= 8; is executed, answer = 3. (true or false)

A

Given that s is a String, what does the following loop do? for(int j = s.length( ); j > 0; j --) System.out.print(s.charAt(j - 1)); A) it prints s out backwards B) it prints s out forwards C) it prints s out backwards after skipping the last character D) it prints s out backwards but does not print the 0th character E) it yields a run-time error because there is no character at s.charAt(j - 1) for j = 0

D

Given two String variables, s1 and s2, to determine if they are the same length, which of the following conditions would you use? A) (s1.equals(s2)) B) (s1.length( ).equals(s2)) C) (s1.length( ).equals(s2.length( )) D) (s1.length( ) == s2.length( )) E) length(s1) == length(s2)

method overloading (When methods share the same name, they are said to be overloaded. The number and type of parameters passed in the message provides the information by which the proper method is called)

Having multiple class methods of the same name where each method has a different number of or type of parameters is known as ______.

D

How many stars are output when this code segment is executed? for (int k = 0; k < 10; k++) for (int j = 0; j < 5; j++) System.out.print("*"); A) 5 B) 10 C) 15 D) 50 E) 500

B

If x is an int and y is a double, all of the following are legal except which assignment statement? A) y = x; B) x = y; C) y = (double) x; D) x = (int) y; E) all of the above are legal

False

If x is the String "Hi There", then x.toUpperCase( ); will return the original version of x (true or false)

False

If you want to use keyboard input, you must import the java.lang package (true or false)

False

In order to create a constant, you would use the reserved word static (true or false)

A piano has 88 keys.

public class PianoKeys { public static void main (String[] args) { int keys = 88; System.out.println("A piano has " + keys + " keys."); //this is one line but wouldn't fit } }

C

public class Questions1_4 { public static void main(String[] args) { System.out.print("Here"); System.out.println("There " + "Everywhere"): System.out.println("But not" + "in Texas"); } } The program will print the word "Here" and then print A) "There Everywhere" on the line after "Here" B) "There" on the line after "Here" and "Everywhere" on the line after "There" C) "There Everywhere" on the same line as "Here" D) "ThereEverywhere" on the same line as "Here" E) "ThereEverywhere" on the line after "Here"

variable declaration

tells the compiler to reserve a portion of main memory space large enough to hold the value and what name to call the location

string literal

text in double quotes

print

the _________ method prints the information sent to it, but does not go to the next line when completed

println

the __________ method prints the information sent to it, then moves to the beginning of the next line

()

What is a mutator method? A A method that has the same name, but different parameters, as another method. B A method that modifies a value. C A method that does not return a value. D A method that is called when an object is first created. E A method that provides read-only access to a value.

23 and 45 concatenated: 2445

What is the output? System.out.println("24 and 35 concatenated: " 24 + 45);

24 and 45 added: 69

What is the output? System.out.println("24 and 45 added: " + (24 + 45));

E

What value will z have if we execute the following assignment statement? double z = 50/10.00; A) 5 B) 5.0 C) 50 D) 10 E) none of the above, a run-time error arises because z is an int and 50/10.00 is not

A

What value with z have if we execute the following statement? double z = 5/10; A) z will equal 0.0 B) z will equal 0.5 C) z will equal 5.0 D) z will equal 0.05 E) none of the above, a run-time error arises because z is a double and 5/10 is an int

B

What will be the result of the following assignment statement? Assume b = 5 and c = 10 int a = -b * (c + 2) / 2; A) 30 B) -30 C) 20 D) -20 E) -6

E

Which of the following best describes the circumstances under which the expression !(a && b) && (a | | b) evaluates as true? A) Always B) Never C) Whenever both a and b are true D) When neither a nor b are true E) Whenever exactly one of a and b is true

E

Which of the following is true about the following code segment? int x = 0; boolean y = true; if (y && (x != 0) && (2/x == 0)) System.out.println("success"); else System.out.println("failure"); A) There will be an error when the code is compiled because the first && operator is applied to a non-boolean expression B) There will be an error when the code is compiled because a boolean variable (y) and an int variable (x) appear in the same if statement C) There will be an error when the code is executed because of an attempt to divide by 0 D) The code will compile and execute without error; the output will be "success" E) The code will compile and execute without error; the output will be "failure"

D

Which of the following would return the last character of the String x? A) x.charAt(0); B) x.charAt(last); C) x.charAt(length(x)); D) x.charAt(x.length( )-1); E) x.charAt(x.length( ));

True

With an enumerated type, the programmer defines the possible values of the type. (true or false)

assignment statement

gives or assigns a value to a variable

constants

identifiers and are like variables except that they always have the same value

undefined

if you don't give an initial value for a variable, the variable is

Student s1 = new Student("Jane Doe", "Computer Science", 3.333, 33); (To instantiate a class, the object is assigned the value returned by calling the constructor preceded by the reserved word new, as in new Student( ). The constructor might require parameters, and for Student, the parameters must be are two String values, a double, followed by an int.)

import java.text.DecimalFormat; public class Student { private String name; private String major; private double gpa; private int hours; public Student(String newName, String newMajor, double newGPA, int newHours) { name = newName; major = newMajor; gpa = newGPA; hours = newHours; } public String toString( ) { DecimalFormat df = new DecimalFormat("xxxx"); // xxxx needs to be replaced return name + "\n" + major + "\n" + df.format(gpa) + "\n" + hours } } Which of the following could be used to instantiate a new Student s1?

s1.getClassRank( ); (To call a method of an object requires passing that object a message which is the same as the method name, as in object.methodname(parameters). In this situation, the object is s1, the method is getClassRank, and this method expects no parameters)

import java.text.DecimalFormat; public class Student { private String name; private String major; private double gpa; private int hours; public Student(String newName, String newMajor, double newGPA, int newHours) { name = newName; major = newMajor; gpa = newGPA; hours = newHours; } public String toString( ) { DecimalFormat df = new DecimalFormat("xxxx"); // xxxx needs to be replaced return name + "\n" + major + "\n" + df.format(gpa) + "\n" + hours } } Assume that another method has been defined that will compute and return the student's class rank (Freshman, Sophomore, etc). It is defined as: public String getClassRank( ) Given that s1 is a student, which of the following would properly be used to get s1's class rank?

C

import java.util.Scanner; public class Questions { public static void main(String[] args) { int x, y, z; double average; Scanner scan = new Scanner (System.in); System.out.println("Enter an integer value"); x = scan.nextInt( ); System.out.println("Enter another integer value"); y = scan.nextInt( ); System.out.println("Enter a third integer value"); z = scan.nextInt( ); average = (x + y + z) / 3; System.out.println("The result of my calculation is " + average); } } What does this program compute? A) the correct average of x, y, and z as a double B) the correct average of x, y, and z as an int C) the average of x, y, and z as a double, but the result may not be accurate D) the sum of z, y, and z E) the remainder of the sum of x, y, and z divided by 3

software reuse

inheritance is a form of

\n

new line escape sequence

objects

once a class had been defined, what can be created from that class?

method

println is a(n)

\t

tab escape sequence

False

A Java variable is the name of a data value stored in memory that cannot change during the program's execution (true or false)

class (fill in blank)

A ____ contains no space to store data, generally

D

A cast is required in which of the following situations? A) using charAt to take an element of a String and store it in a char B) storing an int in a double C) storing a double in a double D) storing a double in an int E) All of the above require casts

how an object is initialized (The constructor should be used to "construct" the object, that is, to set up the initial values of the instance data. This is not essential, but is typically done. The interface of an object is dictated by the visibility modifiers used on the instance data and methods)

A class' constructor usually defines _______.

local variable (Local variables are those that are "local" to the method in which they have been declared, that is, they are accessible only inside that method. Global variables are those that are accessible from anywhere, while parameters are the variables passed into a method. Instance data can be thought of as global variables for an entire object)

A variable whose scope is restricted to the method where it was declared is known as a(n) ______.

True

An enumerated type defined by "enum Grade {A, A-, B+, B, B-, C, D, F}" is invalid (true or false)

equals (The length and toUpperCase messages do not have parameters and substring has one or two int parameters. For equals, a String must be passed as a parameter so that the String receiving the message can be compared to the String passed as a parameter)

An example of passing a message to a String where the message has a String parameter occurs in which of the following messages?

True

An if statement may or may not have an else clause, but an else clause must be part of an if statement. (true or false)

public void updateHours(int moreHours) { hours += moreHours; } (This method will receive the number of new hours and add this to the current hours)

Another method that might be desired is one that updates the Student's number of credit hours. This method will receive a number of credit hours and add these to the Student's current hours. Which of the following methods would accomplish this? A) public void updateHours( ) { hours++; } B) public void updateHours(int moreHours) { hours += moreHours; } C) public int updateHours(int moreHours) { return hours + moreHours; } D) public int updateHours( ) { return hours; } E) public updateHours(int moreHours) { hours += moreHours; }

E

Assume that x is an initialized int variable. This code segment is equivalent to which of the following code segments? if (x > 5) x*=2; if (x > 10) x = 0; A) x = 0; B) if (x > 5) x = 0; C) if (x > 5) x *= 2; D) if (x > 5) x = 0; else x *= 2; E) if (x > 5) x*= 2; else if (x > 10) x = 0;

string concatenation

Combining several strings into a single string, or combining a string with other data into a new, longer string using the (+) operator

all are legal except doublefoo(0.1, 0.2); (In the case of doublefoo(0), the value 0 (an int) is widened to a double. In the case of doublefoo(0.1 + 0.2), the addition is performed yielding 0.3 and then doublefoo is called. The parameter list in doublefoo(0.1, 0.2) is illegal since it contains two double parameters instead of 1)

Consider a method defined with the header: public void doublefoo(double x). Which of the following method calls is legal? A doublefoo(0); B all are legal except doublefoo(0.1, 0.2); C doublefoo(0.555); D doublefoo(0.1, 0.2); E doublefoo(0.1 + 0.2);

foo(0 / 1, 2 * 3); (The only legal method call is one that passes two int parameters. 0 / 1 is an int division (equal to 0) and 2 * 3 is an int multiplication. So this is legal)

Consider a method defined with the header: public void foo(int a, int b). Which of the following method calls is legal? A foo( ); B foo(0 / 1, 2 * 3); C foo(1 + 2, 3 * 0.1); D foo(0, 0.1); E foo(0);

m2 (Once a method terminates, control resumes with the method that called that method. In this case, m2 calls m4, so that when m4 terminates, m2 is resumed.)

Consider a sequence of method invocations as follows: main calls m1, m1 calls m2, m2 calls m3 and then m2 calls m4, m3 calls m5. If m4 has just terminated, what method will resume execution?

B

Consider the following code segment. Assume x, y, and z are int variables and that x and y have been initialized. Which of the statements best described what this code segment does? if (y < 0) { x = -x; y = -y; } z = 0; while (y > 0) { z += x; y --; } A) Sets z to be the sum x + y B) Sets z to be the product of x*y C) Sets z to be the absolute value of x D) Sets z to be the value of x^y E) Sets z to be the value of y^x

A syntax error (The Die class has two constructors, one that receives no parameters and one that receives a single int parameter. The instruction above calls the Die constructor with 2 int parameters. Since no constructor matches this number of parameters exists, a syntax error occurs)

Constructor 1: public class Die() { numFaces = 6; faceValue = 1; } Constructor 2: public Die(int faces) { if(faces<MIN_FACES) numFaces = 6; else numFaces = faces; faceValue = 1; } The Die class from chapter 4 has two constructors defined as follows. Assume MIN_FACES is an int equal to 4. The instruction Die d = new Die(10, 0); results in: A) The Die d having numFaces = 6 and faceValue = 10 B) A syntax error C) The Die d having numFaces = 10 and faceValue = 1 D) The Die d having numFaces = 6 and faceValue = 1 E) The Die d having numFaces = 10 and faceValue = 10

The Die d having numFaces = 10 and faceValue = 1 (Since an int parameter is passed to the constructor, the second constructor is executed, which sets numFaces = 10 (since numFaces >= MIN_FACES) and faceValue = 1)

Constructor 1: public class Die() { numFaces = 6; faceValue = 1; } Constructor 2: public Die(int faces) { if(faces<MIN_FACES) numFaces = 6; else numFaces = faces; faceValue = 1; } The Die class from chapter 4 has two constructors defined in the picture. Assume MIN_FACES is an int equal to 4. The instruction Die d = new Die(10); results in: A) The Die d having numFaces = 6 and faceValue = 1 B) The Die d having numFaces = 6 and faceValue = 10 C) The Die d having numFaces = 10 and faceValue = 10 D) A syntax error E) The Die d having numFaces = 10 and faceValue = 1

Characteristics and behaviors

Every object has

Because they will only be called from methods inside of Rational (All items of a class that are declared to be private are only accessible to entities within that class, whether they are instance data or methods. In this case, since these two methods are only called from other methods (including the constructor) of Rational, they are declared private to promote information hiding to a greater degree)

In the Rational class, defined in chapter 4, the methods reduce and gcd are declared to be private. Why? A) Because they do not use any of Rational's instance data B) Because they will never be used C) Because they will only be called from methods inside of Rational D) Because they will only be called from the constructor of Rational E) Because it is a typo and they should be declared as public

C

In the String major = "Computer Science", which is returned by major.charAt(2)? A) 'C' B) 'o' C) 'm' D) "C" E) "Computer"

may be primitive types or objects (The instance data are the entities that make up the class and may be any type available whether primitive or object, and may be public or private. By using objects as instance data, it permits the class to be built upon other classes. This relationship where a class has instance data that are other classes is known as a has-a relationship)

Instance data for a Java class ______.

String = ("That test was hard!");

Provide an example of how you might use a String to store information about a high school student

char = 'A'; (//Math grade)

Provide an example of how you might use a char to store information about a high school student

double = 78.4; (//Science Grade)

Provide an example of how you might use a double to store information about a high school student

int = 78; (//Science Grade)

Provide an example of how you might use an int to store information about a high school student

D

Since you cannot take the square root of a negative number, you might use which of the following instructions to find the square root of the variable x? A) Math.sqrt(x*x); B) Math.sqrt((int) x); C) Math.abs(Math.sqrt(x)); D) Math.sqrt(Math.abs(x)); E) Math.sqrt(-x);

False

Suppose that String name = "Frank Zappa". Then the instruction name.replace('A', 'I'); will return "FrInk ZIppI". (true or false)

object

System.out is a(n)

the percentage of heads flipped out of 1000 flips (The code iterates 1000 times, flipping the Coin and testing to see if this flip was a 0 ("Heads") or 1 ("Tails"). The variable num counts the number of Heads and the variable value is then the percentage of Heads over 1000)

The Coin class, as defined in Chapter 4, consists of a constructor, and methods flip, isHeads and toString. The method isHeads returns true if the last flip was a Heads, and false if the last flip was a Tails. The toString method returns a String equal to "Heads" or "Tails" depending on the result of the last flip. What does the following code compute? int num = 0; for(int j = 0; j < 1000; j++) { c.flip( ); if(c.isHeads()) num++; } double value = (double) num / 1000; A) the percentage of times neither Heads nor Tails were flipped out of 1000 flips B) the number of Heads flipped out of 1000 flips C) nothing at all D) the percentage of heads flipped out of 1000 flips E) the number of Heads flipped in a row out of 1000 flips

c.flip( ); if(c.toString( ).equals(guess)) System.out.println("User is correct"); (c.flip( ) must be performed first to get a Coin flip. Next, the user's guess is compared against the value of the Coin's flip. The Coin c stores the result as an int and the user's guess is a String. Using getFace( ) returns the int value but using the toString method will return the String "Heads" or "Tails". So, the code compares c.toString( ) with the user's guess using the String method equals)

The Coin class, as defined in Chapter 4, consists of a constructor, and methods flip, isHeads and toString. The method isHeads returns true if the last flip was a Heads, and false if the last flip was a Tails. The toString method returns a String equal to "Heads" or "Tails" depending on the result of the last flip. A set of code has already instantiated c to be a Coin and has input a String guess, from the user asking whether the user guesses that a coin flip will result in "Heads" or "Tails". Which of the following sets of code will perform the coin flip and see if the user's guess was right or wrong? A) c.flip( ).toString( ); if(c.equals(guess)) System.out.println("User is correct"); B) if(c.flip( ).equals(guess)) System.out.println("User is correct"); C) c.flip( ); if(c.isHeads( ).equals(guess)) System.out.println("User is correct"); D) c.flip( ); if(c.toString( ).equals(guess)) System.out.println("User is correct"); E) if(c.isHeads( ).equals(guess)) System.out.println("User is correct");

B

The expression !(a && b) is logically equivalent to which of the following expressions? A) (!a) && (!b) B) (!a) | | (!b) C) !(a | | b) D) (a | | b) E) (a | | b) && (a && b)

False

The expression a | | b will be true if either a or b is true but not if both are true. (true or false)

False

The following for loop is an infinite loop for (int j = 0; j < 1000;) i ++; (true or false)

True

The four stages of software development are determining the program requirements, designing a solution, writing the program code and debugging the program code. (true or false)

polymorphism

The idea that we can refer to objects of different but related types in the same way

Primitive data, objects

The information we manage in a Java program is either represented as _________ _______ or _________ (answers separated by a comma)

False

The mod operator, %, can only be performed on int values and its result is a double (true or false)

False

The relational operators < and > can be used to tell whether one string comes before another alphabetically. (true or false)

Enter eggs needed >> You ordered 50 eggs. That's 4 dozen at $3.25 per dozen and 2 loose eggs at 45 cents each for a total of $13.90

Write the output of the following program: import java.util.Scanner; public class Eggs { public static void main(String[] args) { final int DOZEN = 12; final double PRICE_PER_DOZEN = 3.25; final double PRICE_PER_EGG = 0.45; int eggs; int dozens; int leftOver; double total; Scanner input = new Scanner(System.in); System.out.print("Enter eggs needed >> "); eggs = input.nextInt( ); dozens = eggs / DOZEN; leftOver = eggs % DOZEN; total = dozens * PRICE_PER_DOZEN + leftOver * PRICE_PER_EGG; System.out.println("You ordered " + eggs + " eggs. That's " + dozens + " dozen at $" + PRICE_PER_DOZEN + " per dozen and " + leftOver + " loose eggs at " + (int) (PRICE_PER_EGG * 100) + "cents each for a total of $" + total); } }

object

a character string is a(n) __________ in java

method

a group of programming statements that is given a name so that we can use it when we need it

one

a variable can store _______ value(s) of its declared type

object (fill in the blank)

a(n) _________ is defined by a class

object

a(n) ___________ is an abstraction

the data type of the object

class (book definition)

derived classes

class that has data from a higher class

final modifier

comes before the declaration and causes the variables to be declared as named constants whose values cannot be changed

Primitive Data

common values such as numbers and characters

uppercase

constants use _________ letters

Data type

defines a set of values and operations

encapsulation

each object protects and manages its own information

parameter

each piece of data that we send to a method is called a

"00" (The toString method compares x and z, and if x < y it returns the String y. In this case, x == z, so the else clause is executed, and the String of "" + x + z is returned. This is the String "00")

public class Swapper { private int x; private String y; public int z; public Swapper(int a, String b, int c) { x = a; y = b; z = c; } public String swap( ) { int temp = x; x = z; z = temp; return y; } public String toString( ) { if (x < z) return y; else return "" + x + z; } } If the instruction Swapper s = new Swapper(0, "hello", 0); is executed followed by s.toString( ); what value is returned from s.toString( )? A) "0" B) "hello00" C) "hello" D) "00" E) 0

"no" (The swap method swaps the values of x and z (thus x becomes 10 and z becomes 5) and returns the value of y, which is "no" for r)

public class Swapper { private int x; private String y; public int z; public Swapper(int a, String b, int c) { x = a; y = b; z = c; } public String swap( ) { int temp = x; x = z; z = temp; return y; } public String toString( ) { if (x < z) return y; else return "" + x + z; } } If we have Swapper r = new Swapper (5, "no", 10); then r.swap( ); returns which of the following? A "15" B "no" C "no510" D nothing E "510"

The instance data z is visible outside of Swapper (We would expect none of the instance data to be visible outside of the class, so they should all be declared as "private" whereas we would expect the methods that make up the interface to be visible outside of the class, so they should all be declared as "public". We see that z is declared "public" instead of "private")

public class Swapper { private int x; private String y; public int z; public Swapper(int a, String b, int c) { x = a; y = b; z = c; } public String swap( ) { int temp = x; x = z; z = temp; return y; } public String toString( ) { if (x < z) return y; else return "" + x + z; } } Which of the following criticisms is valid about the Swapper class? A The instance data z is visible outside of Swapper B The instance data y is visible outside of Swapper C The instance data x is visible outside of Swapper D None of the methods are visible outside of Swapper E All 3 instance data are visible outside of Swapper

// Precondition: age >= 0 (A precondition is a condition that should be true BEFORE a method begins executing. // Precondition: age >= 0 is the best choice since age should be >= 0 for the results of the method to make sense)

public int dogYears (int age) { if (age >= 0) return age * 7; else return 0; } What would be an appropriate precondition for the method? A // Precondition: age >= 0 B // Precondition: age is an int C // Precondition: tells how old your dog is D // Precondition: returns age * 7 E // Precondition: age is someone's age

escape sequences

special sequences involving the backslash character

inheritance

the definition of one class can be based on another class that already exists

abstraction

the details of how it works don't matter to the user of the object

behaviors

the methods of an object define its

class

the model or blueprint from which an object is created (establishes the kind of data an object of that type will hold and defines the methods that represent the behavior of such objects or the operations that can be performed on them)

variable

the name for a location in memory used to hold a data value

attributes

the values that an object stores internally (may be primitive data or other objects), representing its state are its

executed

when a method is called, its statements are


Conjuntos de estudio relacionados

(Practice) Ch. 1 - Introduction to Real Estate

View Set

SOC 307: Criminology Exam I - Ch. 1-5

View Set

AWS Certified Solutions Architect Professional (+ review)

View Set