Java CS 170
138 flashcards · Programming Languages · by hgulino
What is the argument in the given method call? System.out.println("Welcome"); System println out "Welcome"
"Welcome"
Which statement is true about the compilation process? The compiler will stop compiling when it finds the first error. The compiler will generate Java virtual machine instructions even if it detects an error. The compiler will continue compiling after it finds an error. The compiler will generate CPU specific instructions even if it detects an error.
The compiler will continue compiling after it finds an error.
Evaluate the given pseudocode to calculate the efficiency of a vehicle's fuel consumption using the following test values: The trip odometer reading (odometer) = 300 The amount to fill the gas tank (amount) = 15 input odometer input amount output odometer/amount What is the final output? 15 30 10 20
20
What is the term used to describe an error detected by the compiler that is a violation of the programming language rules? logic error typo compile-time error run-time error
compile-time error
What term is used to refer to a sequence of steps for solving a problem that is unambiguous, executable, and terminating? algorithm pseudoprogram comments documentation
algorithm
Evaluate the given pseudocode to calculate the payment (pmt) with the following test values: The total number of hours worked (working_hours) = 50 The rate paid for hourly work (rate) = 10 input working_hours input rate pmt = working_hours * rate if working_hours > 40 then extra_hours = working_hours – 40 extra_pmt = extra_hours * rate pmt = pmt + extra_pmt end of if output pmt What is the final output? 580 540 500 600
600
The line public class HelloPrinter indicates which declaration below? Declaration of the class public. Declaration of the class HelloPrinter. Declaration of the variable class. Declaration of the variable public.
Declaration of the class HelloPrinter.
Which statement best describes the portability characteristic of Java? It is easy to change a Java program so that it will work on different operating systems. The same already-compiled Java programs will run on Windows, UNIX, Linux, or Macintosh operating systems without any change. The same Java compiler can be used on many operating systems. There are only small differences between the Java programming language on different operating systems.
The same already-compiled Java programs will run on Windows, UNIX, Linux, or Macintosh operating systems without any change.
What term is used to refer to values supplied to a method that are needed to carry out its task? argument class comment object
argument
Suppose that a computer virus infects your computer and corrupts the files you were going to submit for your current homework assignment. What precaution could have saved you from a disastrously bad grade for this assignment? Purchase an extended warranty for your computer. Make regular backups of all your important files. Purchase an anti-virus program to remove the virus from your computer. Defragment the hard drive.
Make regular backups of all your important files.
Which memory type does not provide persistent storage? primary storage DVD hard disk secondary storage
primary storage
Assuming the programmer wishes to output the phrase "Hello!", which of the following is true about the following Java statement: System.out.println("Welcme!"); There is a compile-time error. There are no errors. There is a run-time error. There are multiple errors.
There is a run-time error.
What term is used to refer to a sequence of characters enclosed in quotation marks? comment variable object string
string
Which statement is true about the following Java code fragment: System.out.println("Hello!); There is a compile-time error. There are multiple errors. There is a run-time error. There are no errors.
There is a compile-time error.
Arguments supplied to methods are enclosed by which symbols? // {} () " "
()
Which statement is true about running a Java program on a different CPU? You need to compile the Java program for each CPU. You can take code that has been generated by the Java compiler and run it on different CPUs. You need different Java source code for each CPU. You cannot run the program on a different CPU because Java, being a high-level programming language, is machine dependent.
You can take code that has been generated by the Java compiler and run it on different CPUs.
What is the purpose of the following algorithm? input num Repeat the following steps for 9 times input var1 if var1 > num then num = var1 print num To search for a particular number among 10 numbers To find the largest among 10 numbers To find the smallest among 10 numbers To print out the 10 numbers
To find the largest among 10 numbers
System.out.println(4 + 6); 4 46 10 4 + 6
10
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.
What is the name of the method in the given method call? System.out.println("Welcome"); "Welcome" System out println
println
A sequence of steps that can be carried out in practice is ______________. documented unambiguous terminating executable
executable
Pseudocode must be i. Unambiguous. ii. Syntactically correct code. iii. Readable by a human. iv. Indicative of results of an algorithm. i, ii, iii i, ii i, iii, iv ii, iii, iv
i, iii, iv
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.
What is the term used to describe an error causing a program to take an action that the programmer did not intend? run-time error typo syntax error compile-time error
run-time error
A sequence of steps that eventually comes to an end is ______________. executable documented terminating unambiguous
terminating
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
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;
Based on the following code, which of the following statements sets the frame to a width of 400 and a height of 200: final int FRAME_WIDTH = 400; final int FRAME_HEIGHT = 200; JFrame frame = new JFrame(); frame.setSize(FRAME_HEIGHT, FRAME_WIDTH); frame.size = (FRAME_WIDTH, FRAME_HEIGHT); frame.addSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
You should provide documentation comments for ___. only methods with parameters every class, every method, every parameter, and every return value only methods with return values only classes
every class, every method, every parameter, and every return value
Assume the method below has been added to the BankAccount class. public void giveBonus () { balance = balance + 5.0; } What will be output from the following statements that use the revised BankAccount class? BankAccount premiumAccount = new BankAccount (100); premiumAccount.giveBonus (); premiumAccount.giveBonus (); premiumAccount.giveBonus (); System.out.println (premiumAccount.getBalance()); 115.0 100.0 105.0 110.0
115.0
If the CarComponent class had the call below added to it, where will car3 be placed? int y3 = (getHeight() - 30)/2; Car car3 = new Car(0, y3); car3.draw(g2); At the middle of the bottom of the window At the middle of the top of the window At the middle of the left side of the window At the middle of the right side of the window
At the middle of the left side of the window
The access specifier in the declaration of instance variables should be ___. protected private class public
private
Consider the following method header: /** Adds interest to the bank account _________________________________ */ public void addInterest(double rate) . . . Fill in the blank in the javadoc comment: @param rate the rate of interest @parameter interestRate the rate of interest @parameter rate the rate of interest @param interestRate the rate of interest
@param rate the rate of interest
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
An instance variable declaration consists of which of the following parts? an access specifier, a list of the parameters (if any), and the body of the method. an access specifier, the type of the instance variable, and the name of the instance variable. the type of the instance variable, an access specifier, a list of the parameters (if any), and the body of the method. the return type, the name of the method, and a list of the parameters (if any).
an access specifier, the type of the instance variable, and the name of the instance variable.
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;
Identify the explicit parameter of the withdraw method of the BankAccount class. amount double public balance
amount
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
Where do parameters and local variables belong? in an object in a package in a class in a method
in a method
Identify the explicit parameter of the withdraw method of the BankAccount class. amount double public balance
amount
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
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
Assume the following variables have been declared as shown and given values elsewhere: double a, b, c; The discriminant of a quadratic equation is defined to be: b2−4ac\sqrt[]{b^2 - 4ac}b2−4ac Which of the following statements will assign the correct value to discriminant? double discriminant = Math.sqrt(b2 - 4ac) double discriminant = Math.sqrt(b * b) - Math.sqrt(4 * a * c); double discriminant = Math.sqrt(b * b - 4 * a * c); double discriminant = Math.sqrt(b * b) - 4 * a * c;
double discriminant = Math.sqrt(b * b - 4 * a * c);
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
Which one of the following refers to a number constant that appears in code without explanation? Constant Variable Magic number String literal
Magic number
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
What is wrong with the following code? int count = 2000 * 3000 * 4000; Variable is undefined Wrong data type Illegal expression Integer overflow
Integer overflow
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 the value of Math.abs(-2)? 4 0 2 -2
2
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;
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
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) { . . . }
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
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 is true exactly when the integer variable number is even? number / 2 == 0 number > 2 number / 2 > 1 number % 2 == 0
number % 2 == 0
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 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"))
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 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 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)
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 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 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
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 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 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.
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 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
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.
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.
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
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 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)); } }
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.
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
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 } };
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];
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.
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 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
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.
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.