Java CS 170
138 flashcards · Programming Languages · by Karthikeyan Palaniyandi
Where do parameters and local variables belong? in an object in a package in a class in a method
in a method
All hamsters are rodents and all rodents are mammals. What hierarchy best captures this information? Mammal is a superclass of Rodent and Hamster Mammal is a superclass of Rodent and Rodent is a superclass of Hamster Hamster is a superclass of Rodent and Mammal Hamster is a superclass of Rodent and Rodent is a superclass of Mammal
Mammal is a superclass of Rodent and Rodent is a superclass of Hamster
In Java, two methods can have the same name provided that what is true? They cannot be defined in the same class. They must differ in their parameter types. They must be related to each other through inheritance. One must be private and the other public.
They must differ in their parameter types.
Suppose the abstract class Message is defined below public abstract class Message { private String value; public Message(String initial) { value = initial; } public String getMessage() { return value; } public abstract String translate(); } A concrete subclass of Message, called FrenchMessage, is defined. Which methods must FrenchMessage define? getMessage() only translate() only The FrenchMessage constructor and translate() only The FrenchMessage constructor, getMessage(), and translate()
translate() only
Consider the following code snippet: public class Vehicle { . . . public void setVehicleClass(double numberAxles) { . . . } } public class Motorcycle extends Vehicle { . . . public void setVehicleClass(double numberAxles) { . . . } } Which of the following statements is correct? The Vehicle class's setVehicleClass method overrides the Motorcycle class's setVehicleClass method. The Motorcycle class's setVehicleClass method overrides the Vehicle class's setVehicleClass method. The Vehicle class's…
The Motorcycle class's setVehicleClass method overrides the Vehicle class's setVehicleClass method.
Consider the following code snippet: public class Score { private String name; . . . public boolean equals(Object otherScore) { Score other = (Score) otherScore; return name.equals(other.name); } . . . } What is wrong with this code? The parameter in the equals method should be declared as Score otherScore. The return statement should use the == operator instead of the equals method. There is nothing wrong with this code. It is an error to cast otherScore as a Score object before using the equa…
There is nothing wrong with this code.
Consider the classes shown below: public class Parent { public void doSomething(){/* Implementation not shown */} } public class Child extends Parent { public void doAnotherThing(){/* Implementation not shown */} } Which lines in the following code will compile without error? Parent kid = new Child(); kid.doSomething(); // line 1 kid.doAnotherThing(); // line 2 Line 1 only Neither line will compile without error Line 2 only Lines 1 and 2
Line 1 only
Consider the following code snippet: public void deposit(double amount) { transactionCount++; super.deposit(amount); } Which of the following statements is true? This method calls a private method in its superclass This method will call itself. This method calls a public method in its superclass. This method calls a public method in its subclass.
This method calls a public method in its superclass.
A method that has no implementation is called a/an ____ method. overloaded abstract interface implementation
abstract
Which of the following is true about interface types and abstract classes? An interface type cannot be instantiated whereas an abstract class can. An interface type cannot have constants whereas an abstract class can. An abstract class can provide method implementation whereas an interface type cannot. An interface type cannot have instance variables whereas an abstract class can.
An interface type cannot have instance variables whereas an abstract class can.
If the user presses and releases a mouse button in quick succession without moving the mouse, which methods of the MouseListenerinterface are called? Only the mouseDblClicked method. Only the mouseClicked method. mousePressed, mouseReleased, and mouseClicked. mousePressed, mouseReleased, and mouseDblClicked
mousePressed, mouseReleased, and mouseClicked.
The methods of an ____ describe the actions to be taken when an event occurs. event interface event source action source event listener
event listener
Event listeners are often installed as ____ classes so that they can have access to the surrounding fields, methods, and final variables. interface helper abstract inner
inner
You have a class that extends the JComponent class. In this class you have created a painted graphical object. Your code will change the data in the graphical object. What additional code is needed to ensure that the graphical object will be updated with the changed data? You do not have to do anything – the component object will be automatically repainted when its data changes. You must use a Timer object to cause the component object to be updated. You must call the component object's repaint…
You must call the component object's repaint() method.
Consider the definition of the Measurable interface and the code snippet defining the Inventory class: public interface Measurable { double getMeasure(); } public class Inventory implements Measurable { private int onHandCount; . . . double getMeasure() { return onHandCount; } } The compiler complains that the getMeasure method has a weaker access level than the Measurable interface. Why? The variable onHandCount was not declared with public access. All of the methods in a class have a default…
All of the methods in a class have a default access level of package access, while the methods of an interface have a default access level of public.
Which of the following statements about a mock class is true? A mock class must be an interface. A mock class does not provide an implementation of the services of the actual class. A mock class provides a complete implementation of the services of the actual class. A mock class provides a simplified implementation of the services of the actual class.
A mock class provides a simplified implementation of the services of the actual class.
Which of the following correctly defines a functional interface that, given an object, returns the value of a Coin? (Object obj) => (Coin) obj.getValue() (Object obj) -> ((Coin) obj).getValue() (Object obj) => ((Coin) obj).getValue() (Object obj) -> (Coin) obj.getValue()
(Object obj) -> ((Coin) obj).getValue()
Consider the following code snippet. File hoursFile = new File("hoursWorked.txt"); Your program must read the contents of this file using a Scanner object. Which of the following is the correct syntax for doing this? Scanner in = Scanner.open(hoursFile); Scanner in = Scanner("hoursWorked.txt"); Scanner in = new Scanner("hoursWorked.txt"); Scanner in = new Scanner(hoursFile);
Scanner in = new Scanner(hoursFile);
Assume inputFile is a Scanner object used to read data from a text file that contains a series of double values. Select an expression to complete the following code segment, which reads the values and prints them in standard output, one per line, in a field 15 characters wide, with two digits after the decimal point. while (inputFile.hasNextDouble()) { double value = inputFile.nextDouble(); ___________________________________ // statement to display double value } System.out.printf("%.2f",value…
System.out.printf("%15.2f\n",value);
Consider the following code snippet: Scanner in = new Scanner(. . .); in.useDelimiter("[A-Za-z]+"); What characters will be read in using this code? Only non-alphabetic characters will be read in. Only non-numeric characters will be read in. Only alphabetic characters will be read in. Only numeric characters will be read in.
Only non-alphabetic characters will be read in.
Assuming that inputFile is a Scanner object used to read words from a text file, select an expression to complete the following code segment, which counts the number of words in the input file. int count = 0; while (inputFile.hasNext()) { String word = _______________; count++; } System.out.println(count); inputFile.nextString() inputFile.nextDouble() inputFile.nextInt() inputFile.next()
inputFile.next()
Consider the Counter class below. public class Counter { public int count = 0; public int getCount() { return count; } public void increment() { count++; } } Using the class above and the variables declared below, what is the value of num1.equals(num2)? Counter num1 = new Counter(); Counter num2 = new Counter(); true false a syntax error nothing since equals is not defined for Counter
false
When you implement equals in a subclass, you should first call equals in the superclass. Why? To ensure that the superclass constructor has already executed. To check whether the objects being compared are instances of the same class. To prevent a bad cast and the possibility of an exception. To check whether the superclass instance variables match.
To check whether the superclass instance variables match.
Consider the following code snippet: myImage.add(new Rectangle(10,10,10,10)); This code is an example of using ____. an anonymous class. an anonymous object. an abstract object. an abstract class.
an anonymous object.
Consider the method in the following code snippet: public void getRewardPoints() { System.out.println(“Your Reward Points balance is now “ + pointBalance); } Which of the following statements would not be a valid criticism of the design of this method? It might not work in an embedded system. It violates the design rule of minimizing the dependencies between classes. It assumes that the message will always need to be in English. It should not be a separate method since it is only one line long.
It should not be a separate method since it is only one line long.
Which of the following does NOT describe a particular side effect related to standard output? Programmers may be surprised by unexpected method actions. Messages printed in a particular language may be of limited usefulness. Programmers may need values for purposes other than informational messages. Methods that rely on standard output have limited usefulness in embedded systems.
Programmers may be surprised by unexpected method actions.
Which class category has static methods and constants, but no objects? Actor class Concept class Utility class Real-life entity abstraction
Utility class
Which of the following classifications of method behavior produces acceptable side effects? Mutator methods that do not change parameter variables. Accessor methods that do not change parameter variables. Any method that changes a parameter variable. Any method that changes another object.
Mutator methods that do not change parameter variables.
Which of the following is a true statement regarding consistency in coding? Inconsistencies are an annoyance, because they can be so easily avoided. Inconsistencies nearly always produce fatal flaws. Consistency always requires extra coding. Consistency is not important in programming.
Inconsistencies are an annoyance, because they can be so easily avoided.
Consider the Checker class below. public class Checker { public static int count = 0; public int number = 0; public Checker() { count++; number = count; } public int getCount() { return count; } public int getNumber() { return number; } } What is output from the code fragment below? Checker one = new Checker(); Checker two = new Checker(); System.out.println(one.getCount() + " " + two.getCount()); 2 2 1 1 1 2 2 1
2 2
How would you create the class PackageSample in a package named bigjava.Chapter8? public class PackageSample : package bigjava.chapter8 {} public package bigjava.chapter8.PackageSample {} public class bigjava.chapter8.PackageSample {} package bigjava.chapter8; public class PackageSample {}
package bigjava.chapter8; public class PackageSample {}
Suppose an object is intended to store its current position in a 2D array using private instance variables: private int row; private int column; Which code represents a method that would move the current position of the object one column to the right on the grid? 1. public void moveRight() { column++; } 2. public void moveRight() { row++; column++; } 3. public void moveRight() { column--; } 4. public void moveRight() { row--; column++; }
1. public void moveRight() { column++; }
Which of the following is true regarding objects created from immutable classes? Immutable classes do not have constructors. It is not advisable to return immutable object references from accessor methods. It is safe to give out references to immutable class objects freely. An immutable object can only be modified by its mutator method.
It is safe to give out references to immutable class objects freely.
Why can’t Java methods change parameters of primitive type? Java methods can have no actual impact on parameters of any type. Parameters of primitive type are immutable. Parameters of primitive type are considered by Java methods to be local variables. Java methods cannot accept parameters of primitive type.
Parameters of primitive type are considered by Java methods to be local variables.
What is the output of the following code snippet? int[] values = { 10, 20, 30, 7}; int[] numbers = values; numbers[2] = 24; values[3] = numbers[0] + 6; System.out.println (numbers[2] + " " + numbers[3] + " " + values[2] + " " + values[3]); 24 16 24 16 24 0 30 6 24 0 30 16 24 7 30 16
24 16 24 16
Assume the method doSomething has been defined as follows: public static void doSomething (int[] values, int p1, int p2) { int temp = values[p1]; values[p1] = values[p2]; values[p2] = values[p1]; } What does the method do? It moves each element of the array values to a higher index position. It overwrites the value stored in the integer array values at position p1 with the value stored in position p2. It swaps the integer values stored in positions p1 and p2 of the array values. It copies the i…
It swaps the integer values stored in positions p1 and p2 of the array values.
What is the result of the following code? for (double element : values) { element = 0; } The elements of the array element are initialized to zero. The first element of the array values is initialized to zero. The elements of the array values are initialized to zero. The array values is not modified.
The array values is not modified.
Identify the correct statement for defining an integer array named numarray of ten elements. int[] numarray = new int[9]; int[10] numarray; int[] numarray = new int[10]; int numarray[10];
int[] numarray = new int[10];
Which one of the following code snippets accepts the integer input in an array list named num1 and stores the odd integers of num1 in another array list named oddnum? 1. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> oddnum = new ArrayList<Integer>(); int data; Scanner in = new Scanner(System.in); for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1.get(i) % 2 == 0) { oddnum.add(num1[i]); } } 2. ArrayList<Integer> num1 = new ArrayList<Integer>();…
3. ArrayList<Integer> num1 = new ArrayList<Integer>(); ArrayList<Integer> oddnum = new ArrayList<Integer>(); int data; Scanner in = new Scanner(System.in); for (int i = 0; i < 10; i++) { data = in.nextInt(); num1.add(data); if (num1.get(i) % 2 != 0) { oddnum.add(num1.get(i)); } }
Consider the following 2-dimensional array. Which expression gives the number of elements in the third row? int[][] counts = { { 0, 0, 1 }, { 0, 1, 1, 2 }, { 0, 0, 1, 4, 5 }, { 0, 2 } }; counts.length[2] counts.length counts[2].size() counts[2].length
counts[2].length
Which statements about array algorithms are true? I. The array algorithms are building blocks for many programs that process arrays. II. Java contains ready-made array algorithms for every problem situation. III. It is inefficient to make multiple passes through an array if you can do everything in one pass. II, III only I, II, III I, II only I, III only
I, III only
Storyboards are a helpful part of the design process because the storyboard develops a pseudocode description of the algorithm being designed. the amount of time and space needed to find a solution. the information needed to solve the problem, and how to present that information. the mathematical formulas required for computing a correct answer.
the information needed to solve the problem, and how to present that information.
What is the outcome of the following code snippet? boolean val1 = true; boolean val2 = false; while (val1) { if (val1) { System.out.println("Hello"); } val1 = val2; } Hello will be displayed infinite times. No output will be displayed because of a compilation error. Hello will be displayed only once. No output will be displayed even after successful compilation of the code snippet.
Hello will be displayed only once.
What is the output of the code snippet given below? String s = "12345"; int i = 1; while (i < 5) { System.out.print(s.substring(i, i + 1)); i+=2; } 2345 13 no output 24
24
Which for loop prints data across each row in the following code snippet? int i; int j; for (i = 1; i <= 3; i++) { for (j = 1; j <= 3; j++) { System.out.print("X"); } System.out.println(""); } the outer for loop both for loops another missing for loop the inner for loop
the inner for loop
What will be the result of running the following code fragment? int year = 0; double rate = 5; double principal = 10000; double interest = 0; while (year < 10) { interest = (principal * year * rate) / 100; System.out.println("Interest " + interest); } The code fragment will display the interest calculated for nine years. The code fragment will not display the calculated interest and halt abruptly. The code fragment will continue to display the calculated interest forever because the loop will n…
The code fragment will continue to display the calculated interest forever because the loop will never end.
The process of hand-tracing code is valuable because it is usually faster than just running the code. it gives valuable insight that you do not get by running the code. it is the best way to design an algorithm. you must already have a working program in order to do it.
it gives valuable insight that you do not get by running the code.
What is the output of the code fragment given below? int i = 0; int j = 0; while (i < 27) { i = i + 2; j++; } System.out.println("j=" + j); j=12 j=27 j=13 j=14
j=14
The command line interface of your operating system provides a way to link a file to the input of a program. What is this process called? profiling redirection debugging compiling
redirection
Which of the following loops executes 8 times? for (int i = 19; i >= 11; i--) for(i = 0; i <= 7; i++) for (years = 8; years >= 0; years--) for(i = 1; i <= 10; i++)
for(i = 0; i <= 7; i++)
The code snippet below checks whether a given number is a prime number. What will be the result of executing it? public static void main(String[] args) { int j = 2; int result = 0; int number = 0; Scanner reader = new Scanner(System.in); System.out.println("Please enter a number: "); number = reader.nextInt(); while (j <= number / 2) { if (number % j == 0) { result = 1; } j++; } if (result == 1) { System.out.println("Number: " + number + " is Not Prime."); } else { System.out.println("Number: "…
The code snippet will display the desired result.
Which of the following conditions will correctly check if the String variable early comes before "middle" alphabetically? if (greeting.compareTo("middle") == 0) if (early.compareTo("middle") < 0) if (greeting <= "middle") if (greeting.compareTo("middle") > 0)
if (early.compareTo("middle") < 0)
Which one of the following is the correct definition for initializing data in a two-dimensional array with three rows and two columns? 1. int[][] arr = { { 1, 1, 1 } { 2, 2, 2 } { 3, 3, 3 } }; 2. int[][] arr = { { 1, 1, 1 }, { 2, 2, 2 }, }; 3. int[][] arr = { { 1, 1 } { 2, 2 } { 3, 3 } }; 4. int[][] arr = { { 1, 1 }, { 2, 2 }, { 3, 3 } };
4. int[][] arr = { { 1, 1 }, { 2, 2 }, { 3, 3 } };
Which of the following statements can be used to validate that the user input for the floor variable is between 0 and 20 inclusive? if (floor >= 0 && floor <= 20) if (floor <= 0 && floor >= 20) if (floor <= 0 || floor >= 20) if (floor >= 0 || floor <= 20)
if (floor >= 0 && floor <= 20)
Which of the following expressions represents a legal way of checking whether a value assigned to the num variable falls in the range 100 to 200 (inclusive)? if (num >= 100 && num <= 200) if (num >= 200 || num <= 100) if (num >= 100 || num <= 200) if (num >= 200 && num <= 100)
if (num >= 100 && num <= 200)
Which of the following conditions will correctly check if the String variable greeting is "bonjour"? if (greeting == "bonjour") if (greeting.equals("bonjour")) if (greeting.compareTo("bonjour") > 0) if (greeting.compareTo("bonjour") < 0)
if (greeting.equals("bonjour"))
Consider a situation where multiple if statements are combined into a chain to evaluate a complex condition. Which of the following reserved words is used to define the branch to be executed when none of the conditions are true? if else if All of the above items else
else
Which of the following conditions is true exactly when the integer variable number is even? number / 2 == 0 number > 2 number / 2 > 1 number % 2 == 0
number % 2 == 0
What is the value of the count variable after the execution of the given code snippet? ArrayList<Integer> num = new ArrayList<Integer>(); num.add(1); num.add(2); num.add(1); int count = 0; for (int i = 0; i < num.size(); i++) { if (num.get(i) % 2 == 0) { count++; } } 3 2 0 1
1
Assume the following variables have been declared and given values elsewhere: boolean isFelon; int age; A person may vote if they are 18 or older and not a felon. Which of the following statements assigns the Boolean variable mayVotecorrectly? mayVote = !((age >= 18) || isFelon); mayVote = (age >= 18) && !isFelon; mayVote = (age >= 18) || !isFelon; mayVote = !((age >= 18) && isFelon);
mayVote = (age >= 18) && !isFelon;
Which of the following conditions can be added to the code below so it will assign the larger value of two integer variables a and b to the integer variable maximum? if (/* put condition here */) { maximum = a; } else { maximum = b; } a == b a > b a.compareTo (b) > 0 b > a
a > b
Consider the following code snippet: boolean attendance = true; boolean failed = false; Which of the following if statements includes a condition that evaluates to true? if (attendance == failed) { . . . } if (attendance == "true") { . . . } if (attendance) { . . . } if (failed) { . . . }
if (attendance) { . . . }
Assume isBusy has been defined to be a Boolean variables. Which of the following has the same value as (isBusy || true) && false? isBusy false true !isBusy
false
Which one of the following is a correct method for defining and initializing an integer variable with name value? Int value = 30; int value = .30; Int value = .30; int value = 30;
int value = 30;
What is the value of Math.abs(-2)? 4 0 2 -2
2
Which one of the following expressions can be used to extract the last five characters from any string variable str? str.substring(str.length() - 5, str.length()) str.substring(str.length() - 4, 5) str.substring(str.length() - 5, 5) str.substring(5, 5)
str.substring(str.length() - 5, str.length())
What is wrong with the following code? int count = 2000 * 3000 * 4000; Variable is undefined Wrong data type Illegal expression Integer overflow
Integer overflow
Assuming that the user inputs a value of 25000 for the pay and 10 for the bonus rate in the following code snippet, what is the output? Scanner in = new Scanner(System.in); System.out.print("Enter the pay: "); double pay = in.nextDouble(); System.out.print("Enter the bonus rate:"); double bonus = in.nextDouble(); System.out.println("The new pay is " + (pay + pay * (bonus / 100.0))); The new pay is 30000.0 The new pay is 27500.0 The new pay is 25100.0 The new pay is 25000.0
The new pay is 27500.0
Which one of the following refers to a number constant that appears in code without explanation? Constant Variable Magic number String literal
Magic number
What is the output of the following statement sequence? int x = 100.0 % 6.0; System.out.println(x); Run-time error 16 4 Compile-time error
Compile-time error
What is the output of this code snippet? int sum = 22; sum = sum + 2; System.out.print(sum); // sum = sum + 4; System.out.print(sum); 2528 2424 2428 2425
2424
What is the output of this code snippet? double average; int grade1 = 87; int grade2 = 94; // System.out.print("The average is " + (grade1 + grade2) / 2.0); System.out.print("The average is " + average); The average is 91.5 The average is 91.5 The average is 91.5 The average is 0.0 Compile-time error The average is 91.5
Compile-time error
Identify the explicit parameter of the withdraw method of the BankAccount class. amount double public balance
amount
Where do parameters and local variables belong? in an object in a package in a class in a method
in a method
The code below for the mutator method public void setLength(double length) of the Square class is intended to set the value of thesideLength instance variable to the parameter variable of the method. Which line of code avoids the common error of ignoring the parameter variables of a method? return sideLength; double thisLength = length; sideLength = length; sideLength = 54;
sideLength = length;
Assuming the following code is the body of the deposit method, what output is generated by the valid call myAccount.deposit(1000) for an account with an initial balance of 500? public void deposit(double amount) { System.out.println(amount); double newBalance = balance + amount; balance = newBalance; } The code fragment has a syntax error and does not compile. 1000.0 1500.0 The code fragment does not compile because the parameter variable is not initialized.
1000.0
Identify the explicit parameter of the withdraw method of the BankAccount class. amount double public balance
amount
Assume that the following Java statement is contained in the main method of the class named Hello: System.out.printLine("Hello!"); What is the name of the file generated by the Java compiler? Hello Hello.java Hello.class No file is generated due to an error.
No file is generated due to an error.
A sequence of steps that can be carried out in practice is ______________. documented unambiguous terminating executable
executable
What term is used to refer to languages that allow programmers to describe tasks at a higher conceptual level than machine code? conceptual high-level sophisticated virtual
high-level
Which statement regarding computer programs is correct? Computer programs can decide what task to perform. Large and complex computer programs are generally written by only one programmer. Small computer programs are not documented. Computer programs are composed of extremely primitive operations.
Computer programs are composed of extremely primitive operations.
Input to a method, enclosed in parentheses after the method name, is known as ______________. arguments implicit parameters interfaces return values
arguments
To use a class in another package you need to ________ it. rewrite export import overload
import
Which of the following is a mutator method for the Rectangle class? getWidth translate isEmpty getHeight
translate
The camel case naming convention uses _________ at intervals in the middle of the variable name. dollar signs uppercase letters the underscore character digits
uppercase letters
What is the name of the type that denotes whole numbers? double integer int whole
int
What do object variables store? numbers object references classes objects
object references
What is the output of the following code: Circle c1 = new Circle(3); Circle c2 = new Circle(3); c1.setRadius(4); System.out.println(c2.getRadius()); 8 6 4 3
3
What is a storage location in the computer's memory called that has a type, name, and contents? variable literal identifier label
variable
Which class is part of the java.lang package? PrintStream String Rectangle Circle
String
What is the name of the = operator in Java? inequality assignment identity equality
assignment
Which operator constructs object instances? construct void instanceof new
new
Which import statement allows for the use of the Rectangle class? import java.geom.Rectangle2D; import java.geom.RectangularShape; import java.awt.Rectangle; import java.geom.Rectangle;
import java.awt.Rectangle;
Which of the following statements about methods is correct? Methods are stored in variables. Correct Answer A method is a sequence of instructions that could access the data of an object A method name is unique across the entire program. A method can be called on any object in any class.
A method is a sequence of instructions that could access the data of an object
Assume that the variable count has been declared as type int. Which statement adds 10 to count? count + 10; count = count + 10; count == count + 10; count = 10;
count = count + 10;
What is an object? An entity in your program that is manipulated by calling methods. A sequence of instructions. Any value stored in a variable. Any input to a method.
An entity in your program that is manipulated by calling methods.
If greeting refers to a String object, which of the following is a syntactically correct Java statement? greeting.println("Hello"); System.out.println(length().greeting); System.out.println(greeting.length()); System.out.println(greeting());
System.out.println(greeting.length());
What is the nickname for the graphical user interface library in Java? GUI JComponent Applet Swing
Swing
It may be necessary to "grow" an array when reading inputs because arrays in Java must be resized after every 100 elements. the only alternative is a bounds exception. the number of inputs may not be known in advance. arrays are based on powers of two.
the number of inputs may not be known in advance.
Which statement declares and stores an integer value in a variable? integer count = 5; String count = 5; count = 5; int count = 5;
int count = 5;