Java Exam 3
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
The layout manager that lays out components in a rectangular grid of cells where each cell is the same size is called
GridLayout
you can use______ within a javadoc comment to apply formatting to the text when it's displayed
HTML tags
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(); } } } (Refer to code example 2-1.) The name of the file that contains this source code must be
InvoiceApp.java
Which of the following files provides the event handlers for an FXML application named Invoice?
InvoiceController.java
What does the following code do? Dimension dim = new Dimension(100, 20); addressField.setPreferredSize(dim); addressField.setMinimumSize(dim);
It prevents the component named addressField from collapsing to a size of zero
a/an _____ component is an invisible component that you can use to group other components
JPanel
which of the following classes provides the basic operations needed to implement a queue?
LinkedList
What exception is thrown by the following statement if the user enters a string that can't be parsed to a double value? double d = Double.parseDouble(totalTextField.getText());
NumberFormatException
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 is not a GUI API for Java?
RIA
Given a GridPane object named grid, which of the following statements creates a Scene object from the grid with a width of 400 and a height of 250?
Scene scene = new Scene(grid, 400, 250);
Which of the following statements uses a Scanner variable named sc to return the next value the user enters at the consolse as a String object and store it in a variable named city?
String city = sc.next();
If the constructor that follows is called, it calls a constructor from which class? public Sailboat(int sails) { super(); this.sails = sails; }
WaterCraft
Which of the following methods of the GridPane class can you use to work with alignment and padding?
a and b only (setAlignment() and setPadding())
which of the following can you not code in a subclass?
a call to a private method of the superclass
What type of component is represented here?
a check box
Which of the following statements is not true?
a combo box can allow multiple items to be selected
Exception in thread "main" java.util.InputMismatchException at 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 this output called?
a stack trace
when you call a method with a parameter list, the arguments in the argument list must be
a, b, and c only (same number, same order, same type)
What class or classes is a method that is declared protected available to?
all classes in the same package and to subclasses
AWT
all of the above
A new dialog box created from the JOptionPane class is always
all of the above (displayed on top of the parent container, modal, blocking)
To add a control to a GridPane object, you must specify
all of the above (the control object to be added, the column index where the control will be displayed, and the row index where the control will be displayed)
you can use the final keyword
all of the above (to prevent a class from being inherited, to prevent a method from being overridden, to prevent a method from assigning a new value to a parameter)
You should consider using a text area instead of a text field when you want to
allow the user to enter multiple lines of text
you should consider using a text area instead of a text field when you want to
allow the user to enter multiple lines of text
its common to store a row of buttons in
an Hbox object
What happens when this statement is executed? Automobile car = new Automobile(1);
an object of the Automobile class is created
When using the GridBagLayout manager, the ________________ field sets where the component is displayed if the component is smaller than the cell that is its display area.
anchor
Using the BigDecimal class, you can
avoid rounding errors that may occur otherwise in business applications
when you add a control or layout manager to a GridPane object, it can
both a and b (span 1 or more rows and span 1 or more columns)
Which of the following statements do you use to jump to the end of a loop from within the loop?
break
a runtime error occurs when
bytecode can't be interpreted properly
If the Loan class contains a final method named calculatePayment, what does the following code do? HomeLoan loan = new HomeLoan(amount, months); loan.calculatePayment();
calls the calculatePayment() method in the Loan class
You code an access modifier on a static method to indicate if it
can be called from other classes
block scope mean that a variable
can't be used outside of the set of braces that it's declared in
What is printed to the console when the code that follows is executed? ArrayList<String> passwords = new ArrayList<>(); passwords.add("akjdk12"); passwords.add("buujl32"); passwords.add("chrcl92"); passwords.add("nnnii87"); passwords.set(2, "cb2kr45"); passwords.remove("akjdk12"); System.out.println(passwords.get(1));
cb2kr45
to include a class in a package, you
code a package statement as the first statement in the class file
Which of the following statements would you use to add a border with a title to a panel named colorPanel?
colorPanel.setBorder(BorderFactory.createTitledBorder("Color");
Given a text area named commentTextArea, which of the following statements would you use to display the value of a string named s in the text area?
commentTextArea.setText(s);
Assume that you have a text field named address1. Which of the following statements gets the text from the text field and stores it in a String object named comments?
comments = address1.getText();
Assume that you have a text area named area. Which of the following statements gets the text from the text area and stores it in a String object named comments?
comments = area.getText();
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
a component that can contain other components is called
container
When you code an anonymous inner class for an event handler, you register the event handler by
creating an Event Handler object that works with the ActionEvent type and passing it to the setOnAction() method
When you code an inner class for an event handler, you register the event handler by
creating an instance of the inner class and passing it to the setOnAction() method
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 of double[] grades = new double[3];
double values
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
What keyword do you use in a class declaration to create a subclass?
extends
You should add all of the panels and components to the frame before calling it's setVisible method. If you don't the user interface may
flicker
What term does Java use to refer to the following component?
frame
What statement should be used to display a JFrame object named frame1?
frame1.setVisible(true);
Which of the following methods would you use to get a List<> object that contains all of the selected elements in a list?
getSelectedValuesList()
in what type of file is javadoc documentation stored
html file
You can use the BorderPane layout manager to lay out controls
in five predefined areas
What field of a GridBagConstraints object specifies the amount of external padding for a component?
insets
Which of the following statements gets the maximum number of Customer objects that the following array can store? Customer[] customers = new Customer[55];
int size = customers.length
Which of the following is not true of generics?
it can be used to create collections that store primitive types
Which of the following statements describes a list box but not a combo box?
it can include scroll bars
Since the sort() method of the Arrays class can sort String objects, what must be true of the String class?
it implements the Comparable interface
which of the following statements is not true about JavaFX?
it is built on top of AWT
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
When a subclass that is not declared as abstract inherits an abstract class,
it must override all of the abstract methods in the abstract class
Which of the following is true about a method that has this declaration? public Employee getDepartmentManager(){...}
it returns an object of the Employee class
What happens when the code that follows is executed? int[] nums = new int[4]; for (int i = 0; i <= nums.length; i++) { nums[i] = i; } System.out.println(nums[2]);
it throws an ArrayIndexOutOfBoundsException
the extension for a Java source file is
java
Which package is automatically available to all Java programs?
java.lang
what component is often used to display a text to identify other components?
label
A ______ is typically stored in a JAR file and contains one or more packages that you want to make available to other projects
library
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
what is the name of the default look and feel provided by Swing?
metal
If the constructor that follows is in the Employee class, what other form of constructor, if any, is implicitly provided? public Employee(String name, int salary){...}
none
to change the size of an array list, you must
none of the above
Which of the following is an invalid list of elements in an array?
"Joe", 3, 25.5
What is the value of s after the following code is executed? ArrayList<String> inventory = new ArrayList<>(); String item = "Computer"; inventory.add(item); inventory.add("Printer"); inventory.add("Monitor"); inventory.add(1, "Mouse"); String s = inventory.get(2);
"Printer"
Which of the following is a valid javadoc comment?
/** Calculates the balance due */
What is the value of nums[2] after the following statements are executed? int[] values = {2, 3, 5, 7, 9}; int[] nums = values; values[2] = 1;
1
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
What is the value of x after the following statements are executed? int x = 5; switch(x) { case 5: x += 4; case 6: x++; break; default: x *= 2; break; }
10
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
How many lines are printed on the console when the following for loop is executed? for (int j = 10; j < 40; j *= 2) { System.out.println(j); }
2
What is the value of the variable named size after the code that follows is executed? LinkedList<Integer> numbers = new LinkedList<>(); numbers.add(44); numbers.add(7); numbers.add(35); numbers.set(1, 29); numbers.removeFirst(); numbers.peek(); int size = numbers.size();
2
What is the initial capacity of the array list that follows? ArrayList<Integer> quantities = new ArrayList<>(20);
20
What is the value of the variable named lists after the statements that follow are executed? String[][] names = new String[200][10]; int lists = names.length;
200
Assume userName equals "Tom" and userAge equals 22. What is printed on the console when the following statement is executed? System.out.println(userAge + " \nis " + userName + "'s age.");
22 is Tom's age.
What is the value of kilos[1] after the code that follows is executed? double[] kilos = {200, 100, 48, 59, 72}; for (int i = 0; i < kilos.length; i++) { kilos[i] *= 2.2; }
220
What is printed to the console when the code that follows is executed? int[] values = {2, 1, 6, 5, 3}; Arrays.sort(values); int index = Arrays.binarySearch(values, 5); System.out.println(index);
3
What is the value of times[2][1] in the array that follows? double[][] times = { {23.0, 3.5}, {22.4, 3.6}, {21.3, 3.7} };
3.7
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
Given the code that follows, what is the value of the shipOption variable if the user has checked the check box named chk1 and selected the radio button named rbo2? if (chk1.isSelected()) { shipOption = 1; } else if (rbo1.isSelected()) { shipOption = 2; } else if (rbo2.isSelected()) { shipOption = 3; } else if (rbo2.isSelected()) shipOption = 4; }
4
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
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.length;
4
If an array list has 500 elements, how many elements will need to be moved to insert an element into position 100?
400
If a linked list has 200 elements, how many elements will need to be accessed to retrieve the 150th element?
51
each element in a linked list
points to the elements both before and after it in the list
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
int 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
After the if statement that follows is executed, what will the value of discountAmount be? double discountAmount = 0.0; double orderTotal = 200.0; if (orderTotal > 200) { discountAmount = orderTotal * .4; } else if (orderTotal > 100) { discountAmount = orderTotal * .3; } else { discountAmount = orderTotal * .2; }
60
How many rows are in the array that follows? Rental[][] transactions = new Rental[7][3];
7
Assume that the variable named entry has a starting value of 9 and number has a value of 3. What is the value of entry after the following statements are executed? if ((entry > 9) || (entry/number == 3)) { entry--; } else if (entry == 9) { entry++; } else { entry = 3; }
8
Which of the following statements is not true?
A border on a panel is required for radio button groups to work properly
What feature allows you to treat an Admin object as though it were an Account object in this inheritance hierarchy?
polymorphism
What is the name of the class that contains this code? private Clock clock; private Alarm alarm; public AlarmClock(Date time){...}
AlarmClock
What is the value of names[4] in the following array? String[] names = {"Jeff", "Dan", "Sally", "Jill", "Allie"};
Allie
Given a Scene object named scene, which of the following statements adds the scene to the Stage object named primaryStage?
primaryStage.setScene(scene);
you can use relational operators to compare
primitive datatype variables
Which of the following statements would you use to declare a list model named productsModel that lets you add and remove Product objects from a list?
private DefaultListModel<Product> productModel;
Which of the following statements creates an array list that can store double values?
ArrayList<Double> sales = new ArrayList<>();
Which of the following statements can be used to create an array list prior to Java 7?
ArrayList<Double> sales = new ArrayList<Double>();
Which of the following is not a difference between arrays and collections?
Arrays can store user-defined objects, but collections can't
the layout manager that uses five areas that can each hold one component is called
BorderLayout
An IDE typically stores all of the files for an application in a
project
which of the following is a valid variable name?
salesTax
what method do you use to set the action that's taken when a window is closed?
setDefaultCloseOperation()
Which of the following methods would you use to set a text field so the user can copy and paste the text it contains but can't change it?
setEditable(false)
To use the binarySearch() method of the Arrays class on an array of ints, you must first
sort the array
The constants of the Pos enumeration can be used to
specify the alignment of a grid
The values held by the attributes of an object describe the object's
state
Given an array of strings named supplies, which of the following statements would you use to create a Swing combo box named suppliesComboBox that contains the elements in the array?
suppliesComboBox = new JComboBox(supplies);
Which of the following statements makes a text field named taxTextField read-only?
taxTextField.setEditable(false);
Which of the following statements selects a radio button named testCheckBox?
testCheckBox.setSelected(true);
Which of the following is not a benefit of using FXML to develop a GUI application?
the code is more efficient
to check if an object is created from the specified class, you can use
the instanceof keyword
if you use a short-circuit operator to combine two expressions
the second expression is evaluated only if it can affect the result
a compile time error occurs when
there's a syntax error in a java statement
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 true about containers?
they must be windows
Which of the following is not a reason to create a package?
to prevent other developers from using the class
you must use the this keyword
to refer to an instance variable from a method when it has the same name as a method parameter
an enhanced for loop can only be used
to work with all the elements of an array
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
you should validate user entries rather than catch and handle exceptions caused by invalid entries whenever possible because
your code will run faster
which of the following classes is NOT in the inheritance hierarchy for all Swing components?
Control
Which of the following is a valid class name?
CustomerMaintApp