cs121 knowledge checks
How is the expression evaluated? ! x - 3 > 0 (!x) - (3 > 0) (!(x - 3) > 0 !((x - 3) > 0) ((!x) - 3) > 0
((!x) - 3) > 0
Which expression evaluates to 3.5? int x = 7; int y = 1; -(x / 2) * 1.0 -x * (1 / 2) -x.0 / 2 -(x / 2.0)
(x / 2.0)
In the Expression Experimentation activity, you were asked to assign volume4 using the expression below. Which of the following best represents the value generated for volume4? You are welcome to references your observation notes to answer this question. volume4 = 4 / (3 * PI) * radiusCubed; -4.188786666666666 -3.14159 -1.0 -0.42441354006516874
0.42441354006516874
How many objects of type Car are created? Car mustang = new Car();Car prius;int miles;Truck tundra = new Truck(); 2 0 1 3
1
What is y after executing the statements? x = 5; y = x + 1; y = y * 2; 5 6 12 8
12
What is the value of fordFusion's odometer at the end of main( )? public class SimpleCar { private int odometer; public SimpleCar() { odometer = 0; } public SimpleCar(int miles) { odometer = miles; } public void drive(int miles) { odometer = odometer + miles; } public static void main(String[] args) { SimpleCar fordFusion = new SimpleCar(); SimpleCar hondaAccord = newSimpleCar(30); fordFusion.drive(100); fordFusion.drive(20); } }
120
What is the value of x? int y = 9;int z = 3;double x;x = (y / (z + 1.0)); 2 3 Error: The operands are different types and cannot be divided 2.25
2.25
In the Conditional Experimentation activity, which of the following best describe the bug introduced in technique 2 of MinOfThree by replacing the '<=' with '<'.
There are specific input combinations, specifically when the min value is duplicated in two or more fields, that prevents the conditional from matching and updating the min variable. This results in the process ending with the min variable still containing the Integer.MAX_VALUE it was initialized with.
Which statement correctly calls calcArea() with two int arguments? calcArea(int w, int h); calcArea( ); calcArea(4, 12); public void calcArea(int w, int h);
calcArea(4, 12);
The expression that is evaluated at the start of a switch statement must not be which primitive data type below? byte char int short double
double
Mustang is an object of type Car. Which statement invokes drive()? drive(135); Car.drive(150); mustang.drive(145); mustang->drive(115);
mustang.drive(145);
Given: public static void printName(String first, String last) { System.out.println(last + ", " + first); } What is printed with the following method call? printName("Bob","Henderson"); Bob Henderson Henderson, Bob Bob, Henderson Henderson,Bob
Henderson, Bob
Which unchecked exception catches the error in the given code snippet? Object x = new Integer(0); System.out.println( (String) x); UnknownEntityException NullPointerException ArithmeticException ClassCastException
ClassCastException
Which statement is true? Command-line arguments are stored as an array of Strings The value 24 could not be entered as a command-line argument since it is a number Command-line arguments are stored as an array of integers A program typically crashes if the user provides too many command-line arguments
Command-line arguments are stored as an array of Strings
In the ArrayList Experimentation activity, you were asked to add "Purple" to the rainbow ArrayList. Which of the following best describes what happened? You are welcome to references your observation notes to answer this question. Purple was successfully added after Color.PINK using the add() method Purple was successfully added to the tail (end) of the rainbow using the add() method Compilation Error: The method add(Color) in the type ArrayList<Color> is not applicable for the arguments (String) Purple was successfully added to the head (start) of the rainbow using the add() method
Compilation Error: The method add(Color) in the type ArrayList<Color> is not applicable for the arguments (String)
Which expression fails to compute the area of a triangle having base b and height h (area is one-half base time height)? 0.5 * b * h (1 / 2) * b * h (1.0 / 2.0 ) * b * h (b * h) / 2.0
(1 / 2) * b * h
How many object references are declared? Car mustang = new Car();Car prius;int miles;Truck tundra = new Truck(); 3 1 2 0
3
Consider the following snippet of code: System.out.println("30 plus 25 is " + 30 + 25); What is printed by this line? this snippet of code will result in a compiler error 30 plus 25 is 25 30 plus 25 is 55 30 plus 25 is 30 30 plus 25 is 3025
30 plus 25 is 3025
A while statement always executes its loop body at least once.
false
Which method is called? p=processData(9.5,2.3); Neither method is called Both methods could be called, resulting in a compiler error public static int processData(double num,double x){...}; public static int processData(double num, int x){...};
public static int processData(double num,double x){...};
Assume a random number generator object named randGen exists. Which expression is most appropriate for randomly choosing a day of the week? randGen.nextInt(6); randGen.nextInt(8); randGen.nextInt(1); randGen.nextInt(7);
randGen.nextInt(7);
Consider the following snippet of code: Random generator = new Random(); int randNum = generator.nextInt(20) + 1; Which of the following will be true after these lines are executed? these lines will not be executed because a compiler error will result. randNum will hold a number between 0 and 20 inclusive. randNum will hold a number between 1 and 21 inclusive. none of the above randNum will hold a number between 1 and 20 inclusive.
randNum will hold a number between 1 and 20 inclusive.
Which XXX completes countProbation( ) to return the number of students with a GPA below parameter lowGrade? public class Roster { private ArrayList<Student> studentList; public int countProbation(double lowGrade) { int count = 0; for(int i = 0; i < studentList.size(); ++i) { Student s = studentList.get(i); if(XXX < lowGrade) { ++count; } } return count; } } s.getGPA() s getGPA() studentList.getGPA()
s.getGPA()
In the String Experimentation activity, you were asked to print the character index value returned by the indexOf() method to the console. Which of the following best represents the value returned by the indexOf() method when the character does not exist in the String? You are welcome to references your observation notes to answer this question. CharacterNotFoundException 1 0 -1
-1
Which is a Javadoc comment? // comment /** comment */ @author Joan Smith /* comment */
/** comment */
How many Scanner objects should be added to the program? public static String readFirst() { // read first name from input stream } public static String readLast() { // read last name from input stream } public static String readStreet() { // read street address from input stream } public static void main(String[] args) { String personInfo = readFirst() + readLast() + readStreet(); } 1 0 4 3
1
What is output? int cost = Integer.valueOf("1999");Double myScore = 30.8;int yourScore = myScore.intValue();System.out.println(cost + " " + yourScore); 1999 31 1999 30.0 1999 30 Error: incompatible types
1999 30
Which is not a valid identifier? 1stName firstName first_name name1
1stName
For the given program, how many print statements will execute? public static void printShippingCharge(double weight) { if((weight > 0.0) && (weight <= 10.0)) { System.out.println(weight * 0.75); } else if((weight > 10.0) && (weight <= 15.0)) { System.out.println(weight * 0.85); } else if((weight > 15.0) && (weight <= 20.0)) { System.out.println(weight * 0.95); } } public static void main(String[] args) { printShippingCharge(18); printShippingCharge(6); printShippingCharge(25); } 1 3 9 2
2
What is the output, if userVal is 5? int x; x = 100; if( userVal != 0 ) { int tmpVal; tmpVal = x / userVal; System.out.print(tmpVal); } 5 0 Error: The compiler generates an error 20
20
What is the ending value of cost? int numApples = 3;double cost;cost = 1.2 * numApples; 3.6 3.2 3 4
3.6
What is the ending value of the element at index 1? int[] numbers = new int[10]; numbers[0] = 35; numbers[1] = 37; numbers[1] = numbers[0] + 4; 0 39 37 35
39
Which value of y results in short circuit evaluation, causing z == 99 to not be evaluated? (y > 50) || (z == 99) 40 50 No such value 60
60
Consider the following snippet of code: int firstNum = 25; int secondNum = 3; double result = 25 / 3; System.out.println(result); What is output by this code? 8.0 8 This snippet of code will result in a compiler error 8.333333333 8.3
8.0
Which is true? The FileOutputStream class includes println( ) A PrintWriter constructor requires an OutputStream object A FileOutputStream object opens an existing file A PrintWriter object should be closed using close( )
A PrintWriter constructor requires an OutputStream object
Which is true regarding how methods work? After a method returns, its local variables keep their values, which serve as their initial values the next time the method is called If a method returns a variable, the method stores the variable's value until the method is called again A return address indicates the value returned by the method A method's local variables are discarded upon a method's return; each new call creates new local variables in memory
A method's local variables are discarded upon a method's return; each new call creates new local variables in memory
Which is true? An accessor is also known as a setter method A mutator may change class fields A mutator is also known as a getter method Private members can be accessed by a class user
A mutator may change class fields
What does the compiler do upon reaching this variable declaration? int x; Increments x's value by 1 Converts variable x from a double to an integer Initializes x with the value -1 Allocates a memory location for x
Allocates a memory location for x
What is the most likely purpose of someMethod() based on the signature? void someMethod(int[] nums, int value) Create a new array Make a copy of the array Change all array elements to value Return the number of times value occurs in the array
Change all array elements to value
Which is true? The output of println() for an object reference includes all data stored in the object System.output.print() only outputs objects of type String A program must import java.io.system to use System.out Data written to System.out are placed in a buffer and eventually output
Data written to System.out are placed in a buffer and eventually output
In the String Experimentation activity, you were asked to concatenate an int variable called dialCode onto a String literal and print it. Which of the following best represents the result of making this change? You are welcome to references your observation notes to answer this question. System.out.println("Dialing code for Antarctica: " + dialCode); Dialing code for Antarctica: 672 Dialing code for Antarctica: 672 Dialing code for Antarctica: dialCode
Dialing code for Antarctica: 672
What is the ending value of y? Math.pow(u, v) returns u raised to the power of v. x = 2.0; y = 3.0; y = Math.pow(Math.pow(x, y)) + 1.0; Error: The compiler complains about calling pow without the correct number of arguments 8.0 9.0 65.0
Error: The compiler complains about calling pow without the correct number of arguments
What is output given the user input? >three blind mice System.out.print("Enter info: "); Scanner keyboard = new Scanner(System.in); String info = keyboard.nextLine(); Scanner inputScnr =new Scanner(info); int item1 = inputScnr.nextInt(); String item2 = inputScnr.next(); String item3 = inputScnr.next(); System.out.println(item1 + " " + item2 + " " + item1); three blind mice Error: input mismatch exception three three three mice blind three
Error: input mismatch exception
What is output? public class UnitTest { public int square(int value) { return value * 1; } public static void main(String[] args) { UnitTest testObject = new UnitTest(); if(testObject.square(3) != 9) { System.out.println("Error: square(3)"); } if(testObject.square(1) != 1) { System.out.println("Error: square(1)"); } if(testObject.square(-1) != 1) { System.out.println("Error: square(-1)"); } System.out.println("Tests complete."); } } Tests complete. Error: square(3)Tests complete. Error: square(3)Error: square(-1)Tests complete. Error: square(3)Error: square(1)Error: square(-1)Tests complete.
Error: square(3)Error: square(-1)Tests complete.
In the Enum Experimentation activity, you were asked to compare the ordinal values of Flavor.HUCKLEBERRY and Flavor.CHOCOLATE. Which of the following best represents the result of this comparison? You are welcome to references your observation notes to answer this question. Run time error. Ordinal values are unable to be compared using a relational operator. HUCKLEBERRY is greater than CHOCOLATE: true Compile time error. Ordinal values are unable to be compared using a relational operator. HUCKLEBERRY is greater than CHOCOLATE: false
HUCKLEBERRY is greater than CHOCOLATE: true
A double variable stores a value in 64 bits, using some bits for mantissa, some for exponent, and one for sign. Which is true about a double variable? The compiler may sometimes use 63 bits for the mantissa. Limited bits may cause some rounding of the mantissa. If a value is too large for a double, a long should be used instead. If a value is too large for a double, a float should be used instead.
Limited bits may cause some rounding of the mantissa.
What is read into string myString for input "One-hit wonder". myString=scnr.next(); - One- - One-hit wonder - One - One-hit
One-hit
The frequency() method is supposed to return the number of occurrences of target within the array. Identify the location of any errors. public static int[] frequency(int[] nums, int target) { int index; int count = 0; for(index = 0; index < nums.length; ++index) { if(nums[index] == target) { ++count; } } return count; } Only the method body has errors Only the method signature has an error The code has no errors Both the method signature and body have errors
Only the method signature has an error
What does mystery( ) do? void mystery(ArrayList<Integer> nums, int target) { int i; for(i = 0; i < nums.size(); ++i) { if(nums.get(i) == target) { nums.remove(i); i = 0; } } } Results in an index out of bounds error Removes every occurrence of target Nothing, since the for loop is always skipped Removes only the first occurrence of target
Removes every occurrence of target
In the User Input Experimentation activity, you were asked to enter 12.0 when prompted for the number of miles in the GasMilage application. Which of the following best represents the result this user input? You are welcome to references your observation notes to answer this question. The GasMilage application runs as expected. The GasMilage application crashes with an InputMismatchException. Java promotes the miles variable from the int data type to the double data type and runs as expected. Java truncates the double value at the decimal point and stores 12 to the miles variable.
The GasMilage application crashes with an InputMismatchException.
In the Arrays of Objects Experimentation activity, you were asked to modify the compareTo() method in the Grade class as shown here: public int compareTo(Grade arg0) {return arg0.lowerBound - this.lowerBound;} Which of the following best describes the affect that had on the way the grades were sorted (and displayed). You are welcome to references your observation notes to answer this question. The Grade objects in the array were sorted in ascending order and displayed in the console beginning with F and going up from there. The Grade objects in the array were sorted in ascending order and displayed in the console beginning with C- and going up from there. The Grade objects in the array were sorted in descending order and displayed in the console beginning with A+ and going down from there. The Grade objects in the array were not sorted.
The Grade objects in the array were sorted in descending order and displayed in the console beginning with A+ and going down from there.
In the Variable Experimentation activity, you were asked to use the final modifier on the sides variable as shown below. Which of the following best represents the result of making this change? You are welcome to references your observation notes to answer this question. final double sides = 7; - The program ran but displayed the value 7 in all the print statements, ignoring the assignment statements. - The program ran as expected, displaying the correct number of sizes for each geometric shape. - The program ran but displayed the value 12 in all the print statements, ignoring the preceding assignment statements - The build failed (compile time error) stating that the local variable sides cannot be assigned.
The build failed (compile time error) stating that the local variable sides cannot be assigned.
In the File Parsing Experimentation activity, you were asked to swap the lines that extract the artist and title fields from the line of CSV data. Which of the following statements best describes the result of this swap. You are welcome to references your observation notes to answer this question. A runtime error occurred, preventing the program from executing properly The field containing the artist data was stored in the title variable while the field containing the title data was stored in the artist variable. The field containing the artist data was stored in the artist variable while the field containing the title data was stored in the title variable. No change occurred
The field containing the artist data was stored in the title variable while the field containing the title data was stored in the artist variable.
Which of the following best describes what happens when an object no longer has any references pointing to it? The object stays in memory for the remainder of the programs execution. The object is immediately deleted from memory. The object is marked as garbage and its associated memory is freed when the garbage collector runs. The object is overwritten the next time the new operator is called using the same class. The object is overwritten the next time the new operator is called.
The object is marked as garbage and its associated memory is freed when the garbage collector runs.
What is the error in writeFile( )? public static void writeFile() throws IOException { FileOutputStream foStream = null; PrintWriteroutFS = null; foStream = new FileOutputStream(); outFS = new PrintWriter(foStream); outFS.println("Java is my favorite language!"); outFS.flush(); foStream.close(); } oStream has not been flushed outFS has not been closed The output stream has not been properly opened writeFile( ) should throw PrintException
The output stream has not been properly opened
In the Formatting Experimentation activity, you were asked to compare the output of a formatter that uses the "$0.###" pattern to a formatter that uses the "$0.000" pattern. Which of the following best represents the result of this comparison? You are welcome to references your observation notes to answer this question. Compile time error. "$0.000" is not a valid DecimalFormatter pattern The output was nearly identical, but the "$0.000" formatter padded an extra zero to the end of the tax output as shown below: Idaho Tax: $0.060 The output was nearly identical, but the "$0.###" formatter padded an extra zero to the end of the tax output as shown below: Idaho Tax: $0.060 Run time error. "$0.000" is not a valid DecimalFormatter pattern
The output was nearly identical, but the "$0.000" formatter padded an extra zero to the end of the tax output as shown below: Idaho Tax: $0.060
In the Interface Experimentation activity you were asked to implement a number of runtime checks to confirm that *die1* and *die2* are instances of the Rollable interface. You were then asked to remove the code that explicitly stated that the Die class implements the Rollable interface. Which of the following best describe the result of running the GameOfDice program after this change? You are welcome to references your observation notes to answer this question. The program ran as normal because it does not have a dependency upon the Die class The program ran as normal because it still provided a roll() method The program produced the following output: Error: Object is not Rollable The program produced the following output: Error: Object is not Comparable
The program produced the following output: Error: Object is not Rollable
In the Encapsulation Experimentation activity you were asked to change the visibility modifier on the *balance* instance variable in the Account class from private to public. You were then asked attempt to update the balance by directly assigning a value to the instance variable instead of calling the deposit() method. What was the result? You are welcome to references your observation notes to answer this question. An error occurred because it is not possible to directly assign a value to an instance variable, even if it has public visibility The variable remained unchanged because negative values are invalid The variable was reset to zero because negative values are invalid. The value -1000000 was successfully assigned to the variable
The value -1000000 was successfully assigned to the variable
In the Static Method Experimentation activity, you were asked to implement two static methods (numDoubler1 and numDoubler2) then call them with a value stored in a variable named myNum. Which of the following best describe what occurred to the value stored in myNum immediately after the call to numDouber1() and why? The value stored in myNum was doubled. myNum is a global variable so any changes make to it are visible globally. The value stored in myNum was unchanged. All the modifications to the value passed in to the numDoubler1() method were local to that method and no value was returned. The value stored in myNum was doubled. Primitive values are objects that are passed by reference to functions. The value stored in myNum was unchanged. The value returned by the call to numDoubler1() was not assigned to a variable.
The value stored in myNum was unchanged. All the modifications to the value passed in to the numDoubler1() method were local to that method and no value was returned.
In the For Loop Experimentation activity you were asked to replace the "I'm here!" for-loop with a *while-loop*. What did this do? This change doubled the number of times that "I'm here!" was displayed in the console. The provided *while-loop* executes half as many times as the original inner *for-loop* that was replaced, but the outer *for-loop* executes four times as many times as it did originally. This change had no effect on the behavior of the program. The inner *for-loop* was never executed and *while-loop* that replaced it was never executed either. This change doubled the number of times that "I'm here!" was displayed in the console. The provided *while-loop* executes twice as many times as the original *for-loop* that was replaced. This change had no effect on the behavior of the program. The provided *while-loop* was functionally equivalent to the inner *for-loop* that was replaced.
This change had no effect on the behavior of the program. The provided *while-loop* was functionally equivalent to the inner *for-loop* that was replaced.
Which is true about testing a method with three integer parameters and one integer return value? Each test case should include a negative value as a parameter Using a variety of calls involving assert() is a good way to test the method A good programmer would test all possible input values Three test vectors are likely sufficient
Using a variety of calls involving assert() is a good way to test the method
How does using findMax() improve the code? public static int findMax(int val1,int val2) { int max; if(val1 > val2) { max = val1; } else { max = val2; } return max; } public static void main(String[] args) { int max1; int max2; int max3; max1 = findMax(15,7); max2 = findMax(100,101); max3 = findMax(20,30); }
Using findMax() decreases redundant code
To assign a value stored in a double variable to an int variable, use promotion a print statement nothing. Java will do this automatically a cast operator a widening conversion
a cast operator
A(n) ___________________ object is one that is made up, at least in part, of other objects. static aggregate public encapsulated private
aggregate
Which of the following array declarations are invalid? int[] grades = { 91, 83, 42, 100, 77 }; int[] grades = new int[5]; int grades[] = new int[5]; all of the above are valid none of the above are valid
all of the above are valid
12A character variable's value is stored in memory as _____ . a string a floating-point value an integer value a graphical symbol
an integer value
Which XXX tests the input value 4 for squareNum()? public static int squareNum(int origNum) { return origNum * origNum; } public static void main(String[] args) { System.out.println("Testing started"); XXX; System.out.println("Testing completed"); } squareNum(4) test(4) assert(test(4)==16):"4, expecting 16, got: "+test(4); assert(squareNum(4)==16):"4, expecting 16, got: "+squareNum(4);
assert(squareNum(4)==16):"4, expecting 16, got: "+squareNum(4);
A static main( ) ___. can not be included within a programmer-defined class can call instance methods without an object can declare and create objects has direct access to class instance members
can declare and create objects
Which catch syntax handles the unchecked exception, ArithmeticException? catch (ArithmeticException except) catch (Exception except) catch (Exception ArithmeticException except) catch (Exception ArithmeticException)
catch (ArithmeticException except)
Which of the following is a correct declaration of enumerated type for the suits of a deck of cards? enum Suit {hearts, spades, diamonds, clubs }; enum Suit = { hearts, spades, diamonds, clubs } enumerated type Suit = {hearts, spades, diamonds, clubs }; enumerated type Suit = { hearts, spades, diamonds, clubs };
enum Suit {hearts, spades, diamonds, clubs };
An array cannot hold object types.
false
An infinite loop is a compile-time error.
false
An object can be thought of as a blueprint for a set of classes.
false
ArrayLists store copies of the objects that are added to them, not references to those objects.
false
Enumerated types allow a programmer to treat primitive data as objects.
false
If an array is declared to hold objects, none of the objects can have instance variables that are arrays.
false
The print and the println methods are identical and can be used interchangeably.
false
Which modifier must be used in the declaration of a variable to make it a constant? -public -static -final -void -private
final
Which declaration assigns a variable with 5 such that the value can be later changed? final int = 5; int NUM_ITEMS = 5; final int NUM_ITEMS = 5; int numItems = 5;
int numItems = 5;
Which of the following is a valid declaration for a two-dimensional array? int[]** matrix; int[2] matrix; none of these are correct int[][] matrix; int[] matrix;
int[][] matrix;
A(n) _________________ is an object that has methods that allow you to process a collection of items one at a time. palindrome nested loop iterator conditional loop
iterator
what is output? public class StringLength { public static void lengthFun(Stringstr) { int length = str.length(); System.out.println("Length : "+length); } public static void main(String[] args) { try { String str = null; lengthFun(str); } catch(Exception except) { System.out.println(except); } } } 4 null java.lang.NullPointerException java.lang.ArithmeticException
java.lang.NullPointerException
newNum is an Integer object that holds an int value. Which expression below returns the value in newNum as a double value? newNum.doubleValue() newNum.toDouble(); Double.newNum(); newNum.double(); There is no way to return the value as a double.
newNum.doubleValue()
Which of the following are examples of invalid string literals? -"Hello World!" -" " -"4 score and 7 years ago, our forefathers brought forth..." -"z" -none of the above
none of the above
What is stored in score1, score2, and grade? Integer score1 = 72; int score2 = 85; Character grade = 'C'; 72, 85, C obj reference, 85, obj reference obj reference, obj reference, C obj reference, obj reference, obj reference
obj reference, 85, obj reference
A(n) ________________ is a piece of data that we send to a method. expression escape sequence object service parameter
parameter
Select the default constructor signature for a Student class. public void Student( ) public Student( ) private void Student( ) private Student( )
public Student( )
Which XXX method signature returns the student's GPA? public class Student { private double myGPA; private int myID; XXX { return myGPA; } } public int getGPA( ) public double getGPA( ) private double getGPA( ) double getGPA( )
public double getGPA( )
Which element of an ArrayList named myList is accessed with the following command? Assume that the ArrayList has been properly declared, instantiated and loaded with items. myList.get(2); the first element the third element the second element the fourth element
the third element
The ________________ reference always refers to the currently executing object. actual final static null this
this
A return statement is not required at the end of every method.
true
In a class that has variables called height and width, methods called getHeight() and getWidth() are examples of accessor methods.
true
In the following ArrayList declaration, the Color tag specifies that the ArrayList can ONLY store Color objects ArrayList<Color> myList;
true
Multiple reference variables can refer to the same object.
true
The Math class is part of the java.lang package.
true
The Scanner class must be imported using the import statement before it can be used in a program.
true
The value of a primitive datatype variable may be assigned to an object of the corresponding wrapper class, and vice-versa.
true
All methods (with the exception of constructors) must specify a return type. What is the return type for a method that does not return any values? void double none of the above public int
void
Which expressions for YYY and ZZZ correctly output the indicated ranges? Assume int x's value will be 0 or greater. Choices are in the form YYY / ZZZ. if( YYY ) { // Output "0-29" } else if( ZZZ ) { // Output "30-39" } else { // Output "40+" } x < 30 / x < 40 x > 29 / x > 40 x < 30 / x >= 30 x < 29 / x >= 29
x < 30 / x < 40