Practice Java II Final Exam
public static double computeSavings(double amt, int years, double rate, double total) { if (years == 0) return total; else { ______code here________ } } Given the method named computeSavings(), write the appropriate condition statements of the total value of the investment before you start saving and the return statement of the computeSavings() method.
// Calculate the total for the current year with interest. double newTotal = total * (1 + rate) + amt; // Recursive call, decrementing the years. return computeSavings(amt, years - 1, rate, newTotal);
The first call sends a substring of the original string from position _____ up to the space. a. 1 b. 3 c. 0 d. 2
0
_____ helps place components in rows. a. A flow layout manager b. A border layout manager c. A window decoration d. The look-and-feel method
A flow layout manager
What might be a reason that a programmer would select one approach(iterative or recursive) over another?
A programmer might choose between iterative and recursive approaches based on several factors, such as simplicity, clarity, performance, memory constraints, and context. 1.Simplicity and Clarity: Recursive solutions can be more intuitive and easier to read for problems that naturally fit a recursive pattern, such as tree traversal, factorial calculation, or Fibonacci sequence. Iterative solutions are often more straightforward for iterative processes, like loops or repetitive operations. 2.Memory Constraints: Recursive approaches use the call stack to keep track of recursive calls, which can lead to stack overflow in cases of deep recursion. This is a concern for memory-constrained environments. Iterative approaches use a fixed amount of memory, avoiding the risk of stack overflow, which makes them more suitable for problems with potentially deep recursion. 3.Performance: Recursive solutions might incur additional overhead due to function calls and stack management, potentially impacting performance. Iterative solutions tend to be more efficient for problems where the overhead of recursion outweighs its benefits.
Define recursive method with an example.
A recursive method is a function that calls itself either directly or indirectly to solve a problem by breaking it into smaller, more manageable sub-problems. The recursive approach is commonly used in scenarios where the problem can be divided into similar sub-problems and is particularly effective for tasks involving hierarchical structures, like trees or directories, and iterative sequences, like calculating factorials. def factorial(n): if n == 0: return 1 # Base case: 0! is 1 else: return n * factorial(n - 1) # Recursive case
Describe recursion with the advantages and disadvantages.
Advantages: -Simplicity -Conciseness -Problem Decomposition Disadvantages: -Memory Consumption -Performance -Complexity in Debugging -Not Always Intuitive
Declare an ArrayList with an example.
ArrayList<String> cities = new ArrayList<>();
What is the default layout manager for a JFrame? a. GridLayout b. FlowLayout c. FrameLayout d. BorderLayout
BorderLayout
Recall that you can stop execution of an infinite loop by pressing _____ and _____. a. Ctrl, C b. Alt, C c. Ctrl, V d. Alt, V
Ctrl, C
A class that can react to ActionEvents includes an addKeyListener() method. a. True b. False
False
A generic method's type parameter can be a primitive data type. a. True b. False
False
A type parameter section in a class header contains curly braces. a. True b. False
False
ArrayList is an abstract class. a. True b. False
False
Collection contains all the methods of List. a. True b. False
False
Collections and arrays both have a size that can increase. a. True b. False
False
If a user enters more characters than specified in a JTextField, the extra characters are deleted. a. True b. False
False
Iterative programs always require more lines of code than recursive ones. a. True b. False
False
Programs that use recursion usually run more quickly than those that do not. a. True b. False
False
The Container class is a child of the Object class, and the Component class is a child of the Container class. a. True b. False
False
The case in a recursive method that does not make a recursive call is the zero case. a. True b. False
False
When a JFrame is closed, you can end a program that you have forgotten to exit by pressing Alt+E. a. True b. False
False
When a user closes a JFrame by clicking the Close button in the upper-right corner, the default behavior is for the JFrame to close and the application to terminate. a. True b. False
False
The _____ responds to keyboard focus events. a. KeyListener b. ActionListener c. ChangeListener d. FocusListener
FocusListener
Which class is the immediate parent of JFrame? a. Container b. Component c. Frame d. Window
Frame
Which programming is a style of computer programming in which code is written with data types to be specified later? a. iterator b. dynamic c. interface d. Generic
Generic
How do you change the text of a JLabel? Provide an example.
In Java's Swing library, a JLabel is used to display text or images in a user interface. To change the text of a JLabel, you can use its setText() method. This method allows you to update the text displayed by the label at any time. label.setText("Text Changed");
How do you modify a JTextField to make it editable or not editable?
In Java's Swing library, a JTextField is used for single-line text input. By default, it is editable, allowing users to type text into it. To change whether a JTextField is editable, you can use the setEditable() method, passing true to make it editable or false to make it non-editable (read-only). boolean isEditable = textField.isEditable(); textField.setEditable(!isEditable); // Update the button text based on the new state toggleButton.setText(isEditable ? "Make Editable" : "Make Non-Editable"); }
Write the statement to create a JButton named submitButton with the label Submit your data.
JButton submitButton = new JButton("Submit your data");
A _____ consists of a label positioned beside a square; you can click the square to display or remove a check mark. a. ButtonGroup b. RadioButton c. JComboBox d. JCheckBox
JCheckBox
A _____ is a component that combines a button or an editable field and a drop-down list. a. JCheckBox b. JComboBox c. JButton d. JTextBox
JComboBox
Which statements create a JLabel that holds the words Happy birthday and adds the greeting to a JFrame object named aGreeting? a. JLabel mygreeting = aFrame.add(mygreeting); new JLabel("Happy Brithday"); b. JLabel mygreeting = new Frame("Happy Brithday"); c. JLabel("Happy Brithday"); aGreeting.add(Label); d. JLabel mygreeting = new JLabel("Happy Birthday"); aGreeting.add(mygreeting);
JLabel mygreeting = new JLabel("Happy Birthday"); aGreeting.add(mygreeting);
Which is the immediate parent class of JTextField? a. JTextComponent b. JComponent c. Container d. JFrame
JTextComponent
Write the statement to provide a JTextField object named myInfo that allows enough room for a user to enter 15 characters.
JTextField myInfo = new JTextField(15);
The Swing classes are part of a more general set of UI programming capabilities that are collectively called the _____. a. JavaX Classes b. Java Foundation Classes c. UI packages d. Java Extension Libraries
Java Foundation Classes
The _____ responds to keyboard events. a. KeyListener b. ActionListener c. ChangeListener d. FocusListener
KeyListener
Which of the following can be a useful technique to work through strings and analyze portions of them? a. Execution b. Iteration c. Recursion d. overhead
Recursion
All of the following classes contain a built-in compareTo() method except _____. a. Integer b. String c. Scanner d. Double
Scanner
Which of the following is true? a. The ArrayList class works better than a LinkedList when you have to randomly retrieve a lot of data. b. The ArrayList class works better than a LinkedList when you have to sequentially retrieve a lot of data. c. An ArrayList always works more efficiently than a LinkedList. d. An ArrayList always is less efficient than using a LinkedList.
The ArrayList class works better than a LinkedList when you have to randomly retrieve a lot of data.
An ArrayList is dynamically resizable. a. True b. False
True
An indirect recursion occurs when a method calls another method that eventually results in the original method being called again. a. True b. False
True
Each Swing component is a descendant of a JComponent. a. True b. False
True
If s.indexOf(' ') returns 4, a space has been located in String s. a. True b. False
True
Java provides you with a Font class from which you can create an object that holds typeface and size information. a. True b. False
True
The cases in a recursive method that make recursive calls are recursive cases. a. True b. False
True
The default behavior of a JFrame is to use the border layout format, which divides a container into regions. a. True b. False
True
Useful recursive methods must have a way to stop infinite repetition. a. True b. False
True
When setting a JFrame's size, part of the area is unusable because it is consumed by the JFrame's title bar and borders. a. True b. False
True
You can use the setEnabled() method to make a component available or unavailable by passing true or false to it, respectively. a. True b. False
True
When constructing a Font object, which of the following arguments is not required? a. Typeface b. Style c. Weight d. Point size
Weight
You can call a JFrame's setDefaultCloseOperation() method and use _____ as an argument to keep the JFrame visible and continue running the program. a. JFrame.EXIT_ON_CLOSE b. WindowConstants.DISPOSE_ON_CLOSE c. WindowConstants.DO_NOTHING_ON_CLOSE d. WindowConstants.HIDE_ON_CLOSE
WindowConstants.DO_NOTHING_ON_CLOSE
_____ are written completely in Java and do not have to rely on the local operating system code. a. Lightweight components b. Window decorations c. Layout managers d. Event handlers
a. Lightweight components
The default capacity of an ArrayList is 10 items. a. True b. False
a. True
The notation mathematicians use to indicate factorials is a/an _____. a. exclamation point b. question mark c. ampersand d. hyphen
a. exclamation point
The ActionListener interface contains the _____ method specification. a. actionOccurred(Action e) b. actionPerformed(ActionEvent e) c. actionEvent(ActionEvent e) d. action(Event e)
actionPerformed(ActionEvent e)
The JButton, JCheckBox, JComboBox, and JRadioButton components are associated with the _____ method. a. addAdjustmentListener() b. addChangeListener() c. addWindowListener() d. addItemListener()
addItemListener()
The List interface _____. a. allows items to be inserted after creation b. cannot contain duplicate elements c. does not allow items to be removed d. cannot contain more than 100 elements
allows items to be inserted after creation
An ArrayList can hold _____. a. any primitive type b. any numeric type c. any object type d. only 10 objects
any object type
The Iterator _____ method determines whether another element exists in a collection without retrieving it. a. next() b. hasNext() c. remove() d. get()
b. hasNext()
Which of the following cases in a recursive method does not make a recursive call? a. primary case b. base case c. extraordinary case d. negative case
base case
Computer programmers use the word _____ to describe a group of objects that can be operated on together. a. collection b. assemblage c. anthology d. collision
collection
Computing factorials lends itself to recursion because _____. a. it is impossible to compute a factorial using a loop b. recursion is most useful for all mathematical computations c. computing the factorial of any number relies on computing the factorial of a simpler case d. the series of if statements required to compute a factorial iteratively would be lengthy
computing the factorial of any number relies on computing the factorial of a simpler case
If you want to place a series of characters running diagonally down the screen, then which loop is used? a. conventional b. detection c. addressable d. enhanced
conventional
The number of times that a method calls itself is the _____ of the recursion. a. iterative b. intensity c. depth d. context
depth
An application requests a user's telephone number. Some users might enter their numbers with embedded dashes, and some might enter just digits. If you want a uniform format for stored phone numbers, then what can you remove from the strings that contain them? a. embedded dashes b. embedded questions c. embedded ampersands d. embedded hyphens
embedded dashes
Every useful recursive method must have a way to finally _____. a. start b. end c. generate d. migrate
end
The _____ loop creates an iterator to cycle through a list. a. for b. each c. foreach d. eachfor
foreach
Which of the following is a picture that is created by using infinite copies of itself? a. recursion b. fractal c. factorial d. overhead
fractal
Look and feel comprises the elements of design, style, and _____ in any user interface. a. font faces b. functionality c. logistics d. syntactic sugar
functionality
Which of the following method doesn't create an Iterator object that has access? a. hasNext() b. next() c. remove() d. get()
get()
Within an implementation of the itemStateChanged()method, you can use the _____ method to determine which object generated the event and the getStateChange() method to determine whether the event was a selection or a deselection. a. getSource() b. getEvent() c. getItem() d. getState()
getItem()
A method that executes because it is called automatically when an appropriate event occurs is an event _____. a. responder b. listener c. handler d. source
handler
A _____ requires interaction with the local operating system. a. border layout manager b. flow layout manager c. lightweight component d. heavyweight component
heavyweight component
Which of the following statements will change the value displayed in a JLabel named hello? a. hello.setText("Hello"); b. setText.hello = "Hello" c. hello = setText("Hello"); d. setText = hello
hello.setText("Hello");
Sort an ArrayList using the Collections.sort() method with the statements.
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class ArrayListSorting { public static void main(String[] args) { // Create an ArrayList of integers ArrayList<Integer> numbers = new ArrayList<>(); // Add some numbers to the ArrayList numbers.add(5); numbers.add(2); numbers.add(8); numbers.add(1); numbers.add(3); // Sort in ascending order Collections.sort(numbers); System.out.println("Sorted in ascending order: " + numbers); // Sort in descending order Collections.sort(numbers, Collections.reverseOrder()); System.out.println("Sorted in descending order: " + numbers); } }
Which of the following recursions occurs when a method calls another method that eventually results in the original method being called again? a. overhead b. iterative c. direct d. indirect
indirect
A difference between a collection and an array is that a collection _____. a. can hold references b. can be passed to a method c. is dynamically resizable d. can hold primitive data types
is dynamically resizable
An advantage of using the ArrayList class over the Arrays class is that an ArrayList _____. a. can hold more elements b. is dynamically resizable c. supports use with indexes d. requires less memory
is dynamically resizable
The approach to writing nonrecursive methods that include loops to produce results is _____. a. sequential b. iterative c. object-oriented d. procedural
iterative
An object that can be used as a foreach loop to process the elements in a Collection is a(n) _____. a. index b. subscript c. repeater d. iterator
iterator
A generic method _____. a. must have a type parameter that represents a reference type b. must return a generic parameter c. must have an empty body that is created at runtime d. can have no more than one type parameter
must have a type parameter that represents a reference type
Which of the following statements will correctly set a JFrame named myFrame to be visible? a. myFrame.Visible = True b. myFrame.setVisible(true) c. myFrame.Visibility.True d. myFrame.true = Visible
myFrame.setVisible(true)
If you have declared an ArrayList of Strings named myStrings, which of the following is NOT a legal method call? a. myStrings.add("tomato"); b. myStrings.remove("tomato"); c. int s = myStrings.size(); d. myStrings.add(5, "leek");
myStrings.add(5, "leek");
The Iterator _____ method retrieves the next element in a collection. a. remove() b. get() c. next() d. hasNext()
next()
If the parameter is NOT 0, the method returns the value of the parameter added to the return value of a new method call with a value that is for which of the following parameters? a. one less than b. one more than c. two less than d. two more than
one less than
The excess computation time required for repeated method calls in recursive programs is called _____. a. overload b. backup c. overhead d. liability
overhead
The factorial of a nonnegative integer is the _____ of all the integers from 1 up to and including the integer. a. list b. sum c. product d. reverse list
product
By using the code given, explain how to create a generic class. public class TestGenericClass { public static void main (String[ ] args) { Book book = new Book("The Hunger Games"); GenericClass<Integer> integerObj = new GenericClass<Integer>(37); GenericClass<String> stringObj = new GenericClass<String>("Zebra"); GenericClass<Book> bookObj = new GenericClass<Book>(book); System.out.println("The integer is " + integerObj.getObject()); System.out.println("The String is " + stringObj.getObject()); System.out.println("The Book is " + bookObj.getObject().getTitle());
public class GenericClass<T> { private T object; // The generic type instance variable // Constructor to initialize the object public GenericClass(T object) { this.object = object; } // Getter method to retrieve the object public T getObject() { return object; } }
Which of the following cases in a recursive method make recursive calls? a. recursive cases b. base cases c. relative cases d. positive cases
recursive cases
A programmer might choose an iterative approach to a problem rather than a recursive one because iterative programs often _____. a. run more quickly b. is faster to write c. contains more code d. impresses the boss
run more quickly
Which method overrides the default behavior for the JFrame to be positioned in the upper-left corner of the computer screen's desktop? a. setSize() b. title() c. setBounds() d. isResizable()
setBounds()
Which method sets the state of the JCheckBox to true for selected or false for unselected? a. isSelected b. getSelected c. setSelected d. setState
setSelected
Recursion is often used when a problem's solution relies on a _____. a. more complicated solution to the same problem b. simpler solution to the same problem c. later solution to part of the problem d. value that is user input
simpler solution to the same problem
Recursion can be successfully used to _____. a. solve mathematical problems b. create visual patterns c. solve mathematical problems and to create visual patterns d. neither solve mathematical problems nor create visual patterns
solve mathematical problems and to create visual patterns
Within an event-driven program, a component on which an event is generated is the _____ of the event. a. handler b. driver c. listener d. source
source
If the indexOf () method returns a positive value, then there is a/an _____ in the String at the value's position. a. hyphen b. space c. dash d. ampersand
space
Which of the following methods doesn't work just like they do with an ArrayList. a. add() b. remove() c. set() d. string()
string()
A generic method _____. a. resides in a generic class b. cannot be overloaded c. can contain only one parameter d. uses at least one type of parameter
uses at least one type of parameter
Which method do you use to change the state of a JCheckBox? a. void setSelected(boolean) b. oolean isSelected() c. void setText(String) d. String getText()
void setSelected(boolean)
If you want to use Collections.sort() with a class you have created, you must _____. a. write your own compareTo() method b. overload the < and > operators c. write your own toString() method d. write both a compareTo() method and toString() method
write your own compareTo() method
When you create a class from which you will instantiate objects to store in an ArrayList, _____. a. you must create a toString() method b. you must create a compareTo() method c. you must create both a toString() method and a compareTo() method d. you are not required to create either a toString() method or a compareTo() method
you must create both a toString() method and a compareTo() method