COSC 1437 Java Final
javac MyClass.java Before entering the command, you must? A.Make sure you are in the same directory or folder where the MyClass.java file is located B. Save the program with the .comp extension C.Close all other Windows on your computer system. D.Execute the java.sun.com program
A
A sentinel value _________ and signals that there are no more values to be entered. A) is a different data type than the values being processed B) is a special value that cannot be mistaken as a member of the list C) indicates the start of a list D) guards the list
B
A(n) ________ is a special value that cannot be mistaken as a member of a list of data items and signals that there are no more data items from the list to be processed. A. terminator B. sentinel C. accumulator D. delimiter
B
A(n) ________ is used as an index to pinpoint a specific element within an array. Question options: A. boolean value B. subscript C. element D. range
B
An array of String objects A. must be initialized when the B. consists of an array of references to String objects C. is arranged the same as an array of primitive objects D. is compressed to 4 bytes for each element.
B
Enclosing a group of statements inside a set of braces creates A. an expression B. a block of statements C. an if-else statement D. a relational operator
B
Event listeners must: A) Not receive any argument B) Implement an interface C) Exit the application once it handled the event D) Be included in private inner classes
B
If object1 and object2 are objects of the same class, to make object2 a copy of object1 A) Assign object1 to object2, object2 = object1; B) Write a copy method that will make a field by field copy of object1 data members into object2 data members C) Use the Java copy method that is a part of the Java language D) Use the default constructor to create object2 with object1 data members
B
If object1 and object2 are objects of the same class, to make object2 a copy of object1 Question options: A. use the copy method that is a part of the Java API. B. write a method for the class that will make a field by field copy of object1 data members into object2 data members. C. use an assignment statement to make object2 a copy of object1. D. use the default constructor to create object2 with object1 data members.
B
In the following Java statement what value is stored in the variable name? String name = "John Doe"; A."name" B.the memory address where "John Doe" is located C."John Doe" D.the memory address where name is located
B
The "has a" relationship is sometimes called a(n) ________ because one object is part of a greater whole. A. mutual relationship B. whole-part relationship C.possession D.enterprise
B
The JVM periodically performs this process to remove unreferenced objects from memory. A. system restore B.garbage collection C. memory shuffling D. memory sweeping
B
The ________ is ideal in situations where the exact number of iterations is known. A. posttest loop B. for loop C. do-while loop D. while loop
B
The ________ loop is ideal in situations where you always want the loop to iterate at least once. A. pretest B. do-while C. while D. for
B
The sequential search algorithm A. requires the array to be in ascending ordered B. uses a loop to sequentially step through an array,starting with the first element C. returns 1 if the value being search for is found, otherwise it returns -1. D. All of the above
B
This is a special language used to write computer programs. A.Application B.Programming Language C.Pseudocode D.Operating System
B
This statement tells the compiler where to find the JOptionPane class and makes it available to your program. A. import javax.JOptionPane; B.Import javax.swing.JOptionPane; C.import JOptionPance; D.import Java.Swing.JOptionPane;
B
What is the result of the following expression? A.8 B.7 C.12 D.105
B
Which Scanner class method reads a String? A.nextString B.nextLine C.getLine D.charAt
B
enum Tree {OAK, MAPLE, PINE} What is the ordinal value of the MAPLE enum constant? A) 0 B) 1 C) 2 D) 3 E) Tree.MAPLE
B
final int x = 22, y = 4; y += x; System.out.println("x = " + x + ", y = " + y); A.x=22,y=88 B.x=22,y=26 C.x=22,y=4 D.Nothing.
B
int x = 5, y = 20; x += 32; y /= 4; System.out.println("x = " + x + ", y = " + y); A.x=160,y=80 B.x=37,y=5 C.x=32,y=4 D.x=9,y=52
B
If, within one try statement you want to have catch clauses of the following types, in which order should they appear in your program: (1) Exception (2) IllegalArgumentException (3) RuntimeException (4) Throwable
B. 2 3 1 4
What will be the result of the following code? FileOutputStream fstream new FileOutputStream("Output.dat"); DataOutputStream outputFile = new DataOutputStream(fstream);
B. The outputFile variable will reference an object that is able to write binary data to the Output.dat file.
To serialize an object and write it to the file, use this method of the ObjectOutputStream class.
B. WriteObject
The IllegalArgumentException class extends the RuntimeException class, and is therefore:
B. an unchecked exception class
A(n) ________ is an object that is generated in memory as the result of an error or an unexpected event.
B. exception
The try statement may have an optional ____________ clause, which must appear after all of the catch clauses.
B. finally
What will be displayed when the following code is executed? double x = 45678.259; DecimalFormat formatter = new DecimalFormat("#,##0.0"); JOptionPane.showMessageDialog(null,formatter.format(x)); A. 45,678.26 B. 45678.259 C. 45,678.259 D. 45,678.3
D
What will be returned from the method, if the following is the method header? public Rectangle getRectangle() A. the values stored in the data members of the Rectangle object B. a null value C. an object that is contained in the class Rectangle D. the address of an object of the Rectangle class
D
When an array is passed to a method A. it is passed just as any other object would be B. a reference to the array is passed C. the method has direct access to the original array D. All of the above
D
What will be returned from the method, if the following is the method header? public Rectangle getRectangle() Question options: A. the values stored in the data members of the Rectangle object B. a null value C. an object that is contained in the class Rectangle D. the address of an object of the Rectangle class
D.
If a method does not handle a possible checked exception, what must the method have?
D. A throws clause in its header
1. In object-oriented programming, _____ allows you to extend the capabilities of a class by creating another class that is a specialized version of it.
Inheritance
A method that gets a value from a class's field but does not change it is a mutator method.
Instance Methods
The scope of a private instance field is:
Instance methods of the same class
13. When a class implements an interface, an inheritance relationship known as ____ is established.
Interface inheritance
Which of the following is NOT true about static methods? They are created by placing the key word static after the access specifier in the method header. They are called directly from the class. They are often used to create utility classes that perform operations on data, but have no need to collect and store data. It is necessary for an instance of the class to be created to execute the method.
It is necessary for an instance of the class to be created to execute the method.
8. A subclass can directly access?
Only public and protected member of the superclass
3. The actions performed by the JVM that take place with each method call are sometimes referred to as this.
Overhead
A special variable that holds a value being passed into a method is called what?
Parameter
4. In Java, a reference variable is ____ because it can reference objects of types different from its own, as long as those types are related to its type through inheritance.
Polymorphic
Data stored in an object are called _____.
Fields
Returning Arrays from methods
In addition to accepting arrays as arguments, methods may also return arrays. public static double[] getArray() { double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 }; return array; } values = getArray();
12. All methods specified by an interface are?
Public
9. Which of the following statements declares Salaried as a subclass of PayType?
Public class Salaried extend PayType
This type of operator determines whether a specific relationship exists between two values:
Relational
Assuming the following declaration exists: enum Seasons { SPRING, WINTER, SUMMER, FALL } what is the fully qualified name of the FALL constant
Seasons.FALL
If you do not specify delimiters in the StringToken constructor, which of the following cannot be a delimiter?
Semicolon
ArrayList Class's toString method
The ArrayList class has a toString method that returns a string representing all of the items stored in an ArrayList objec
Inserting an item
The ArrayList class has an overloaded version of the add method that allows you to add an item at a specific index. nameList.add(1, "Mary");
Replacing an item
The ArrayList class's set method can be used to replace an item at a specific index with another item nameList.set(1, "Becky");
Assume the class BankAccount has been created, and the following statement correctly creates an instance of the class: BankAccount account = new BankAccount(5000.0); What is true about the following statement? System.out.println(account);
The account object's toString method will be implicitly called
Assume the class BankAccount has been created, and the following statement correctly creates an instance of the class: BankAccount account = new BankAccount(5000.0); What is TRUE about the following statement? System.out.println(account); The account object's toString method will be implicitly called. A compiler error will occur. The method will display unreadable binary data on the screen. A runtime error will occur.
The account object's toString method will be implicitly called.
The key word 'this' is the name of a reference variable that an object can use to refer to itself. T or F?
True
True or False: A private class that is defined inside another class is not visible to code outside the outer class.
True
True or False: Enumerated data types are actually special types of classes.
True
True or False: When an object is passed as an argument to a method, the method can access the argument
True
Trying to extract more tokens than exist from a StringTokenizer object will cause an error.
True
When an array of objects is declared, but not initialized, the array values are set to null. T or F
True
When the continue statement is encountered in a loop it causes a loop to stop its current iteration and begin the next one. T or F
True
When working with the String and StringBuilder class's getChars method, the character at the start position is included in the substring, but the character at the end position is not included.
True
he ActionEvent argument that is passed to an action listener's actionPerformed method is the event object that was generated in response to an event. T or F
True
15. In ______, inheritance is shown with a line that has an open arrowhead at one end that points to the superclass
UML diagram
Two ways of concatenating two Strings are:
Use the concat method or use the + between the two Strings
Assuming that str is declared as follows, String str = "RSTUVWXYZ"; What value will be returned from str.charAt(5)?
W
What will be displayed after the following code is executed? String str = "RSTUVWXYZ";
W
What will be displayed after the following statements are executed? StringBuilder strb = new StringBuilder("We have lived in Chicago, Trenton, and Atlanta."); strb.replace(17, 24, "Tampa"); System.out.println(strb);
We have lived in Tampa, Trenton, and Atlanta.
What will be displayed after the following statements are executed? Stringbuilder strb=
We have lived in Tampa, Trenton, and Atlanta.
If you want to append data to the existing binary file, BinaryFile.dat, use the following statements to open the file.
c. FileOutputStream fstream = new FileOutputStream("BinaryFile.dat", true); DataOutputStream binaryOutputFile = new DataOutputStream(fstream);
The throw statement informs the compiler that a method throws one or more exception. (T/F)
false
The throws clause causes an exception to be thrown (T/F)
false
2. When a method is declared with the _____ modifier, it cannot be overridden in a subclass.
final
8. Classes that inherit from the Error class are
for exceptions that are thrown when a critical error occurs, and the application program should not try to handle them.
The JVM periodically performs this process to remove unreferenced objects from memory. memory sweeping system restore memory shuffling garbage collection
garbage collection
The JVM periodically performs this process, which automatically removes unreferenced objects from memory
garbage collection
5. An exception object's default error message can be retrieved using this method.
getMessage
The term for the relationship created by object aggregation is: is a Sub-class object has a Inner class
has a
Assume that the variable checkbox references a JCheckBox object. To determine whether the check box has been selected, use the following code:
if (checkBox.isSelected()) {/code to execute, if selected/}
To use the StringTokenizer class you must have the following import statement.
import java.util.StringTokenizer;
Which of the following import statements is required to use the StringTokenizer class?
import java.util.StringTokenizer;
Which of the following import statements is required to use the StringTokenizer class? import java.text.DecimalFormat; import java.util.Scanner import javax.swing.JOptionPane; import java.util.StringTokenizer;
import java.util.StringTokenizer;
A class that is defined inside of another class is called a(n)
inner class or nesting
Which of the following statements converts a String object variable named str to an int and stores the value in the variable x?
int x = Integer.parseInt(str);
Which of the following statements converts a String object variable named str to an int and stores the value in the variable x? int x = str; int x = Integer.integer(str); int x = Integer.parseInteger(str); int x = Integer.parseInt(str);
int x = Integer.parseInt(str);
What will be displayed after the following code has been executed? String str1 = "The quick brown fox jumped over the lazy dog."; String str2 = str1.substring(20, 26); System.out.println(str2);
jumped
When writing a string to a binary file or reading a string from a binary file, it is recommended that you use
methods that use UTF-8 encoding
When writing a string to a binary file or reading a string from a binary file, it is recommended that you use
methods that use UTF-8 encoding.
Beginning in Java 7, you can use ________ to reduce a lot of duplicated code in a try statement that needs to catch multiple exceptions, but perform the same operation for each one.
multi-catch
Add an item to an ArrayList
nameList.add("James"); nameList.add("Catherine"); nameList.add("Bill");
Summing the columns of a two-dimensional array
nested loops. The outer loop controls the column subscript and the inner loop controls the row subscript. The inner loop calculates the sum of a column, which is stored in an accumulator.
13. When an exception is thrown by code in the try block, the JVM begins searching the trystatement for a catch clause that can handle it and passes control of the program to
the first catch clause that can handle the exception.
A static field is created by placing: the key word static after the field name the key word static after the access specifier and before the field's data type the key word static after the access specifier and field's data type it in a static field block
the key word static after the access specifier and before the field's data type
The toString Method
the method returns a string that represents the state of an object. state: the data that is stored in the object's fields at any given moment.
Variable-Length Argument Lists
variable-length argument lists, which makes it possible to write a method that takes a variable number of arguments
Capacity
which is the number of items it can store without having to increase its size. - When an ArrayList object is first created, using the no-arg constructor, it has an initial capacity of 10 items. -You can specify a different starting capacity, if you desire, by passing an int argument to the ArrayList constructor. ArrayList<String> list = new ArrayList<String>(100);
Two-Dimensional Arrays
- A two-dimensional array is an array of arrays. It can be thought of as having rows and columns - 2D arrays, can hold multiple sets of data - To declare a two-dimensional array, two sets of brackets and two size declarators are required: The first one is for the number of rows and the second one is for the number of columns double[][] scores = new double[3][4]; - To access one of the elements in a two-dimensional array, you must use both subscripts scores[2][1] = 95;
String Arrays
- An array of String objects may be created, but if the array is uninitialized, each String in the array must be created individually. String[] names = { "Bill", "Susan", "Steven", "Jean" }; - In order to use a String object, you must have a reference to the String object.
Create and Use an ArrayList Object
- Create ArrayList<String> nameList = new ArrayList<String>();
three or more dimensions arrays
- It is possible to create arrays with multiple dimensions, to model data that occurs in multiple sets double[][][] seats = new double[3][5][8];
Command-line Arguments
- It is not required that the name of main's parameter array be args. You can name it anything you wish. It is a standard convention, however, for the name args to be used -
Binary search
- Its only requirement is that the values in the array must be sorted in ascending order. - Instead of testing the array's first element, this algorithm starts with the element in the middle.
Array Initialization
- Like regular variables, Java allows you to initialize an array's elements when you create the array. int[ ] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - This statement declares the reference variable days, creates an array in memory, and stores initial values in the array. The series of values inside the braces and separated with commas is called an initialization list. - Note that you do not use the NEW key word when you use an initialization list - Java allows you to spread the initialization list across multiple lines.
Comparing Arrays
- To compare the contents of two arrays, you must compare the elements of the two arrays. // First determine whether the arrays are the same size. if (firstArray.length != secondArray.length) arraysEqual = false; // Next determine whether the elements contain the same data. while (arraysEqual && index < firstArray.length) { if (firstArray[index] != secondArray[index]) arraysEqual = false; index++; } if (arraysEqual) System.out.println("The arrays are equal."); else System.out.println("The arrays are not equal.");
Passing Arrays as Arguments to Methods
- To pass an array, you pass the value in the variable that references the array. showArray(numbers);
Input and Output array contents
- You can read values from the keyboard and store them in an array element just as you can a regular variable. - You can also output the contents of an array element with print and println.
Arrays of Objects
- You may create arrays of objects that are instances of classes that you have written. - Objects in an array are accessed with subscripts, just like any other data type in an array.
Copying Arrays
- reference copy: both the array1 and array2 variables will reference the same array. - Only the address of the array object is copied, not the contents of the array object.
What will be the value of loc after the following code is executed? int loc; String str = "The cow jumped over the moon."; loc = str.lastIndexOf("ov", 14);
-1
What will be the value of position after the following code is executed? int position; String str = "The cow jumped over the moon."; position = str.lastIndexOf("ov", 14);
-1
If the following is from the method section of a UML diagram, which of the following statements is true? + equals(object2:Stock) : boolean A. This is a private method that returns a boolean value. B. This is a private method that receives two objects from the Stock class and returns a boolean value. C. This is a public method that accepts a Stock object as its argument and returns a boolean value. D. This is a public method that returns a reference to a String object.
...
Write the contents of each element of the numbers array to a file
// Open the file. PrintWriter outputFile = new PrintWriter("Values.txt"); // Write the array elements to the file. for (int index = 0; index < numbers.length; index++) outputFile.println(numbers[index]); // Close the file. outputFile.close();
Java automatically stores this value in all uninitialized static member variables: null 0 -1 false
0
Look at the following declaration: enum Tree { OAK, MAPLE, PINE } What is the ordinal value of the MAPLE enum constant? 0 1 2 3 Tree.MAPLE
1
What will be the value of loc after the following code is executed? int loc; String str = "The cow jumped over the moon."; loc = str.indexOf("ov");
15
What will be the value of position after the following code is executed? position=str.indexOf("ov");
15
The no-arg constructor for a StringBuilder object gives the object enough storage space to hold this many characters.
16 characters
For the following code, how many times would the while loop execute? StringTokenizer strToken = new StringTokenizer("Ben and Jerry's ice cream is great."); while (strToken.hasMoreTokens()) { System.out.println(strToken.nextToken()); }
7
For the following code, how many times would the while loop execute? StringTokenizer strToken = new StringTokenizer("Cars, trucks, and SUVs " + "are all types of automobiles."); while (strToken.hasMoreTokens()) { System.out.println(strToken.nextToken()); }
9
int x = 5, y = 28; float z; z = (float) (y / x); A.5.6 B.5.60 C.5.0 D.3.0
A
When a method's return type is a class, what is actually returned to the calling program? An object of that class A reference to an object of that class Only the values in the object that the method accessed Nothing, the return type is strictly for documentation in this situation.
A reference to an object of that class
Selection sort and binary search
A sorting algorithm is used to arrange data into some order. A search algorithm is a method of locating a specific item in a larger collection of data. The selection sort and the binary search are popular sorting and searching algorithms.
The length field in a two-dimensional array
A two-dimensional array, however, has multiple length fields. It has a length field that holds the number of rows, and then each row has a length field that holds the number of columns
To read data from a binary file you create objects from the following classes:
A. FileInputStream and DataInputStream
The numeric classes' "parse" methods all throw an exception of this type if the string being converted does not contain a convertible numeric value.
A. NumberFormatException
Unchecked exceptions are those that inherit from:
A. a. the Error class or the RuntimeException class.
When you write a method that throws a checked exception, you must:
A. have a throws clause in the method header.
The ability to catch multiple types of exceptions with a single catch is known as ____________, and was introduced in Java 7.
A. multi catch
The catch clause
All of the above i. starts with the word catch followed by a parameter list in parentheses containing anExceptionType parameter variable. ii. contains code to gracefully handle the exception type listed in the parameter list. iii. follows the try clause
The catch clause:
All of the above.
A deep copy of an object is:
An operation that copies an aggregate object and all objects it references
7. All fields declared in an interface?
Are treated as final and static
Values that are sent into a method are called ________.
Arguments
If the main method calls method A, and method A calls method B, what happens when method B finishes? A) control is returned to the main method B) control is returned to method A C) an IOException is thrown D) the program terminates
B
Why does the following code cause a compiler error? try { number = Integer.parseInt(str); } catch (IllegalArgumentException e) { System.out.println("Bad number format."); } catch (NumberFormatException e) { System.out.println(str + " is not a number."); }
B. Because NumberFormatException inherits from IllegalArgumentException. The code should handle NumberFormatException before IllegalArgumentException.
Look at the following code: FileInputStream fstream = new FileInputStream("MyInfo.dat"); DataInputStream inputFile = new DataInputStream(fstream); This code can also be written as:
B. DataInputStream inputFile = new DataInputStream(new FileInputStream("MyInfo.dat"));
All exceptions are instances of classes that extend this class
B. Throwable
If the program does not handle an unchecked exception:
B. the program is halted and the default exception handler handles the exception.
In a catch statement, what does the following code do? System.out.println(e.getMessage());
B.It prints the error message for an exception.
What will be the result of the following statements? FileInputStream fstream = new FileInputStream("DataIn.dat"); DataInputStream inFile = new DataInputStream(fstream);
B.The inFile variable will reference an object that is able to read binary data from the Input.dat file.
A declaration for an enumerated type begins with this keyword. A) enumerated B) enum_type C) enum D) ENUM
C
You may use this to compare two enum data values. A. the==,> and < operators B.the moreThan, lessThan and equalsTo methods C. the equals and compareTo methods D. the ordinal method
C
If the following is from the method section of a UML diagram, which of the following statements is true? + equals(object2:Stock) : boolean Question options: A. This is a private method that returns a boolean value. B.This is a private method that receives two objects from the Stock class and returns a boolean value. C.This is a public method that accepts a Stock object as its argument and returns a boolean value. D. This is a public method that returns a reference to a String object.
C.
What will the following code display? String input = "99#7"; int number; try { number = Integer.parseInt(input); } catch(NumberFormatException ex) { number = 0; } catch(RuntimeException ex) { number = 1; } catch(Exception ex) { number = -1; }
C. 0
If your code does not handle and exception when it is thrown, this prints an error message and crashes the program.
C. Default exception handler
If the IOData.dat file does not exist, what will happen when the following statement is executed? RandomAccessFile randomFile = new RandomAccessFile("IOData.dat", "rw");
C. The file IOData.dat will be created
The following catch statement can: catch (Exception e) {...}
C. handle all exceptions that are instances of the Exception class or a subclass of Exception.
When an exception is thrown:
C. it must be handled by the program or by the default exception handler.
In a try/catch construct, after the catch statement is executed:
C. the program resumes at the statement that immediately follows the try/catch construct.
CRC stands for
Class, Responsibilities, Collaborations
6. In the following statement, which is the superclass? Public class ClassA extends ClassB implements ClassC
ClassB
Methods that operate on an object's fields are called A. private methods B.instance variables C.public methods D.instance methods
D
This type of loop will always be executed at least once. A. infinite B. pretest C. conditional D. posttest
D
Which of the following statements opens a file named MyFile.txt and allows you to append data to its existing contents? A. PrintWriter outfile = new PrintWriter(true, "MyFile.txt"); B. FileWriter fwriter = new FileWriter("MyFile.txt"); PrintWriter outFile = new PrintWriter(fwriter); C. PrintWriter outfile = new PrintWriter("MyFile.txt", true); D. FileWriter fwriter = new FileWriter("MyFile.txt", true); PrintWriter outFile = new PrintWriter(fwriter);
D
________ operators are used to determine whether a specific relationship exists between two values. A. Assignment B. Logical C. Arithmetic D. Relational
D
enum Truee {OAK, MAPLE, PINE} System.out.println(Tree.OAK); will display: A) Tree.OAK B) 0 C) 1 D) OAK E) Nothing, error
D
9. Look at the following code: FileInputStream fstream = new FileInputStream("info.dat"); DataInputStream inputFile = new DataInputStream(fstream); This code could also be written as
DataInputStream inputFile = new DataInputStream(new FileInputStream("info.dat"));
What is the term used for the character that separates tokens?
Delimiter
Off-by-One Errors
During the loop's execution, the variable index takes on the values 1 through 100, when it should take on the values 0 through 99. As a result, the first element, which is at subscript 0, is skipped. In addition, the loop attempts to use 100 as a subscript during the last iteration. Because 100 is an invalid subscript, the program will throw an exception and halt.
Unchecked exceptions are those that inherit from the
Error class or the RuntimeException class
A catch clause that uses a parameter variable of the Exception type is capable of catching any exception that extends the Error class.
F
The throw statement informs the compiler that a method throws one or more exception.
F
The throws clause causes an exception to be thrown.
F
A GUI program automatically stops executing when the end of the main method is reached. T or F
False
A sorting algorithm is used to locate a specific item in a larger collection of data. T or F
False
All operating systems offer the same set of GUI components
False
If a class has a method named 'finalize' its called automatically just before a data member that has been identified as 'final' of the class is destroyed by the garbage collector. T or F?
False
If a class has a method named finalize, it is called automatically just before a data member that has been identified as final of the class is destroyed by the garbage collector. True False
False
If a string has more than one character used as a delimiter, we must write a loop to determine the tokens, one for each delimiter character.
False
TRUE/FALSE: If a non-letter argument is passed to the toLowerCase or toUpperCase method, the boolean value false is returned.
False
TRUE/FALSE: If a string has more than one character used as a delimiter, we must write a loop to determine the tokens, one for each delimiter character.
False
The key word this is the name of a reference variable that an object can use to refer to itself. True False
False
The names of the enum constants in an enumerated data type must be enclosed in quotation marks. True False
False
The this key word is the name of a reference variable that is available to all static methods. True False
False
True or False: A class may not have more than one constructor
False
True or False: A method cannot return a reference to an object
False
To read data from a binary file, you create objects from the following classes:
FileInputStream and DataInputStream .
To write data to a binary file, you create objects from the following classes:
FileOutputStream and DataOutputStream
This type of loop is ideal in situations where the exact number of iterations is known: _______ loop
For
In GUI terminology, a container that can be displayed as a window is a:
Frame
Look at the following statement: StringBuilder str = new StringBuilder(25); What will the StringBuilder constructor do?
Give the object, str, 25 bytes of storage and not store anything in them
Processing Array Elements
Individual array elements are processed like any other type of variable. grossPay = hours[3] * payRate; - When using increment and decrement operators, be careful not to use the operator on the subscript when you intend to use it on the array element
In a catch statement, what does the following code do?
It prints the error message for an exception.
In a catch statement, what does the following code do? System.out.println(e.getMessage());
It prints the error message for an exception.
Autoboxing is:
Java's process of automatically "boxing up" a value inside an object
11. A protected member of a class may be directly accessed by?
Methods of a subclass, methods of the same class, methods in the same package.
What will be the value of position after the following code is executed? position=str.lastIndexOf("ov",14);
NOT 1
When a parameter value is changed within the body of a method: the change has (NO EFFECT or AN EFFECT) _______ on the associated argument value when the method returns.
No effect
Use the following import statement when using the Character wrapper class:
No import statement is needed
Which of the following import statements is required to use the Character wrapper class?
No import statement is needed
Which of the following import statements is required to use the Character wrapper class? import java.lang.Char import java.String import java.Char No import statement is needed
No import statement is needed
Assuming the following declaration exists: enum Tree { OAK, MAPLE, PINE } What will the following code display? System.out.println(Tree.OAK); Tree.OAK 0 1 OAK Nothing. This statement will cause an error.
OAK
4. In order for an object to be serialized, the class must implement this interface.
Serializable
Passing Objects as an argument // PassObject.java
Shows an example of how you can pass an object into an argument on page 504.
Which of the following statements converts a double variable named tax to a string and stores the value in the String object variable named str?
String str = Double.toString(tax);
Which of the following statements converts a double variable named tax to a string and stores the value in the String object variable named str? String str = tax.Double.toString(str); String str = double.toString(tax); String str = double(tax); String str = Double.toString(tax);
String str = Double.toString(tax);
To convert the int variable, number to a string, use the following statement:
String str = Integer.toString(number);
Which of the following statements converts an int variable named number to a string and stores the value in the String object variable named str?
String str = Integer.toString(number);
If your program needs to make a lot of changes to one or more string, you might consider using objects of this class:
StringBuilder
Multiple alternative decision structure is a ______ statement.
Switch
What will be displayed after the following statements are executed? StringBuilder strb = new StringBuilder (12);
The cow jumped over the moon.
Look at the following code. Integer myNumber; myNumber = 5; Which of the following is true about the second statement?
The statement performs autoboxing.
Look at the following code: Integer myNumber = new Integer(5); int var = myNumber; Which of the following is true about the second statement?
The statement performs unboxing.
Which of the following is NOT true about static methods? They are created by placing the key word static after the access specifier in the method header. They are called from an instance of the class. They are often used to create utility classes that perform operations on data, but have no need to collect and store data. It is not necessary for an instance of the class to be created to execute the method.
They are called from an instance of the class.
Each of the numeric wrapper classes has a static ____________ method that converts a number to a string.
ToString
The process of breaking a string down into tokens is known as what?
Tokenizing
Sometimes a string will contain a series of words or other items of data separated by spaces or other characters. In programming terms, items such as these are known as what?
Tokens
This character is one that appears at the end, or right side, of a string, after the non-space characters:
Trailing whitespace
When you are writing a program with String objects that may have unwanted spaces at the beginning or end of the strings, use this method to delete them.
Trim
15. A class must implement the Serializable interface in order for objects of the class to be serialized
True
16. An abstract class is not instantiated itself, but serves as a superclass for other classes.
True
18. In a try statement, the try clause must appear first, followed by all of the catch clauses, followed by the optional finally clause.
True
19. When catching multiple exceptions that are related to one another through inheritance, you should handle the more specialized exception classes before the more general exception classes.
True
A class is not an object but a description of an object. T or F?
True
A class's static methods do not operate on the fields that belong to any instance of the class. T or F?
True
A constructor is a method that is automatically called when an object is created. T or F?
True
A single copy of a class's static field is shared by all instances of the class. True False
True
A single copy of a class's static field is shared by all instances of the class. T or F?
True
An ArrayList object automatically expands in size to accommodate the items stored in it. T or F
True
An enumerated data type is actually a special type of class. T or F?
True
An instance of a class does not have to exist in order for values to be stored in a class's static fields. True False
True
An instance of a class does not have to exist in order for values to be stored in a class's static fields. T or F?
True
An object can store data. T or F?
True
Both instance fields and instance methods are associated with a specific instance of a class, and they cannot be used until an instance of the class is created. True False
True
Both instance fields and instance methods are associated. T or F?
True
Check boxes may be grouped in a ButtonGroup, like radio buttons are
True
Each field that the programmer wishes to be modified by other classes needs a mutator
True
If you write a toString methods for a class Java will automatically call the method any time you concatenate an object of the class with a string.
True
Java does not limit the number of dimensions that an array may have. T or F
True
Most of the String comparison methods are case sensitive.
True
Objects in an array are accessed with subscripts, just like any other data type in an array. T or F
True
Some of the common GUI components are buttons, labels, texts fields, check boxes, and radio buttons
True
StringBuilder objects are not immutable.
True
TRUE/FALSE: If a non-letter is passed to the toLowerCase or toUpperCase method, it is returned unchanged.
True
TRUE/FALSE: If you are using characters other than whitespaces as delimiters, you will probably want to trim the string before tokenizing; otherwise, the leading and/or following whitespaces will become part of the first and/or last token.
True
TRUE/FALSE: The String class's valueOf() method accepts a value of any primitive data type as an argument and returns a string representation of the value.
True
TRUE/FALSE: The wrapper classes in Java are immutable, which means that once you create an object, you cannot change the object's value.
True
TRUE/FALSE: You can change the contents of a StringBuilder object, but you cannot change the contents of a String object.
True
When you open a file with the PrintWriter class, the class can potentially throw an IOException. T or F
True
You can use the PrintWriter class to open a file for writing and write data to it.
True
You will cause an off-by-one error, when working with a character position within a string, if you think of the first position in a string as 1.
True
This is the process of converting a wrapper class object to a primitive type.
Unboxing
When an object is passed as an argument to a method, this is actually passed
a reference to the object
12. If a method does not handle a possible checked exception, what must the method have?
a throws clause in its header
The process of matching a method call with the correct method is known as
binding
10. The RandomAccessFile class treats a file as a stream of
bytes.
In the following statement, what data type must recField be? str.getChars(5, 10, recField, 0);
char []
In the following statement, what data type must recField be?
char[]
In the following statement, what data type must recField be? str.getChars(5, 10, recField, 0);
char[]
3. This shows the inheritance relationships among classes in a manner that is similar to a family tree.
class hierarchy
In the ________ file format, when the data in a spreadsheet is exported, each row is written to a line, and the values in the cells are separated by commas.
comma separated value
The catch clause
contains code to gracefully handle the exception type listed in the parameter list follows the try clause starts with the word catch followed by a parameter list in parentheses containing an ExceptionType parameter variable
What is the value of str after the following code has been executed? String str; String sourceStr = "Hey diddle, diddle, the cat and the fiddle"; str = sourceStr.substring(12,17);
diddl
To convert the string, str = "285.74" to a double, use the following statement.
double x = Double.ParseDouble(str);
A declaration for an enumerated type begins with this key word. enum enum_type enumerated ENUM
enum
11. This is a section of code that gracefully responds to exceptions when they are thrown.
exception handler
This is a section of code that gracefully responds to exceptions when they are thrown.
exception handler
If str is declared as: String str = "ABCDEFGHI"; What will be returned from Character.toLowerCase(str.charAt(5))?
f
19. You show inheritance in a UML diagram by connecting two classes with a line that has an open arrowhead that points to the subclass.
false
7. The recursive case does not require recursion, so it stops the chain of recursive calls
false
9. A recursive method can have no more than one base case.
false
What will be the value of matches after the following code has been executed? boolean matches; String str1 = "The cow jumped over the moon."; String str2 = "moon"; matches = str1.endsWith(str2);
false
You cannot assign a value to a wrapper class object. (T/F)
false
14. If a random access file contains a stream of characters, which of the following statements would move the file pointer to the starting byte of the fifth character in the file?
file.seek(8);
If a random access file contains a stream of characters, which of the following statements would move the file pointer to the starting byte of the fifth character in the file?
file.seek(8);
If a class has this method, it is called automatically just before an instance of the class is destroyed by the JVM
finalize
If numbers is a two-dimensional int array that has been initialized and total is an int that has been set to 0, which of the following will sum all the elements in the array?
for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col]; }
Summing the rows of a two-dimensional array
int total; // Accumulator for (int row = 0; row < numbers.length; row++) { // Set the accumulator to 0. total = 0; // Sum a row. for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col]; // Display the row's total. System.out.println("Total of row " + row + " is " + total); }
To convert the string, str = "285" to an int, use the following statement:
int x = Integer.parseInt(str);
A deep copy of an object: is always a private method is a bogus term, it has no meaning is an assignment of that object to another object is an operation that copies an aggregate object, and all the objects it references
is an operation that copies an aggregate object, and all the objects it references
7. When an exception is thrown,
it must be handled by the program or by the default exception handler.
In order to execute a _____ must be called by another _____
method, method
Any ________ argument passed to the Character class's toLowerCase method or toUpperCase method is returned as it is.
nonletter
What will be displayed after the following code is executed? String str = "abc456"
not ABC
If you have defined a class named SavingsAccount with a public static data member named numberOfAccounts, and created a SavingsAccount object referenced by the variable account20, which of the following will assign numberOfAccounts to numAccounts? numAccounts = account20.numAccounts; numAccounts = numberOfAccounts; numAccounts = SavingsAccount.numberOfAccounts; None of these, you cannot reference a static data member.
numAccounts = SavingsAccount.numberOfAccounts;
You cannot use the == operator to compare the contents of: objects strings Boolean values integers
objects
This enum method returns the position of an enum constant in the declaration.
ordinal
return object from methods // ReturnObject.java
pg. 507 - 509
4. In the ________, we must always reduce the problem to a smaller version of the original problem.
recursive case
What will be displayed after the following statements are executed? String str = "red$green$blue#orange";
red green blue orange
2. Like a loop, a recursive method must have which of the following?
some way to control the number of times it repeats
An object's ________ is simply the data that is stored in the object's fields at any given moment. value assessment record state
state
Static methods can only operate on ________ fields. global instance static local
static
This type of method cannot access any nonstatic member variables in its own class
static
What would be the results of executing the following code? StringBuilder str = new StringBuilder("Little Jack Horner "); str.append("sat on the "); str.append("corner");
str would reference "Little Jack Horner sat on the corner".
What would be the results of executing the following code? StringBuilder str = new StringBuilder(12); str.append("The cow"); str.append(" jumped over the "); str.append("moon.");
str would reference "The cow jumped over the moon."
Alternate Array Declaration Notation
style 1: int[ ] numbers; style 2: int numbers[ ]; int numbers[ ], codes[ ], scores[ ];
The term ________ commonly is used to refer to a string that is part of another string.
substring
The Character wrapper class provides numerous methods for
testing and converting character data
The Character wrapper class provides numerous methods for
testing and converting character data.
Two or more methods in a class may have the same name, as long as this is different
their signatures
This is the name of a reference variable that is always available to an instance method and refers to the object that is calling the method.
this
If you write this method for a class, Java will automatically call it any time you concatenate an object of the class with a string
toString
A series of words or other items of data separated by spaces or other characters are known as
tokens
The ________ method returns a copy of the calling String object, in which all leading and trailing whitespace characters have been deleted.
trim
10. Recursion is never absolutely required to solve a problem.
true
18. When a class contains an abstract method, you cannot create an instance of the class.
true
20. Because the subclass is more specialized than the superclass, it is sometimes necessary for the subclass to replace inadequate superclass methods with more suitable ones.
true
6. Any problem that can be solved recursively can also be solved iteratively, with a loop.
true
8. A problem can be solved recursively if it can be broken down into successive smaller problems that are identical to the overall problem.
true
If a class has fields that are objects of other classes, those classes must implement the Serializable interface in order to be serialized. (T/F)
true
The ability to catch multiple types of exceptions with a single catch clause is known as multi-catch, and was introduced in Java 7. (T/F)
true
Trying to extract more tokens than exist from a StringTokenizer object will cause an error. (T/F)
true
When catching multiple exceptions that are related to one another through inheritance, you should handle the more specialized exception classes before the more general exception classes. (T/F)
true
When you deserialize an object using the readObject method, you must cast the return value to the desired class type. (T/F)
true
You will cause an off-by-one error, when working with a character position within a string, if you think of the first position in a string as 1. (T/F)
true
6. A(n) ________ is one or more statements that are executed and can potentially throw an exception.
try block
A(n) ________ is one or more statements that are executed and can potentially throw an exception.
try block
You can concatenate String objects by
using the concat method or the + operator.
kb.nextInt(); is an example of a __________ method.
value returning
The String class's ________ method accepts a value of any primitive data type as its argument and returns a string representation of the value.
valueOf
This type of method performs a task and then terminates: _____
void
If object1 and object2 are objects of the same class, to make object2 a copy of object1: use the Java copy method that is a part of the Java language assign object1 to object2, such as object2 = object1; use the default constructor to create object2 with object1 data members write a copy method that will make a field by field copy of object1 data members into object2 data members
write a copy method that will make a field by field copy of object1 data members into object2 data members
To compare two objects in a class: Since objects consist of several fields, you cannot compare them write a method to do a byte-by-byte compare of the two objects write an equals method that will make a field by field compare of the two objects use the == operator, e.g. object1 == object2
write an equals method that will make a field by field compare of the two objects
diamond operator
you are no longer required to write the data type in the part of the statement that calls the ArrayList constructor. Instead, you can simply write a set of empty angled brackets ArrayList<String> list = new ArrayList<>();
What will be the tokens in the following statement? String str = "red$green&blue#orange"; String tokens = str.split("[$&#]");
"red", "green", "blue", and "orange"
14. Protected class members can be denoted in a UML diagram with the ______ symbol.
#
Selection sort
- A sorting algorithm is a technique for scanning through an array and rearranging its contents in some specific order. - The selection sort works like this: The smallest value in the array is located and moved to element 0. Then the next smallest value is located and moved to element 1. This process continues until all of the elements have been placed in their proper order
Calling String methods from an array element
- Because each element of a String array is a String object, you can use an element to call a String method - Because the array's length member is a field, you do not write a set of parentheses after its name. You do write the parentheses after the name of the String class's length method. for (int i = 0; i < names.length; i++) System.out.println(names[i].length());
Array Length
- Each array in Java has a public field named length. size = temperatures.length; for (int i = 0; i < temperatures.length; i++) System.out.println(temperatures[i]); - You cannot change the value of an array's length field.
Bounds Checking
- Java performs array bounds checking, which means that it does not allow a statement to use a subscript that is outside the range of valid subscripts for an array. - Bounds checking occurs at runtime. The Java compiler does not display an error message when it processes a statement that uses an invalid subscript. Instead, when the statement executes, the program throws an exception and immediately terminates.
The Enhanced for Loop
- simplifies array processing. for (dataType elementVariable : array) statement; - The enhanced for loop is designed to iterate once for every element in an array
Common Errors to Avoid
1. Using an invalid subscript. Java does not allow you to use a subscript value that is outside the range of valid subscripts for an array. 2. Confusing the contents of an integer array element with the element's subscript. An element's subscript and the value stored in the element are not the same thing. The subscript identifies an element, which holds a value. 3. Causing an off-by-one error. When processing arrays, the subscripts start at zero and end at one less than the number of elements in the array. Off-by-one errors are commonly caused when a loop uses an initial subscript of one and/or uses a maximum subscript that is equal to the number of elements in the array. 4. Using the = operator to copy an array. Assigning one array reference variable to another with the = operator merely copies the address in one variable to the other. To copy an array, you should copy the individual elements of one array to another. 5. Using the = operator to copy an array. Assigning one array reference variable to another with the = operator merely copies the address in one variable to the other. To copy an array, you should copy the individual elements of one array to another. 6. Reversing the row and column subscripts when processing a two-dimensional array. When thinking of a two-dimensional array as having rows and columns, the first subscript accesses a row and the second subscript accesses a column. If you reverse these subscripts, you will access the wrong element
What will be the tokens in the following statement? StringTokenizer strToken = new StringTokenizer("123-456-7890", "-", true);
123, 456, 7980, and -
What will be the tokens in the following statement? StringTokenizer st = new StringTokenizer("9-14-2014", "-", true);
9, 14, 2014, and -
A characteristic of ________ is that only an object's methods are able to directly access and make the changes to the object's data. A.Data Hiding B.Classes C.Component Reusability D.Procedure
A
A constructor is a method that: A) Performs initialization or setup operations B) Never receives any arguments C) Returns an object of the class D) With the name ClassName.constructor
A
A search algorithm is: A) Method for locating a specific item in a larger collection of data B) Is rarely used with arrays C) Arranges elements in ascending order D) Arranges elements in descending order
A
An object typically hides it data, but allows outside code to access? A.the methods that operate on the data B.the data files C.private data members D.the pseudocode
A
Assuming that inputFile references a Scanner object that was used to open a file, which of the following statements will read an int from the file? A) int number = inputFile.nextInt(); B) int number = inputFile.next(); C) int number = inputFile.readInt(); D) int number = inputFile.integer();
A
Enumerated types have this method, which returns the position of an enum constant in the declaration list A) ordinal B) position C) toString D) location
A
If you wish to use the System.out.printf method to print a string argument, use the ________ format specifier. A.%s B.%d C.%b D.%f
A
In general, there are two types of files: A. text and binary B. delimited and unlimited C. encrypted and unencrypted D.static and dynamic
A
What is a ragged array? A. a two-dimensional array where the rows have a different number of columns B. a two-dimensional array for which the number of rows is unknown C. a partially initialized two-dimensional array of ranged values D. a one-dimensional array for which the number of elements is unknown
A
What is the value of scores[2][3] in the following array? int[][] scores = { {88, 80, 79, 92}, {75, 84, 93, 80}, {98, 95, 92, 94}, {91, 84, 88, 96} }; A. 94 B. 95 C. 93 D. 84
A
When you pass the name of a file to the PrintWriter constructor and the file already exists, A) it will be erased and a new empty file with the same name will be created. B) an IOException will be thrown. C) a new empty file will be created with the same name and a different version number. D) the file will be opened and new data will be appended to its current contents.
A
Which of the following is a correct method header for receiving a two-dimensional array as an argument? A. public static void passMyArray(int[][] myArray) B. public static void passMyArray(array myArray) C. public static void passMyArray(int myArray) D. public static void passMyArray(int[]myArray1, int[]myArray2)
A
Which of the following will open a file named MyFile.txt and allow you to read data from it? A) File file = new File("MyFile.txt"); B) Scanner inputFile = new Scanner("MyFile.txt"); C) File file = new File("MyFile.txt"); Scanner inputFile = new Scanner(file); D) PrintWriter inputFile = new PrintWriter("MyFile.txt");
A
You can use the ________ method to replace an item at a specific location in an ArrayList. A. set B. add C. replace D. remove
A
Sequential Search Algorithm
A search algorithm is a method of locating a specific item in a larger collection of data. This section discusses the sequential search algorithm, which is a simple technique for searching the contents of an array - The reason -1 is returned when the search value is not found in the array is because -1 is not a valid subscript.
Static Class Members
A static class member belongs to the class, not objects instantiated from the class
Static Methods
A static method is created by placing the key word static after the access specifier in the method header. Because they are declared as static, they belong to the class and may be called without any instances of the class being in existence.
If, within one try statement you want to have catch clauses that catch exceptions of the following types, in which order should they appear in your program? (1) Throwable (2) Exception (3) RuntimeException (4) NumberFormatException
A. 4, 3, 2, 1
The exception classes are in packages in the _____________.
A. Java API
When writing a string to a binary file or reading a string from a binary file, it is recommended that you use
A. Methods that use UTF-8 encoding
What is demonstrated by the following code? try { (try block statements . . .) } catch(NumberFormatException | IOException ex) { respondToError(); }
A. Multi-catch, a catch clause that can handle more than one exception, beginning in Java 7
Classes that inherit from the Error class are:.
A. for exceptions that are thrown when a critical error occurs, and the application program should not try to handle them.
An exception's default error message can be retrieved using this method.
A. getMessage()
5. A class becomes abstract when you place the ____ key word in the class definition.
Abstract
When using the StringBuilder class's insert method, you can insert:
All of the above (Any primitive type, a String object, & a char array)
What does the following statement do? Double number = new Double(8.8);
All of the above (It creates a Double object, It initializes that object to 8.8, & It assigns the object's address to the number variable)
What does the following statement do? Float number = new Float(8.8);
All of the above (It creates a Float object, It initializes that object to 8.8, & It assigns the object's address to the number variable)
ArrayList class
ArrayList is a class in the Java API that is similar to an array and allows you to store objects. Unlike an array, an ArrayList object's size is automatically adjusted to accommodate the number of items being stored in it - • An ArrayList object automatically expands as items are added to it. - • In addition to adding items to an ArrayList, you can remove items as well. - • An ArrayList object automatically shrinks as items are removed from it. *The ArrayList class is in the java.util package, so the following import statement is required: import java.util.ArrayList;
The following statement creates an ArrayList object. What is the purpose of the <String> notation? ArrayList<String> arr = new ArrayList<String>();
ArrayList<String> arr = new ArrayList<String>();
A class specifies the _______ and ______ that a particular type of object has. A) relationships; methods B) fields; methods C) fields; object names D) relationships; object names
B
A method A.may have only one parameter variables B.may have zero or more parameter variables C.must have at least two parameter variables D.never has parameter variables
B
A method's signature consists of A. the return type and the method name B.the method name and the parameter list C.the size of the method in memory D.the return type, the method name, and the parameter list
B
A ________ is a boolean variable that signals when some condition exists in the program. A.case B.block C.flag D.sentinel
C
A block of code is enclosed in a set of A. parentheses B. double quotes C. braces D. brackets
C
A class's responsibilities include A.the things a class is responsible for doing. B.the things a class is responsible for knowing C.both a and b D.neither A nor B
C
A classes responsibilities include: A) The things a class is responsible for doing B) The things a class is responsible for knowing C) Both things a class is responsible for doing and knowing D) Neither things a class is responsible for doing or knowing
C
A constructor A.has return type of void B.always accepts two arguments C.has the same name as the class D.always has an access specifier of private
C
A ragged array is: A: A two-dimensional array for which the number of rows is unknown B: A one-dimensional array for which the number of elements is unknown C: A two-dimensional array where the rows are of different lengths D: There is no such thing as a ragged array
C
Assume that inputFile references a Scanner object that was used to open a file. Which of the following while loops shows the correct way to read data from the file until the end of the file is reached? A) while (inputFile != null) { ... } B) while (!inputFile.EOF) { ... } C) while (inputFile.hasNext()) { ... } D) while (inputFile.nextLine == " ") { ... }
C
Before entering a loop to compute a running total, the program should first A.read all the values into main memory. B. know exactly how many values there are to total. C. set the accumulator variable to an initial value, usually zero D. set all variable to zero.
C
CRC stands for: A) Class, recyclability, collaborations B) Class, redundancy, collections C) Class, responsibilities, collaborations D) Code, reuse, consistency
C
If str1 and str2 are both Strings, which of the following will correctly test to determine whether str1 is less than str2? A) str1 < str2 B) str1.equals(str2) < 0 C) str1.compareTo(str2) < 0 D) str1.lessThan(str2) == true
C
The UML diagram does not contain: A) Method names B) Class name C) Object names D) Field names
C
The ________ method is used to display a message dialog. A.messageDialog B.showDialog C.showMessageDialog D.messageDialogshop
C
The boolean data type may contain the following range of values: A.-2,147,483,648 to +2,147,483,647 B.-32,762 to +32,767 C.true or false D.-128 to +127
C
To return an array of long values from a method, use this as the return type for the method. A. long[ARRAY_SIZE] B. long C. long[] D. array
C
What is the following statement an example of? import java.util.Scanner; A.a wildcard import statement B.a conditional import statement C.an explicit import statement D.an unconditional import statement
C
Which of the following statements opens a file named MyFile.txt and allows you to read data from it? A. File file = new File("MyFile.txt"); B. PrintWriter inputFile = new PrintWriter("MyFile.txt"); C. File file = new File("MyFile.txt"); Scanner inputFile = new Scanner(file); D. Scanner inputFile = new Scanner("MyFile.txt");
C
You can use the enum key word to A. specify the values that belong to that type B. create your own data type C. Both A and B
C
f method A calls method B, and method B calls method C, and method C calls method D, when method D finishes, what happens? Control is returned to method __.
C
In the following code, assume that inputFile references a Scanner object that has been successfully used to open a file: double totalIncome = 0.0; while (inputFile.hasNext()) { try { totalIncome += inputFile.nextDouble(); } catch(InputMismatchException e) { System.out.println("Non-numeric data encountered " + "in the file."); inputFile.nextLine(); } finally { totalIncome = 35.5; } } What will be the value of totalIncome after the following values are read from the file? 2.5 8.5 3.0 5.5 abc 1.0
C. 35.5
To write data to a binary file you create objects from the following classes:
C. FileOutputStream and DataOutputStream
RAM is usually? A.A static type of memory, used for permanent storage B.Secondary Storage C.An input/output device D.A volatile type of memory, used only for temporary storage.
D
The only limitation that static methods have is A. they must be declared outside of the class B. they can only be called from static members of the class C. they can refer to only nonstatic members of the class D. they cannot refer to nonstatic members of the class
D
The original name for Java was? A.*7 B.HotJava C. Elm D. Oak
D
Assume that the classes BlankISBN, NegativePrice, and NegativeNumberOrdered are exception classes that inherit from Exception. The following code is a constructor for the Book class. What must be true about any method that instantiates the Book class with this constructor? public Book(String ISBNOfBook, double priceOfBook, int numberOrderedOfBook) throws BlankISBN, NegativePrice, NegativeNumberOrdered { if (ISBNOfBook == "") throw new BlankISBN(); if (priceOfBook < 0) throw new NegativePrice(priceOfBook); if (numberedOrderedOfBook < 0) throw new NegativeNumberOrdered(numberOrderedv); ISBN = ISBNOfBook; price = priceOfBook; numberedOrdered = numberOrderedOfBook; }
C. It must handle all of the possible exceptions thrown by the constructor or have its own throws clause specifying them.
In order for an object to be serialized, its class must implement this interface.
C. Serializable
When an exception is thrown by code in the try block, the JVM begins searching the try statement for a catch clause that can handle it and passes control of the program to
C. the first catch clause that can handle the exception.
In a multi-catch, (introduced in Java 7) the exception types are separated in the catch clause by this symbol:
C. |
The ________ class is the wrapper class for the char data type.
Character
If you attempt to use a local variable before it has been given a value: a _____ ______ will occur.
Compiler error
"Blank" is a cross between human language and a programming language. A. Java B. The Java Virtual Machine C. The compiler D. Pseudocode
D
A for loop normally performs which of these steps? A) initializes a control variable to a starting value B) tests the control variable by comparing it to a maximum/minimum value and terminate when the variable reaches that value C) updates the control variable during each iteration D) all of the above
D
A loop that executes as long as a particular condition exists is called a(n) ________ loop. A. infinite B. count-controlled C. relational D. conditional
D
Another term for an object of a class is a(n) A.access specifier B.member C.method D.instance
D
Another term for an object of a class is: A) Method B) Member C) Access specifier D) Instance
D
Assume that radio references a JRadioButton. To click the radio button in code use the following statement: A) Click (radio, true); B) radio.Click(); C) Click(radio); D) radio.doClick();
D
Class objects normally have ________ that perform useful operations on their data, but primitive variables do not. A.instances B.relationships C.fields D.methods
D
Enumerated types have this method, which returns the position of an enum constant in the declaration list. A.index B.position C.location D.ordinal
D
Given the following statement, which statement will write "Calvin" to the file DiskFile.txt? PrintWriter diskOut = new PrintWriter("DiskFile.txt"); A) System.out.println(diskOut, "Calvin"); B) DiskFile.println("Calvin"); C) PrintWriter.println("Calvin"); D) diskOut.println("Calvin");
D
Given the following two-dimensional array declaration, which statement is true? int[][] numbers = new int[6][9]; A. The numbers array has 54 rows. B. The numbers array has 6 columns and 9 rows. C. The numbers array has 15 rows. D. The numbers array has 6 rows and 9 columns.
D
If chr is a character variable, which of the following if statements is written correctly? A) if (chr = "a") B) if (chr == "a") C) if (chr = 'a') D) if (chr == 'a')
D
If numbers is a two-dimensional array, which of the following would give the length of row r? A) numbers.length B) numbers.length[r] C) numbers[r].length[r] D) numbers[r].length
D
One or more objects may be created from a(n) A. method B.field C.instance D.class
D
This is a set of programming language statements that, together, perform a specific task. A.Object B.Compile C.Pseudocode D.Procedure
D
Given the following constructor code, which of the statements are true? public Book(String ISBNOfBook, double priceOfBook, int numberOrderedOfBook) { if (ISBNOfBook == "") throw new BlankISBN(); if (priceOfBook < 0) throw new NegativePrice(priceOfBook); if (numberedOrderedOfBook < 0) throw new NegativeNumberOrdered(numberOrderedv); ISBN = ISBNOfBook; price = priceOfBook; numberedOrdered = numberOrderedOfBook; }
D. All of the above
If the code in a method can potentially throw a checked exception, then that method must:
D. Either A or B
This is a section of code that gracefully responds to exceptions when they are thrown
D. Exception handler
Under Windows, which of the following statements will open the file InputFile.txt that is in the root directory on the C: drive?
D. FileReader freader = new FileReader("C:\\InputFile.txt");
All of the exceptions that you will handle are instances of classes that extend this class
D. exception
If a random access file contains a stream of characters, which of the following would you use to set the pointer on the fifth character?
D. file.seek(8);
TRUE/FALSE: StringBuilder objects are immutable.
False
TRUE/FALSE: The String class's valueOf() method accepts a string representation as an argument and returns its equivalent integer value.
False
TRUE/FALSE: The following statement correctly creates a StringBuilder object. StringBuilder str = "Caesar Salad";
False
TRUE/FALSE: You cannot assign a value to a wrapper class object.
False
TRUE/FALSE: You must call a method to get the value of a wrapper class object.
False
The String class's valueOf method accepts a string representation as an argument and returns its equivalent integer value.
False
The String class's valueOf method accepts a string representation as an argument and returns its equivalent integer value. (T/F)
False
True or False: A static member method may refer to nonstatic member variables of the same class at any time.
False
True or False: All static member variables are initialized to -1 by default.
False
True or False: You can declare an enumerated data type inside a method.
False
True or False: enum constants have a toString method
False
You can declare an enumerated data type inside of a method. True False
False
A method that gets a value from a class's field but does not change it is a mutator method. T or F?
False, thats an accessor
Passing Objects as an argument // PassObject2.java
Shows an example of how you can pass an object into an argument on page 506. The method modifies the contents of the object referenced by the variable.
An object's ______ is simply the data that is stored in the object's fields at any given moment in the program
State
Static Members
Static Fields and Static Methods are fields and methods that do not belong to any instance of a class. They belong in the same class and not an instance of a class.
Use of Static Methods
Static methods are convenient for many tasks because they can be called directly from the class, as needed. They are most often used to create utility classes that perform operations on data, but have no need to collect and store data.
To convert the double variable, d = 543.98, to a string, use the following statement:
String str = Double.toString(d);
The term ____________ commonly is used to refer to a string that is part of another string.
Substring
Which of the following statements will display the maximum value that a double can hold?
System.out.println(Double.MAX_VALUE);
Which of the following statements will print the maximum value a double variable may have?
System.out.println(Double.MAX_VALUE);
Which of the following statements will print the maximum value an int variable may have?
System.out.println(Integer.MAX_VALUE);
A class must implement the Serializable interface in order for objects of the class to be serialized.
T
Beginning in Java 7, multi-catch can reduce a lot of duplicated code in a try statement that needs to catch multiple exceptions, but perform the same operation for each one.
T
If the class SerializedClass contains references to objects of other classes as fields, those classes must also implement the Serializable interface in order to be serialized.
T
In versions of Java prior to Java 7, each catch clause can handle only one type of exception.
T
The call stack is an internal list of all the methods that are currently executing.
T
When an exception is thrown by a method that is executing under several layers of method calls, a stack trace indicates the method executing when an exception occurred and all of the methods that were called in order to execute that method.
T
When an object is serialized, it is converted into a series of bytes that contain the object's data.
T
When deserializing an object using the readObject method, you must cast the return value to the desired class type.
T
When the code in a try block may throw more than one type of exception, you need to write a catch clause for each type of exception that could potentially be thrown.
T
The Character wrapper class provides numerous methods for:
Testing and converting char variables
Remove an Item from an ArrayList
The ArrayList class has a remove method that removes an item at a specific index. You pass the index as an argument to the method. nameList.remove(1);
What will be returned from a method, if the following is the method header? public Rectangle getRectangle() An object of the class Rectangle The values stored in the data members of the Rectangle object the method changed A graph of a rectangle The address of an object of the class Rectangle
The address of an object of the class Rectangle
Finding the highest value
The code to find the highest value in the array is as follows: int highest = numbers[0]; for (int index = 1; index < numbers.length; index++) { if (numbers[index] > highest) highest = numbers[index]; }
vararg parameter
The ellipsis (three periods) that follows the data type indicates that numbers is a special type of parameter public static int sum(int... numbers)
If the data.dat file does not exist, what will happen when the following statement is executed? RandomAccessFile randomFile = new RandomAccessFile("data.dat", "rw");
The file data.dat will be created.
Finding the lowest value
The following code finds the lowest value in the array int lowest = numbers[0]; for (int index = 1; index < numbers.length; index++) { if (numbers[index] < lowest) lowest = numbers[index]; }
What will be the result of the following statements? FileInputStream fstream = new FileInputStream("Input.dat"); DataInputStream inFile = new DataInputStream(fstream);
The inFile variable will reference an object that is able to read binary data from the Input.dat file.
Given the following statement, which of the following is not true? str.insert(8, 32);
The insert will start at position 32
A static field is created by placing:
The key word static after the access specifier and before the field's data type
10. In a class hierarchy?
The more general classes are toward the top of the tree and the more specialized classes are toward the bottom.
If a program does not handle an unchecked exception, what is the result?
The program is halted and the default exception handler handles the exception.
What will be the tokens in the following statement? StringTokenizer strToken = new StringTokenizer("January 1, 2008", ", ", true);
The tokens will be: January space 1 , space 2008
16. The call stack is an internal list of all the methods that are currently executing.
True
17. If a method in a subclass has the same signature as a method in the superclass, the subclass method overrides the superclass method.
True
17. When an object is serialized, it is converted into a series of bytes that contain the object's data.
True
A file must always be opened before using it and closed when the program is finished using it. T or F
True
A method that stores a value in a class's field or in some other way changes the value is known as a mutator method. T or F?
True
Each field that the programmer wishes to be viewed by other classes needs an accessor
True
Enum constants have a toString method. True False
True
Enum constants have a toString method. T or F?
True
If you write a toString method for a class, Java will automatically call the method any time you concatenate an object of the class with a string. True False
True
If you write a toString method to dislplay the contents of an object, object1, for a class, Class1 then the following 2 statements are equivalent: System.out.println(object1); System.out.println(object1.toString ()); T or F?
True
Static Fields
When a field is declared with the key word static, there will be only one copy of the field in memory, regardless of the number of instances of the class that might exist. It is shared amongst all instances of the class.
Passing two-dimensional arrays to methods
When a two-dimensional array is passed to a method, the parameter must be declared as a reference to a two-dimensional array private static void showArray(int[][] array)
Initializing a two-dimensional array
When initializing a two-dimensional array, you enclose each row's initialization list in its own set of braces. int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Ragged arrays
When the rows of a two-dimensional array are of different lengths, the array is known as a ragged array - You create a ragged array by first creating a two-dimensional array with a specific number of rows, but no columns.
Command-line arguments and variable-length argument lists
When you invoke a Java program from the operating system command line, you can specify arguments that are passed into the main method of the program. In addition, you can write a method that takes a variable number of arguments. When the method runs, it can determine the number of arguments that were passed to it and act accordingly
What is term used for a class that is "wrapped around" a primitive data type and allows you to create objects instead of variables?
Wrapper class
To serialize an object and write it to the file, use this method of the ObjectOutputStream class.
WriteObject
You cannot use the fully qualified name of an enum constant for this
a case expression
You cannot use the fully-qualified name of an enum constant for this. a switch expression an argument to a method a case expression all of these
a case expression
1. Which of the following problems can be solved recursively?
a. All of the Above i. binary search ii. towers of Hanoi iii. greatest common denominator
Making an instance of one class a field in another class is called
aggregation
Which of the following are used as delimiters if the StringTokenizer class's constructor is called and a reference to a String object is passed as the only argument? newline space tab
all of the above
A partially filled
array is normally used with an accompanying integer variable that holds the number of items stored in the array. - If a partially filled array is passed as an argument to a method, the variable that holds the count of items in the array must also be passed as an argument. Otherwise, the method will not be able to determine the number of items that are stored in the array