p
Which class in the following list of classes are all exceptions subclasses of?
Exception
What is the third line printed to the console in the code that follows?int items = 3;for (int i = 1; i <= items; i++) {int result = 1;for (int j = i; j >= 1; j--) {result *= j;}System.out.println("Factorial " + i + " = " + result);}
Factorial 3 = 6
What output is displayed when the code that follows is executed?TreeMap<String, Double> sales = new TreeMap<>();sales.put("January", 389.45);sales.put("February", 432.89);sales.put("March", 275.30);for (Map.Entry sale : sales.entrySet()) {System.out.println(sale.getKey() + ": " + sale.getValue());}
February: 432.89January: 389.45March: 275.30
Output example 5-1Exception in thread "main" java.util.InputMismatchExceptionat java.util.Scanner.throwFor(Scanner.java:818)at java.util.Scanner.next(Scanner.java:1420)at java.util.Scanner.nextDouble(Scanner.java:2324)at FutureValueApp.main(FutureValueApp.java:17) (Refer to output example 5-1.) What is the order of method calls?
FutureValueApp.main calls java.util.Scanner.nextDouble calls java.util.Scanner.next calls java.util.Scanner.throwFor
import java.util.Scanner;public class InvoiceApp {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String choice = "y";while (choice.equals("y")) {System.out.print("Enter subtotal: ");double subtotal = sc.nextDouble();double salesTax = subtotal * .0875;double invoiceTotal = subtotal + salesTax;String message = "Subtotal = " + subtotal + "\n"+ " Sales tax = " + salesTax + "\n"+ "Invoice total = " + invoiceTotal + "\n\n"System.out.println(message);System.out.print("Continue? Enter y or n: ");choice = sc.next();}}}
InvoiceApp.java
Which of the following is not a feature of using an Installer program to deploy an application?
It automatically updates the application when a new version is available.
Which of the following is a feature of using an executable JAR file to deploy an application?
It has no significant security restrictions
Which of the following is not a feature of using Java Web Start to deploy an application?
It has no significant security restrictions
Which of the following is not an advantage of using a three-tiered architecture for your applications?
It makes it easier to document the tasks performed by an application.
What does the code that follows do?String s1 = "Kristine";s1 += " Thomas";String s2 = s1;if (s1.equals(s2)) {System.out.println("same");}if (s1 == s2) {System.out.println("equal");}
It prints "same" and "equal" to the console.
What does the following code do?String s1 = "805 Martin Street";String s2 = "805 Martin Street";if (s1.equals(s2)) {System.out.println("same");}if (s1 == s2) {System.out.println("equal");}
It prints "same" to the console.
If the Point class doesn't override the equals() method in the Object class, what will the following code do?Point pointOne = new Point(3, 4);Point pointTwo = new Point(3, 4);System.out.println(pointOne.equals(pointTwo));
Print "false" to the console
Which of the following statements creates a Scanner object named sc?
Scanner sc = new Scanner(System.in);
Which of the following statements converts a double variable named subtotal to a String object named subtotalString?
String subtotalString = Double.toString(subtotal);
Which of the following statements prints a variable named total to the console, followed by a new line character?
System.out.println(total);
Consider the code that follows. What does it do?String value = "2";boolean tryAgain = true;while (tryAgain == true) {try {int num = Integer.parseInt(value);tryAgain = false;}System.out.println("Valid integer");catch(NumberFormatException nfe) {System.out.println("Invalid integer");System.out.print("Enter an integer");value = sc.next}}
The code doesn't compile.
If name is a String instance variable, average is a double instance variable, and numOfStudents is a static int variable, why won't the following code from a class compile?public Student(String s) {name = s;average = getAverage(name);numOfStudents++;}public double getAverage(String x) {numOfStudents++;double ave = StudentDB.getAverage(x);return ave;}public static void setAverage(double g) {average = g;}
The setAverage() method can't access the average instance variable.
Which of the following is a benefit of using javadoc comments?
They make it easy for other programmers to learn about your class.
Which of the following is not a reason to create a package?
To prevent other developers from using the class
Which of the following is not a benefit of a typical IDE for Java?
Your code compiles and runs faster.
An executable JAR file contains
a and c only
To make it easier for a user to run an executable JAR file for a console application, you can create
a script file such as a BAT or SH file
Explicit casting is always required to cast
a superclass object to a subclass object
In a do-while loop, the Boolean expression is tested
after the loop is executed
To determine the cause of an unhandled exception, you can
all of the above
A static initialization block
all of the above: is used to initialize a static variable that can't be initialized in the declaration AND is executed when a static method of the class is called AND is executed when an instance of the class is created
As you develop a Java program, you can use an IDE to
all of the above: run the application enter and edit the source code compile the source code
Each constant within an enumeration is assigned
an integer value beginning with zero
Using the BigDecimal class, you can
avoid rounding errors that may occur otherwise in business applications
Unlike an if/else statement, a switch statement: - can't test for a default condition - can't perform an operation based on the result of a Boolean expression - can't be nested within another switch statement
can't perform an operation based on the result of a Boolean expression
Unlike a variable, a constant can't
change in value as an application runs
The has methods of the Scanner class let you
check if the user has entered data at the console AND check if the data entered at the console can be converted to a specific data type
To handle an exception using the try statement, you must
code a catch block that contains the statements that you want to be executed when the exception occurs AND code a try block around the statement that may throw the exceptions
In an IDE, what tool do you use to enter and edit source code?
code editor
What is the value of the string named lowest when the code that follows is executed?String[] types = {"lux", "eco", "comp", "mid"};Arrays.sort(types);String lowest = types[0];
comp
When you run a project, most IDEs automatically
compile the project
Which of the following are two types of desktop applications that you can develop in Java?
console and GUI
Which of the following statements do you use to jump to the end of a loop from within the loop? (end of loop cycle not of the entire loop)
continue (break is to end loop cycle completely)
Code example 5-1import java.util.Scanner;import java.text.NumberFormat;public class WeightConverter{public static void main(String[] args){Scanner sc = new Scanner(System.in);String prompt = "Enter weight in lbs: ";boolean isValid = false;double weightInPounds = 0.0;while (isValid == false){weightInPounds = getDouble(sc, prompt);if (weightInPounds > 0)isValid = true;elseSystem.out.println("Weight must be greater than 0.");}double weightInKilos = weightInPounds / 2.2;NumberFormat nf = NumberFormat.getNumberInstance();nf.setMaximumFractionDigits(2);String message = weightInPounds + " lbs\nequals\n"+ nf.format(weightInKilos) + " kgs\n";System.out.print(message);}public static double getDouble(Scanner sc, String prompt){double d = 0.0;boolean isValid = false;while (isValid == false){System.out.print(prompt);if (sc.hasNextDouble()){d = sc.nextDouble();isValid = true;}else{System.out.println("Error! Invalid decimal value. Try again.");}sc.nextLine();}return d;}}(Refer to code example 5-1.) If the user enters "two hundred" at the console prompt, what does the code do?
displays an error message from the getDouble method
Code example 5-1import java.util.Scanner;import java.text.NumberFormat;public class WeightConverter {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String prompt = "Enter weight in lbs: ";boolean isValid = false;double weightInPounds = 0.0;while (!isValid) {weightInPounds = getDouble(sc, prompt);if (weightInPounds > 0) {isValid = true;} else {System.out.println("Weight must be greater than 0.");}}double weightInKilos = weightInPounds / 2.2;NumberFormat nf = NumberFormat.getNumberInstance();nf.setMaximumFractionDigits(2);String message = weightInPounds + " lbs\nequals\n"+ nf.format(weightInKilos) + " kgs\n";System.out.print(message);}public static double getDouble(Scanner sc, String prompt) {double d = 0.0;boolean isValid = false;while (!isValid) {System.out.print(prompt);if (sc.hasNextDouble()) {d = sc.nextDouble();isValid = true;} else {System.out.println("Error! Invalid decimal value. Try again.");}sc.nextLine();}return d;}} (Refer to code example 5-1.) If the user enters -1 at the first console prompt, what does the code do?
displays an error message from the main() method
Which of these data types are used to store numbers with decimal positions?
double
Which of the following method declarations overrides this method?double calculateMilesPerGallon(double speed){...}
double calculateMilesPerGallon(double s){...}
Which of the following is a valid statement for declaring and initializing a double variable named length to a starting value of 120?
double length = 120.0;
The array that follows is an array ofdouble[] grades = new double[3];
double values
If a user's computer has an appropriate version of the JRE installed, that user can run an executable JAR file for a GUI application by
double-clicking on the JAR file
Based on the naming recommendations in the book, which of the following is a good identifier for a variable that will be used to hold an employee's phone number?
employeePhoneNumber
When you call the equals() method in the String class without knowing how it's coded, you're taking advantage of what object-oriented concept?
encapsulation
The double data type can be used to store
floating-point numbers
When you code a class that implements an interface, most IDEs can
generate all of the method declarations for the methods defined by the interface
A method that accepts an interface as an argument can accept any object that
implements that interface
Which of the following statements makes all of the classes in the java.io package available to a Java application?
import java.io.*;
When you add characters to a StringBuilder object, Java
increases the capacity of the object if necessary to store the new characters
Which of these data types are used to store whole numbers (no decimal positions)?
int short long
Which of the following is true about a method that has this declaration? public Employee getDepartmentManager(){...}
it returns an object of the Employee class
The extension for a Java source file is
java
An error that lets the application run but produces the wrong results is known as a
logic error
In the statement that follows, x can not be what data type?switch(x){statements}
long
The class that contains the main() method for an application is known as the
main class
When you delete characters from a StringBuilder object, Java
maintains the current capacity of the object
The goal of testing is to
make sure the application works with valid data
What is the value of s1 after the code that follows is executed?StringBuilder title = new StringBuilder();title.append("The Basics of OOP");title.delete(0, 13);String s1 = title.toString();
" OOP"
Which of the following is an invalid list of elements in an array?
"Joe", 3, 25.5
Code example 9-1public interface Printable {public void print();}public class Printer {public static void printInvoice(Printable p) {System.out.println("Printing invoice");p.print();}}public class Order implements Printable {public void print() {System.out.println("Order object");}}public class Rental extends Transaction implements Printable {public void print() {System.out.println("Rental object");}} (Refer to code example 9-1.) What happens when the code that follows is executed?Rental rental = new Rental();Printer.printInvoice(rental);
"Printing invoice" and "Rental object" are printed to the console.
What is the value of the variable named len after the code that follows is executed?int[][] nums = { {1, 2, 3}, {3, 4, 5, 6, 8}, {1}, {8, 8} };int len = nums[2].length;
1
What numbers does the code that follows print to the console?int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};for (int i = 0; i < 9; i++){System.out.println(numbers[i]);}
1-9
If int variable x = 100, float variable y = 1.587F, and double variable z = 4.8, what does the following expression return?x + Math.round(y) + (int) z
106
What is the value of s1 after the code that follows is executed?StringBuilder s1 = new StringBuilder();s1.append("115-88-9525");s1.deleteCharAt(4);
115-8-9525
What happens when the code that follows is executed?LinkedList<Integer> units = new LinkedList<>();units.add(8);units.add(12);units.add(3);System.out.println(units.get(1));
12 is printed to the console.
Assume that before the following code is executed, the value of totalOne is 6.728, the value of totalTwo is 116, and both are BigDecimal objects. What is the value of totalFinal after the code is executed?totalOne = totalOne.setScale(2, RoundingMode.HALF_UP);BigDecimal totalFinal = totalTwo.add(totalOne);
122.73
What is the value of the variable named cap after the code that follows is executed?StringBuilder name = new StringBuilder("Thomas");int cap = name.capacity();
16
Code example 4-1int limit = 0;for (int i = 10; i >= limit; i -= 2) {for (int j = i; j <= 1; j++) {System.out.println("In inner for loop");}System.out.println("In outer for loop");} (Refer to code example 4-1.) How many times does "In inner for loop" print to the console?
2
Each element in a linked list
points to the elements both before and after it in the list
What is the value of m after the code that follows is executed?ArrayList<Double> miles = new ArrayList<>();miles.add(37.5);miles.add(26.2);miles.add(54.7);double m = miles.remove(0);
37.5
What is the value of the variable named counter after the statements that follow are executed?double percent = 0.54;boolean valid = true;int counter = 1;if ((percent > 0.50) && (valid == true)) {counter += 2;if (valid == true) {counter++;} else if (percent >= 0.50){counter += 3;}} else {counter++;}
4
If a linked list has 200 elements, how many elements will need to be accessed to retrieve the 150th element?
51
Code example 4-1int limit = 0;for (int i = 10; i >= limit; i -= 2) {for (int j = i; j <= 1; j++) {System.out.println("In inner for loop");}System.out.println("In outer for loop");} (Refer to code example 4-1.) How many times does "In outer for loop" print to the console?
6
If the double variables x = 2.5 and y = 4.0, what is the value of z after this statement is executed?int z = (int) x + (int) y;
6
What does the following code display?public class RentalApp {public static void main(String[] args) {Rental r = new Rental();r.setNumOfPersons(5);r.addPerson(r);System.out.println(r.getNumOfPersons());}}public class Rental {private int numOfPersons;public int getNumOfPersons() {return numOfPersons;}public void setNumOfPersons(int numOfPersons) {this.numOfPersons = numOfPersons;}public void addPerson(Rental rental) {rental.numOfPersons++;}}
6
How many rows are in the array that follows?Rental[][] transactions = new Rental[7][3];
7
If the variable named input is 755, what is the value of r after these statements are executed?NumberFormat n = NumberFormat.getNumberInstance();n.setMinimumFractionDigits(3);String r = n.format(input);
755.000
What is the value of x after the following statements are executed?int x = 5;switch(x) {case 5:x += 2;case 6:x++;break;default:x *= 2;break;
8
What does the following code display?public class GradeCurveApp {public static void main(String[] args) {int grade = 95;GradeCurve curve = new GradeCurve();curve.lowerGrade(grade);System.out.println(grade);}}public class GradeCurve {public void lowerGrade(int g) {g -= 5;}}
95 ( value not returned)
Which of the following can you not code in a subclass?
A call to a private method of the superclass
What is the name of the class that contains this code?private Clock clock;private Alarm alarm;public AlarmClock(Date time){...}
AlarmClock
What class or classes is a variable available to if it is declared without an access modifier?
All classes in the same package
If a method accepts an Object object, what other types of objects can it accept?
All objects
What information does a module-info file provide?
All of the above: A unique name for the module AND Other modules that the module requires AND Packages that the module exports
What is the value of names[4] in the following array?String[] names = {"Jeff", "Dan", "Sally", "Jill", "Allie"};
Allie
Which of these statements is not true about the method that follows?public void deposit(Date date, double amt){this.balance += amt;this.printDeposit(accountNum, date, amt);}
printDeposit is a static method
Based on the naming recommendations in the book, which of the following is a good identifier for a constant that will be used to hold a base shipping charge?
BASE_SHIPPING_CHARGE
Which of the following statements creates a BigDecimal variable named decimalSubtotal from a double variable named subtotal, making sure that conversion problems are avoided.
BigDecimal decimalSubtotal = new BigDecimal(Double.toString(subtotal));
When using an IDE, what must you do to use a class that's stored in a library?
Both b and c. Co de an import statement for the class. AND Add the library to your project
If the Loan class contains a final method named calculatePayment, what does the following code do?
Calls the calculatePayment() method in the Loan class
What output is displayed when the code that follows is executed?HashMap<String, Double> sales = new HashMap<>();sales.put("January", 389.45);sales.put("February", 432.89);sales.put("March", 275.30);for (Map.Entry sale : sales.entrySet()) {System.out.println(sale.getKey() + ": " + sale.getValue());}
Can't be determined from the information that's given.
An IDE typically stores all of the files for an application in a
project
Which method is an example of overloading the method that follows?public int parseNumber(String numberString){...}
public int parseNumber(String numberString, String entry){...}
An error that occurs after an application is running is known as a
runtime error
If the variables named price and rate are doubles and qty is an int, what is a possible declaration for the getTax() method that's called by the statement that follows? double tax = TaxCalculator.getTax(price, rate, qty);
static double getTax(double x, double y, int z)
When you're using an IDE's debugger and execution reaches a breakpoint, you can click
the Step Into button to execute the current statement and move to the next statement
When you add an entry to a queue, it's added to
the end of the queue
Consider the following condition. It will be true when(!endProgram.equalsIgnoreCase("n"))
the value of endProgram doesn't equal "n" or "N"
A syntax error occurs when
there's a syntax error in a Java statement
An enhanced for loop can only be used
to work with all the elements of an array
Which of the following methods can always be called from a Product object?
toString()
the equality operator (==) checks whether
two Strings variables refer to the same String object
What is the highest index value associated with the array that follows?byte[] values = new byte[x];
x - 1
You should validate user entries rather than catch and handle exceptions caused by invalid entries whenever possible because
your code will run faster
What is the value of s3 after the code that follows is executed?String s1 = "abc def ghi";String s2 = s1.substring(1, 5);String s3 = s2.replace('b', 'z');
zc d