OCAJP 8
B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * x is automatically promoted to long and cannot be automatically stored in y, which is in an int value. Options B, C, and D solve this problem by reducing the long value to int. Option E does not solve the problem and actually makes it worse by attempting to place the value in a smaller data type. Option F solves the problem by increasing the data type of the assignment so that long is allowed.
What change would allow the code snippet to compile? (Choose all that apply) 3: long x = 10; 4: int y = 2 * x; A. No change; it compiles as is. B. Cast x on line 4 to int. C. Change the data type of x on line 3 to short. D. Cast 2 * x on line 4 to int. E. Change the data type of y on line 4 to short. F. Change the data type of y on line 4 to long.
B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * x is automatically promoted to long and cannot be automatically stored in y, which is in an int value. Options B, C, and D solve this problem by reducing the long value to int. Option E does not solve the problem and actually makes it worse by attempting to place the value in a smaller data type. Option F solves the problem by increasing the data type of the assignment so that long is allowed.
What change would allow the following code snippet to compile? (Choose all that apply) 3: long x = 10; 4: int y = 2 * x; A. No change; it compiles as is. B. Cast x on line 4 to int. C. Change the data type of x on line 3 to short. D. Cast 2 * x on line 4 to int. E. Change the data type of y on line 4 to short. F. Change the data type of y on line 4 to long.
A, B, D. Note, x + y is automatically promoted to int.
What data type (or types) will allow the following code snippet to compile? byte x = 5; byte y = 10; ______ z = x + y; A. int B. long C. boolean D. double E. short F. byte
java.lang.NumberFormatException. Note, this exception is thrown when a method that converts a String to a number receives a String that it cannot convert.
What exception/error would the following code throw? Integer.parseInt("asdf");
C. This code does not contain any compilation errors or an infinite loop, so options D, E, and F are incorrect. The break statement on line 8 causes the loop to execute once and finish, so option C is the correct answer.
What is the output of the code snippet? A. 10, 14, B. 10, 14 C. 10, D. The code will not compile because of line 7. E. The code will not compile because of line 8. F. The code contains an infinite loop and does not terminate.
A. The code compiles successfully, so options C and D are incorrect. The value of b after line 4 is false. However, the if-then statement on line 5 contains an assignment, not a comparison. The variable b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success, so the answer is option A.
What is the output of the code snippet? A. Success B. Failure C. The code will not compile because of line 4. D. The code will not compile because of line 5.
D. The variable x is an int and s is a reference to a String object. The two data types are incomparable because neither variable can be converted to the other variable's type. The compiler error occurs on line 5 when the comparison is attempted, so the answer is option D.
What is the output of the code snippet? A. Success B. Failure C. The code will not compile because of line 4. D. The code will not compile because of line 5.
F. The code does not compile because two else statements cannot be chained together without additional if-then statements, so the correct answer is option F. Option E is incorrect as Line 6 by itself does not cause a problem, only when it is paired with Line 7. One way to fix this code so it compiles would be to add an if-then statement on line 6. The other solution would be to remove line 7.
What is the output of the code snippet? A. Too Low B. Just Right C. Too High D. Compiles but throws a NullPointerException. E. The code will not compile because of line 6. F. The code will not compile because of line 7.
B. This example is tricky because of the second assignment operator embedded in line 5. The expression (z=false) assigns the value false to z and returns false for the entire expression. Since y does not equal 10, the left-hand side returns true; therefore, the exclusive or (^) of the entire expression assigned to x is true. The output reflects these assignments, with no change to y, so option B is the only correct answer. The code compiles and runs without issue, so option F is not correct.
What is the output of the code snippet? A. true, 10, true B. true, 20, false C. false, 20, true D. false, 20, false E. false, 20, true F. The code will not compile because of line 5.
A. The "*" and "%" have the same operator precedence, so the expression is evaluated from left-to-right. The result of 5 * 4 is 20, and 20 % 3 is 2 (20 divided by 3 is 18, the remainder is 2). The output is 2 and option A is the correct answer.
What is the output of the code? A. 2 B. 3 C. 5 D. 6 E. The code will not compile because of line 3.
D. Line 4 generates a possible loss of precision compiler error. The cast operator has the highest precedence, so it is evaluated first, casting a to a byte. Then, the addition is evaluated, causing both a and b to be promoted to int values. The value 90 is an int and cannot be assigned to the byte sum without an explicit cast, so the code does not compile. The code could be corrected with parentheses around (a + b), in which case option C would be the correct answer.
What is the output of the code? A. 40 B. 50 C. 90 D. The code will not compile because of line 4. E. An undefined value.
D. Although parentheses are not required, they do greatly increase code readability, such as the following equivalent statement: System.out.println((x > 2) ? ((x < 4) ? 10 : 8) : 7) We apply the outside ternary operator fi rst, as it is possible the inner ternary expression may never be evaluated. Since (x>2) is true, this reduces the problem to: System.out.println((x < 4) ? 10 : 8) Since x is greater than 2, the answer is 8, or option D in this case.
What is the output of the code? A. 5 B. 4 C. 10 D. 8 E. 7 F. The code will not compile because of line 4.
E. Note, neither remove( ) or add( ) can be called on a backed List, that is, a List created by calling Arrays.asList( ) on an array. This is because a backed List is a fixed-size List, so it's size cannot change.
What is the output of the code? A. hawk test add B. hawk robin new test add C. new test add D. The code will not compile. E. UnsupportedOperationException
D. The variable y is declared within the body of the do-while statement, so it is out of scope on line 6. Line 6 generates a compiler error, so option D is the correct answer.
What is the output of the following code snippet? A. 1 2 3 4 5 6 7 8 9 B. 1 2 3 4 5 6 7 8 9 10 C. 1 2 3 4 5 6 7 8 9 10 11 D. The code will not compile because of line 6. E. The code contains an infinite loop and does not terminate.
E. This is actually a much simpler problem than it appears to be. The while statement on line 4 is missing parentheses, so the code will not compile, and option E is the correct answer. If the parentheses were added, though, option F would be the correct answer since the loop does not use curly braces to include x++ and the boolean expression never changes. Finally, if curly braces were added around both expressions, the output would be 10, 6 and option B would be correct.
What is the output of the following code snippet? A. 10, 5 B. 10, 6 C. 11, 5 D. The code will not compile because of line 3. E. The code will not compile because of line 4. F. The code contains an infinite loop and does not terminate.
D. The intialization statement in the for loop attempts to declare x as a long with a value of 4. Because x was already declared outside the loop, this results in a compile-time error.
What is the output of the following code: int x = 0; for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) { System.out.print(x + " "); } A. 4 B. 5 C. 0 D. Does not compile.
animals. Note, the substring method of the StringBuilder class returns a String, not a reference to the object, as with many other StringBuilder methods. Subsequently, the assignment of sb must use the StringBuilder constructor, passing the substring call on s as an argument, or a compile-time error occurs.
What is the output of the following code? StringBuilder s = new StringBuilder("animals"); StringBuilder sb = new StringBuilder(s.substring(0,4)); System.out.println(s);
D. Passing an int to the StringBuilder constructor creates an empty StringBuilder object with a capacity of 5.
What is the output of the following code? StringBuilder sb = new StringBuilder(5); System.out.println(sb); A. 5 B. The code does not compile. C. An exception is thrown. D. A blank line is printed.
null1. Note, if a null reference variable is passed to the '+' operator, it gets converted to the String "null".
What is the output of the following code? String s = null; System.out.println(s + "1");
0 10 Torchie constructor. Order of Initialization - If there is a superclass, initialize it first. Then Static variable declarations and static initializers in the order they appear in the file. Then Instance variable declarations and instance initializers in the order they appear in the file. And finally, the constructor.
What is the output?
2 4 6 8 5. There is no superclass, so we jump right to rule 2—the statics. There are three static blocks: on lines 2, 5, and 7. They run in that order. The static block on line 2 calls the add() method, which prints 2. The static block on line 5 calls the add() method, which prints 4. The last static block, on line 7, calls new to instantiate the object. This means we can go on to rule 3 to look at the instance variables and instance initializers. There are two of those: on lines 6 and 8. They both call the add() method and print 6 and 8, respectively. Finally, we go on to rule 4 and call the constructor, which calls the add() method one more time and prints 5.
What is the output?
C. Unboxing a null throws NullPointerException.
What is the output? A. 0.0 B. 0.25 C. An Exception D. Compilation Fails
D. First, passes 1 as start but nothing else. This means Java creates an array of length 0 for nums. Line 20 passes 1 as start and one more value. Java converts this one value to an array of length 1. Line 21 passes 1 as start and two more values. Java converts these two values to an array of length 2. Line 22 passes 1 as start and an array of length 2 directly as nums.
What is the output? A. 0112 B. 0000 C. 1111 D. 0122 E. Throws a runtime exception. F. Does not compile.
B. Note, the date operations performed on Lines 2 and 3 aren't assigned and so are ignored.
What is the output? A. 2018 APRIL 2 B. 2018 APRIL 30 C. 2018 MAY 2 D. 2021 APRIL 2 E. 2021 APRIL 30 F. 2021 MAY 2 G. A runtime exception is thrown.
D. A LocalDate does not have a time element. Therefore, it has no method to add hours and the code does not compile.
What is the output? A. 2018 APRIL 2 B. 2018 APRIL 30 C. 2018 MAY 2 D. The code does not compile. E. A runtime exception is thrown.
F. Java throws an exception if invalid date values are passed. There is no 40th day in April—or any other month for that matter.
What is the output? A. 2018 APRIL 4 B. 2018 APRIL 30 C. 2018 MAY 10 D. Another date. E. The code does not compile. F. A runtime exception is thrown.
E
What is the output? A. 3/7/14 11:22 AM B. 5/10/15 11:22 AM C. 3/7/14 D. 5/10/15 E. 11:22 AM F. The code does not compile. G. A runtime exception is thrown.
B. Period does not allow chaining. Only the last Period method called counts, so only the two years are subtracted.
What is the output? A. 5/9/13 11:22 AM B. 5/10/13 11:22 AM C. 5/9/14 D. 5/10/14 E. The code does not compile. F. A runtime exception is thrown.
D. Boolean fields initialize to false and references initialize to null, so empty is false and brand is null. Brand = null is output.
What is the output? A. Line 6 generates a compiler error. B. Line 7 generates a compiler error. C. There is no output. D. Empty = false, Brand = null E. Empty = false, Brand = F. Empty = null, Brand = null
B
What is the output? A. abbaaccc B. abbaccca C. bbaaaccc D. bbaaccca E. An exception is thrown. F. The code does not compile.
B
What is the output? A. true, 10, true B. true, 20, false C. false, 20, true D. false, 20, false E. false, 10, true F. The code does not compile.
-128 to 127
What is the range of a byte?
7. Remeber bitwise XOR compares each bit and if one, but not both, are 1, returns a 1 for that bit, so 4^3 is 00000100^00000011==00000111 which is 7.
What is the result of 4^3?
F. The question is trying to distract you into paying attention to logical equality versus object reference equality. It is hoping you will miss the fact that line 4 does not compile. Java does not allow you to compare String and StringBuilder using ==.
What is the result of the code? A. 1 B. 2 C. 12 D. No output is printed. E. An exception is thrown. F. The code does not compile.
C. After line 4, values has one element (4). After line 5, values has two elements (4, 5). After line 6, values has two elements (4, 6) because set() does a replace. After line 7, values has only one element (6).
What is the result of the code? A. 4 B. 5 C. 6 D. 46 E. 45 F. An exception is thrown. G. The code does not compile.
D. Note, a Period object cannot be passed to the plus( ) method of a LocalTime object, just as a Duration object cannot be passed to the plus( ) method of a LocalDate object.
What is the result of the code? A. It will not compile. B. It will print the current time. C. It will print tomorrow's date with the current time. D. UnsuppoertedTemporalTypeException is thrown.
C. This code will not compile because a TemporalAmount argument is being passed to the plusDays( ) method, which expects an int. This could be fixed by either passing an int, or using the plus( ) method on the LocalDateTime object, which takes types that implement TemporalAmount (e.g., Period or Duration).
What is the result of the code? A. It will print the date and time of now plus one hour. B. It will throw a DateTimeException. C. It will not compile.
D. The code does not compile because list is instantiated using generics. Only String objects can be added to list and 7 is an int.
What is the result of the code? A. onetwo B. onetwo7 C. onetwo followed by an exception D. Compiler error on line 9. E. Compiler error on line 10.
B
What is the result of the code? A. roar roar B. roar roar!!! C. roar!!! roar D. roar!!! roar!!! E. An exception is thrown. F. The code does not compile.
F. a += 2 expands to a = a +2. A String concatenated with any other type gives a String. Lines 14, 15, and 16 all append to a, giving a result of "2cfalse". The if statement on line 18 returns true because the values of the two String objects are the same using object equality. The if statement on line 17 returns false because the two String objects are not the same in memory. One comes directly from the string pool and the other comes from building using String operations.
What is the result of the code? (choose all that apply) A. Compile error on line 14. B. Compile error on line 15. C. Compile error on line 16. D. Compile error on another line. E. == F. equals G. An exception is thrown.
A. Note, ArrayList is mutable, so the call to Collections.sort( ) mutates the object.
What is the result? A. -1 B. 10 C. Compiler error on line 4. D. Compiler error on line 5. E. Compiler error on line 6. F. An exception is thrown.
D. After sorting, hex contains [30, 3A, 8, FF]. Remember that numbers sort before letters and strings sort alphabetically. This makes 30 come before 8. A binary search correctly finds 8 at index 2 and 3A at index 1. It cannot find 4F but notices it should be at index 2. The rule when an item isn't found is to negate that index and subtract 1. Therefore, we get -2-1, which is -3.
What is the result? A. 0 1 -2 B. 0 1 -3 C. 2 1 -2 D. 2 1 -3 E. None of the above. F. The code doesn't compile.
C. Converting from an array to an ArrayList uses Arrays.asList(names). There is no asList() method on an array instance. If this code were corrected to compile, the answer would be option A.
What is the result? A. Sue B. Tom C. Compiler error on line 7. D. Compiler error on line 8. E. An exception is thrown.
F. This is a trick question. The first line does not compile because you cannot assign a String to a StringBuilder. If that line were StringBuilder b = new StringBuilder("rumble"), the code would compile and print rum4. Watch out for this sort of trick on the exam. You could easily spend a minute working out the character positions for no reason at all.
What is the result? A. rum B. rum4 C. rumb4 D. rumble4 E. An exception is thrown. F. The code does not compile.
A. First, we delete the characters at index 2 until the character one before index 8. At this point, 0189 is in numbers. The following line uses method chaining. It appends a dash to the end of the characters sequence, resulting in 0189-, and then inserts a plus sign at index 2, resulting in 01+89-.
What is the result? (choose all that apply) A. 01+89- B. 012+9- C. 012+-9 D. 0123456789 E. An exception is thrown. F. The code does not compile.
0. Note, multiple variable can be declared and initialized in the same statement, if they are of the same type. However, here only i3 is initialized, i1 and i2 are only declared. Therefore, their values are set to the default value for ints, 0.
What is the value of i2 in the following code snippet? int i1, i2, i3 = 5;
Access Modifiers
What is used to control the accessibility of your class and its members outside of the class and package?
System.exit(0)
What line of code in a try or catch clause would prevent an associated finally clause from executing?
A, D, E. Interface variables are assumed to be public static final; therefore, options A, D, and E are correct. Options B and C are incorrect because interface variables must be public—interfaces are implemented by classes, not inherited by interfaces. Option F is incorrect because variables can never be abstract.
What modifiers are assumed for all interface variables? (Choose all that apply) A. public B. protected C. private D. static E. final F. abstract
A, B, D, E. Note, C is invalid because type can only be specified once in a single statement. E is invalid because i4 isn't typed.
What of the following are valid declarations? A. boolean b1, b2; B. String s1 = "1", s2; C. double d1, double d2; D. int i1; int i2; E. int i3; i4;
A period.
What separates the package and sub-package names?
B. Note, copies of the s1 and s2 reference are passed to the method, not the references themselves, so reassigning the reference within the method has no effect on the contents of s2 outside the method.
What will be the contents of s1 and s2 at the time of the println statement in the main method of the following program? A. [100] [100] B. [100] [ ] C. [ ] [100] D. [ ] [ ]
D. Note, the insert( ) method of the StringBuilder class inserts the second argument starting at the index position specified by the first argument. The characters starting at that index position before the insert is performed are subsequently shifted to the right.
What will be the output of the following code snippet? StringBuilder sb = new StringBuilder( ); sb.append(123); sb.insert(2,4); System.out.println(sb); A. The code will not compile. B. "1234" C. "1423" D. "1243" E. A StringIndexOutOfBoundsException will be thrown.
E. Note, this one is tricky. The first parameter of the insert method in the StringBuilder class specifies the index position of the insert. In this case, the last StringBuilder index position is 2. If we had specified 3 as the first parameter, the String "2" would have been 'inserted' at the end of the StringBuilder character sequence (i.e., "1232")
What will be the output of the following code snippet? StringBuilder sb = new StringBuilder( ); sb.append(123); sb.insert(4,2); System.out.println(sb); A. "1232" B. "1234" C. "1423" D. "1243" E. A StringIndexOutOfBoundsException will be thrown.
C
What will be the output of the following code: int[ ] numbers = {2,4,6,8,10}; System.out.print(numbers.binarySearch(3)); A. -1 B. 1 C. -2 D. The output is unpredictable. E. The code will not compile.
E. A NullPointerException is thrown by the code on Line 6. The toString() method is being called on an Integer variable that has not been initialized, and that is therefore null.
What will be the output of this program when the given command line invocation is java Program 10? A.NumberFormat Fin1 Fin2 B.NumberFormat Fin1 C.NumberFormat Fin2 D.Fin1 Fin2 E.Fin2 Fin1 followed by uncaught exception
A. The ints Array is initialized to an empty array of 0b101 in length. 0b101 is a binary literal, signified by the prefix 0b, translating to 5 in decimal. The default value for an int is 0, so the empty array of length 5 with type int would contain five 0's.
What will be the output of this program? A. 00000 B. 0000 C. nullnullnullnull D. A NullPointerException is Thrown E. Compilation fails due to error at line 4
B
What will be the output of this program? A. 1Z1-808 B. 1Z0-810 C. 1Z1-801 D. 1Z0-801 E. An ArrayIndexOutOfBoundsException is thrown.
C
What will be the output of this program? A.01 B.02 C.03 D.04 E.Compilation Error
A. When we create an array, elements of the array are initialized to default values. Since the default value of int is zero, all elements will be 0 here. At line 4, while initializing the array, we have passed binary literal which is perfectly legal. Passed binary value is 5 in decimal; so, the array will store 5 elements and the output will contain 5 zeros i.e. 00000.
What will be the output? A. 00000 B. 0000 C. nullnullnullnull D. A NullPointerException is thrown. E. Compilation fails due to error at line 4.
E. Note that the continue statement on Line 9 terminates the for loop, thus rendering the code at Line 11 unreachable.
What will be the output? A. 0112233445 B. 01234 C. 12345 D. Compilation fails due to error at line 7. E. Compilation fails due to error at line 10. F. Compilation fails due to multiple errors.
C. Java tries to use the most specific parameter list it can find. When the primitive int version isn't present, it will autobox. However, when the primitive int version is provided, there is no reason for Java to do the extra work of autoboxing.
What will be the output? A. 1 B. 2 C. 3 D. The code will not compile.
C. Note, this works because the method receives and object reference parameter and subsequently is able to change the attributes of that object. In the main method, when the array is access for printing, it is still just the reference, which is pointing at the same object that was modified by the method.
What will be the output? A. 1 2 3 4 5. B. 1 2 3 4. C. 5 4 3 2 1. D. 5 4 3 2. E. Compilation fails.
C
What will be the output? A. 1234 B. 123 C. 143 D. The code will fail to compile.
D. Note, Line 9 sets the length of the String to 4 so Line 10 throws the exception. If Line 9 were omitted, or the argument passed changed to 5, the exception wouldn't be thrown.
What will be the output? A. 1Z0-800 B. 1Z0-808 C. 1Z0-810 D. A StringIndexOutOfBoundsException E. Compilation fails.
D. The Numeric types provide several convenience methods such as isNaN() and isInfinite(). However, the no-arg version of these methods almost always requires an instance (i.e., is non-static). It follows then, that a call to the static version must pass an argument. Here, Line 7 calls isNaN( ) on the Double class, indicating that is a call to a static method, and not an instance method.
What will be the output? A. true false B. false false C. An Exception is thrown. D. Compilation fails due to error at line 7. E. Compilation fails due to error at line 8.
B. Note, E is incorrect because even with classes that have only the Object superclass, and with all classes generally, the JVM calls the no-arg super constructor by default. Calling it explicitly has no effect.
What will be the output? A. unknown B. parrot C. Unknown parrot D. Compilation fails due to an error at line 18. E. Compilation fails due to an error at line 3.
E. int x cannot be declared twice in the same scope.
What will be the output? A.0123 B.012 C.123 D.222 E.Compilation fails.
E. Note, i is declared inside the do- code block (i.e., is local to do), and is therefore not accessible to the while evaluation.
What will be the output? A.11111 B.12345 C.123456 D.An infinite loop E.Compilation fails
C. Note, in the for-loop, x is re-assigned to 1. Had x been declared final on Line 3, this re-assignment would not have been possible. It iterates through the loop, printing '1', incrementing, iterates again, printing '2', increments again, exits the loop because it is no longer less than 3, and finally the code prints '3'. Note also the last call to .println(), which prints first then terminates the line, so the '3' is printed on the same line as the previous two outputs.
What will be the output? A.12310 B.1210 C.123 D.10 E.Compilation fails.
B. Note that the if statement on Line 10 has the break statement on Line 11 as its execution block. It follows, then, that the break statement on Line 11 is only executed if the if statement on Line 10 is true.
What will be the output? A.3 B.3567 C.34567 D.No output will be produced. E.Compilation fails due to multiple errors.
b
What will the code print?
ba
What will the code print?
shadow
When an argument in a method or constructor has the same name as a field in the class, it is said to ________________ that field.
Anywhere
Where can comments appear in a class definition?
C, E. Option C is allowed because it is a more specific type than RuntimeException. Option E is allowed because it isn't in the same inheritance tree as RuntimeException. It's not a good idea to catch either of these. Option B is not allowed because the method called inside the try block doesn't declare an IOException to be thrown. The compiler realizes that IOException would be an unreachable catch block. Option D is not allowed because the same exception can't be specified in two different catch blocks. Finally, option A is not allowed because it's more general than RuntimeException and would make that block unreachable.
Which of the following can be inserted before e to make this code compile? A. Exception B. IOException C. IllegalArgumentException D. RuntimeException E. StackOverflowError F. None of the above.
D, F. Options A and B are incorrect because LocalDate does not have a public constructor. Option C is incorrect because months start counting with 1 rather than 0. Option E is incorrect because it uses the old pre-Java 8 way of counting months, again beginning with 0. Options D and F are both correct ways of specifying the desired date.
Which of the following can be inserted into the blank to create a date of June 21, 2014? (choose all that apply) A. new LocalDate(2014, 5, 21); B. new LocalDate(2014, 6, 21); C. LocalDate.of(2014, 5, 21); D. LocalDate.of(2014, 6, 21); E. LocalDate.of(2014, Calendar.JUNE, 21); F. LocalDate.of(2014, Month.JUNE, 21);
Constructors
Which of the following can not be declared in an anonymous class: - Fields - Extra methods - Instance initializers - Local classes - Constructors
G. Remember that wrapper classes are final, as are System and StringBuilder and StringBuffer.
Which of the following classes can be extended? (choose all the apply) A. Integer B. Byte C. String D. Long E. StringBuilder F. Boolean G. Number H. System I. StringBuffer
D. A switch works with the byte, short, char, int, String, Integer, and enum data types.
Which of the following data types cannot be used in switch expression? A. char B. enum C. String D. long E. None of the above
D, E
Which of the following exceptions are checked exceptions? (choose all that apply) A. ArrayIndexOutOfBoundsException B. ClassCastException C. ExceptionInInitializerError D. FileNotFoundException E. IOException
A, C, D, E. Option A is correct because it is the traditional main() method signature and variables may begin with underscores. Options C and D are correct because the array operator may appear after the variable name. Option E is correct because varargs are allowed in place of an array. Option B is incorrect because variables are not allowed to begin with a digit. Option F is incorrect because the argument must be an array or varargs. Option F is a perfectly good method. However, it is not one that can be run from the command line because it has the wrong parameter type.
Which of the following legally fill in the blank so you can run the main() method from the command line? (Choose all that apply) public static void main(___________________ ) A. String[ ] _names B. String[ ] 123 C. String abc[ ] D. String _Names[ ] E. String... $n F. String names G. None of the above.
C. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
Which of the following statement is true? A. All classes of Exception extend Error. B. All classes of Error extend Exception. C. Checked Exceptions must be handled or declared to be thrown. D. Runtime Exceptions must be handled or declared to be thrown. E. None of the above.
C, D, E
Which of the following statements are correct? (Choose 3 options.) A. Overloaded methods may change the argument list. B. Overloaded methods should not throw new or broader exceptions. C. Overloaded methods must change the argument list. D. Overloaded methods may change return type. E. Overloaded methods may use the more restrictive access modifier.
C. Note, A is incorrect because p2( ) is a private method. B is incorrect because P hasn't been declared. D is incorrect because print( ) requires an int parameter. C is correct because even though p is an instance, instance can access static methods.
Which of the following statements will compile the code successfully when inserted at line 4? A. Print.p2(6); B. P.p2(6); C. p.print(6); D. Print.print(); E. None of the above
expressions
While local classes are class declarations, anonymous classes are __________________.
varargs
You can use a construct called ______________to pass an arbitrary number of values to a method.
Error, RunTimeException
________________ and _______________________ and its subclasses are unchecked exceptions.
Strings
________________ are immutable sequences of characters.
garbage collection
_________________ _________________ is the process by which the Java runtime environment deletes objects when it determines that they are no longer being used.
java.lang
_________________ is a special package that does not need to be imported.
CLASSPATH
___________________ is an environment variable which is used by Java Virtual Machine to locate user defined classes.
Binary
_____________________ operators perform mathematical operations on more than one variable, create logical expressions, as well as perform basic variable assignments.
array access expression, array reference expression, index expression
a[ b ] is an ___________________ ___________________ ___________________, where a represents the __________________ _________________________ _____________________ and c represents the __________________ _____________________.
3, 1, 2.
int[ ] a[ ] [ ], b, c[ ]; a has ____ dimensions, b has ____ dimensions, and c has _____ dimensions.
java.io.IOException
java.io.FileNotFoundException extends _________________________.
unchecked exceptions
java.lang.Error, java.lang.RuntimeException, and their subclasses are categorized as ________________ ____________________.
compound assignment
result + = 2 is an example of _______________________________.
00110011
~11001100 = _________________
bitwise complement
'~' is the _____________ ______________ operator.
Object, String. Note, the toArray() method of the Array
Consider the following code: List<String> list = new ArrayList<>(); list.add("one"); list.add("two"); Calling list.toArray() will return an array of type _______________ containing elements of type ______________.
10, 5
Consider the following code: StringBuilder s = new StringBuilder(10); s.append("start"); s has a capacity of _________ and a size of ________.
Object
Every class has one and only one superclass except ______________.
A, B, C, E. Note, E is incorrect because INTERVAL was already initialized and is final, therefore, the static initialization block cannot re-assign it.
Given the following class, which of the given blocks can be inserted at line 1 without errors (choose all that apply)? A. static {System.out.println("Static"); } B. static { loop = 1; } C. static { loop += INTERVAL; } D. static { INTERVAL = 10; } E. { flag = true; loop = 0; }
LocalTime.plusHours(1);
How do you add an hour to a LocalTime object?
False. This code will not compile.
True or False. The following code generates a RuntimeException: ArrayList<String> list = new ArrayList<>(); list.add(5);
False
True or False: Static methods can use the this keyword.
False
True or False: The default statement in a switch statement must be located after all case statements.
True
True or False: The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
True
True or False: The static modifier can be applied to inner classes, inner interfaces, variables, and methods.
A, D, E. substring() has two forms. The first takes the index to start with and the index to stop immediately before. The second takes just the index to start with and goes to the end of the String. Remember that indexes are zero based. The first call starts at index 1 and ends with index 2 since it needs to stop before index 3. The second call starts at index 7 and ends in the same place, resulting in an empty String. This prints out a blank line. The final call starts at index 7 and goes to the end of the String.
What are the results of the code? (choose all that apply) A. 12 B. 123 C. 7 D. 78 E. A blank line F. An exception is thrown. G. The code does not compile.
instantiated
Abstract classes cannot be ___________________.
reference, object. Note, this is particularly relevant where the Object is a subclass of the Reference Type (e.g., Animal a = new Dog();). Here, if both classes have static int a, int b, static void c( ), and void d( ); a.a, a.b, and a.c() would all come from Animal, while a.d( ) would come from Dog. Note, this doesn't universally apply. Private methods, for example, won't be access outside their package, regardless of the reference or object type. Protected instance methods, on the other hand, can only be accessed by class outside their package if the accessing class inherits its class and so too does the reference type.
Access to static and instance fields and static methods is determined by the class of the object ________________, while access to instance methods is determined by the _______________ .
Object
All classes in the Java Platform are descendants of _______________.
static
All instances of an object share the ____________ fields of that object.
;
All java statements end with a _____.
array
An __________ is a container object that holds a fixed number of values of a single type.
enum
An ___________ type is a special data type that enables for a variable to be a set of predefined constants.
interface
An ______________ is a contract between a class and the outside world.
inner
An _______________ class is a nested class that is not explicitly or implicitly declared static.
array
An _______________ is a fixed-sized area of memory on the heap that has space for primitives or pointers to objects.
expression
An _________________ is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.
abstract
An ____________________ method is one that is declared without an implementation.
IllegalAccessException
An ___________________________ is thrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or constructor.
extended, overridden
An abstract class must be ___________________, and an abstract method must be _____________________.
ArrayIndexOutOfBoundsException
An array access throws an __________________________ if the value of the array index expression is negative or greater than or equal to the length of the array.
B, E, A, E, D
An array has ____, a String has ____, an ArrayList has ____, and StringBuilder has ____ and ____. (answers may be used more than once) A. size() B. length C. capacity D. capacity() E. length() F. size
ArrayStoreException
An assignment to an array component of reference type throws an ______________________ when the value to be assigned is not compatible with the component type of the array.
transaction
An atomic unit of work that modifies data. A ______________ encloses one or more program statements, all of which either complete or roll back.
classpath
An environmental variable which tells the Java virtual machine and Java technology-based applications where to find the class libraries, including user-defined class libraries.
exception
An event during program execution that prevents the program from continuing normally; generally, an error.
JVM, main
An executable Java class is a class that, when handed over to the ____, starts its execution at a particular point in the class. This point of execution is the _______ method.
JDBC
An industry standard for database-independent connectivity between the Java platform and a wide range of databases.
ArithmeticException
An integer division or integer remainder operator throws an _______________________ if the value of the right-hand operand expression is zero.
binary literal, 0b
An integral data type expressed using the binary number system is known as a ______________ _________________, and is indicated by prefixing ______ to a binary number.
scope
An object becomes eligible for garbage collection when there are no more references to it or its references have all gone out of ____________.
methods
An object exposes its behavior through ________________.
garbage collection
An object is eligible for _________________ _________________ when there are no more references to that object.
fields
An object stores its state in _______________.
wrapper
An object that encapsulates and delegates to another object to alter its interface or behavior in some way.
atomic
An operation that is never interrupted or left in an incomplete state is said to be _________________.
bitwise operator
An operator that manipulates the bits of one or more of its operands individually and in parallel.
innermost, outer
An unlabeled break statement terminates the _____________ switch, for, while, or do-while statement, but a labeled break terminates an __________ statement.
void, return
Any method that is not declared __________ must contain a _______________ statement
0
Arguments are indexed starting with _________.
logical complement
"!" is known as the ___________________________ operator and inverts the value of a boolean.
logical, bitwise
&& and || are __________________ operators, while & and | are ______________ operators.
NaN. Same applies to float.
0d/0 = ___________________.
Infinity. Same applies to double.
2f/0 = ___________________.
Unicode
A 16-bit character set defined by ISO 10646. See also ASCII . All source code in the Java programming environment is written in _____________.
D
A Java class will always have _________ . A. A main method. B. Variable(s). C. At least one method. D. A Constructor. E. All of the above.
default
A Java keyword optionally used after all case conditions in a switch statement. If all case conditions are not matched by the value of the switch variable, the ______________ keyword will be executed.
try
A Java keyword that defines a block of statements that may throw a Java language exception.
throws
A Java keyword used in method declarations that specify which exceptions are not handled within the method but rather passed to the next higher level of the program.
volatile
A Java keyword used in variable declarations that specifies that the variable is modified asynchronously by concurrently running threads.
catch
A Java keyword used to declare a block of statements to be executed in the event that a Java exception, or run time error, occurs in a preceding try block.
do
A Java keyword used to declare a loop that will iterate a block of statements. The loop's exit condition can be specified with the while keyword.
char
A Java keyword used to declare a variable of type character.
final
A Java keyword. You define an entity once and cannot change it or derive from it later. More specifically: a __________ class cannot be subclassed, a __________ method cannot be overridden and a __________ variable cannot change from its initialized value.
block
A ____________ is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
LocalDate, LocalTime, LocalDateTime
A _____________ contains just a date, a _____________ contains just a time, and a _____________ contains both a date and time.
static initialization block
A ______________ _______________________ ___________ is a normal block of code enclosed in braces, { }, and preceded by the static keyword.
unary
A ______________ operator is one that requires exactly one operand, or variable, to function.
final
A ______________ variable may only be assigned to one.
concrete class
A _______________ ____________ is the first class to extend an abstract class.
local. Note, a as long as the local final variable hasn't already been assigned or accessed, it can be assigned. final int x; x = 2; System.out.print(x);
A ________________ final variable can be initialized without a value, then assigned a value, before it is accessed.
statement
A ________________ forms a complete unit of execution.
package, namespace
A ________________ is a ________________ that organizes a set of related classes and interfaces.
IllegalArgumentException
A ________________ is thrown to indicate that a method has been passed an illegal or inappropriate argument.
NumberFormatException
A ________________ is thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
ClassCastException
A ________________ is thrown to signal an attempt to cast an object to a class of which it is not an instance
pipeline
A ____________________ is a sequence of stream operations.
compile-time constant expression
A _____________________ ________________ __________________ is typically a string or an arithmetic expression that can be evaluated at compile time.
narrowing
A ______________________ conversion may lose information about the overall magnitude of a numeric value.
widening
A ______________________ conversion occurs when a small primitive type value is converted to a larger primitive type value.
exception handler
A block of code that reacts to a specific type of exception. If the exception is for an error that the program can recover from, the program can resume executing after the _______________ _______________ has executed.
initializer block
A block of code, without the static keyword, copied by the Java compiler into every constructor, and executed before the constructor completes execution, is called an _______________ ____________.
compile-time error
A call to a method that does not exist will throw a _________________ ______________.
scope
A characteristic of an identifier that determines where the identifier can be used.
package, import
A class can define multiple components. All the Java components you've heard of can be defined within a Java class: ________ and ________ statements, variables, constructors, methods, comments, nested classes, nested interfaces, annotations, and enums.
final
A class can never be declared both _____________ and abstract.
upcasting
A class cast from a child to a parent is known as ________________.
different signatures
A class define multiple methods with the name main and not be THE main method if the use _________________ _________________ than those used in THE main method.
Package
A class defined using default access can't be accessed outside its _______.
nested
A class defined within a class is a ______________ class.
OutOfMemoryError
A class instance creation expression, array creation expression, or string concatenation operator expression throws an ______________________ if there is insufficient memory available.
executeable
A class is said to be ________________ if it has a public static void main method.
checked
A class that extends RuntimeException is a _________________ exception.
E
A class that is derived from another class is called: A. subclass B. derived class C. extended class D. child class E. All of the above
instance
A class variable cannot reference an _________________ variable in its initialization expression.
generic
A class, interface, or method that declares one or more type variables. These type variables are known as type parameters. A ______________ declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. At runtime, all of these parameterized types share the same class, interface, or method.
interface
A collection of methods with no implementation is called an ____________________.
primitive, String
A constant variable is a variable of _______________ type or type __________ that is declared final and initialized with a compile-time constant expression.
A, E, G
A constuctor can have which of the following access modifiers: (choose all that apply) A. private B. abstract C. final D. static E. protected F. synchronized G. public
closest unmatched
A dangling else matches with the __________________ __________________ if.
field
A data member of a class. Unless specified otherwise, a __________ is not static.
definition
A declaration that reserves storage (for data) or provides implementation (for methods).
NullPointerException
A field access throws a _______________________ if the value of the object reference expression is null.
shadowed
A field in a superclass with the same simple name as a field in that class's subclass is said to be ___________________.
transient
A keyword in the Java programming language that indicates that a field is not part of the serialized form of an object.
synchronized
A keyword in the Java programming language that, when applied to a method or code block, guarantees that at most one thread at a time executes that code.
arrow, body
A lambda expression consists of the following: - a comma-separated list of formal parameters, - the __________-token, - a __________.
final, effectively final
A local class can only access local variables that are ____________ or _______________ _____________.
method
A local variable stores temporary state; it is declared inside a ________________.
Static
A method can't be defined both as abstract and _______.
IllegalStateException
A method invoked at an illegal or inappropriate time will throw a ____________________.
return statement
A method returns to the code that invoked it when it: - completes all the statements in the method, - reaches a _______________ ____________________, or - throws an exception; whichever occurs first.
throws an exception
A method returns to the code that invoked it when it: - completes all the statements in the method, - reaches a return statement, or - ______________ _____ ___________________; whichever occurs first.
concrete
A method that is not abstract may be referred to as a ________________ method.
local
A named class declared within the body of a method is known as a ____________ class.
JAR
A platform-independent file format that aggregates many files into one. Multiple applets written in the Java programming language, and their requisite components (.class files, images, sounds and other resource files) can be bundled in a _______ file and subsequently downloaded to a browser in a single HTTP transaction. It also supports file compression and digital signatures.
constructor
A pseudo-method that creates an object. Instance methods with the same name as their class.
name
A public class can be defined only in a source code file with the same ________.
bean
A reusable software component that conforms to certain design and naming conventions.
byte
A sequence of eight bits.
JVM
A software "execution engine" that safely and compatibly executes the byte codes in Java class files on a microprocessor (whether in a computer or in another electronic device).
declaration
A statement that establishes an identifier and associates attributes with it, without necessarily reserving its storage (for data) or providing the implementation (for methods).
non-static
A static method or variable can't access _____ variables or methods of a class.
null
A static variable of type String defaults to ______.
0.0
A static variable of type double defaults to ______.
private
A subclass does not directly inherit the _________________ member(s) of its parent.
public, protected
A subclass inherits all the ______________ and ________________ members of its parents, no matter what package the subclass is in.
members
A subclass inherits all the _________________ from its superclass. This includes fields, methods, and nested classes, but not Constructors.
A, D
A top-level class may be declared: (choose all that apply) A. public B. private C. static D. default (i.e., no access modifier) E. protected
anonymous
A unnamed class declared within the body of a method is known as a ____________ class.
main
A valid Java entry point class must have a method named ______________.
parameter
A variable declared within the opening and closing parenthesis of a method is called a _______________________.
effectively final
A variable or parameter whose value is never changed after it is initialized is _______________ _____________.
compile-time error
Attempt to assign a parent object to a child reference will generate a ______________-________ _____________.
StringIndexOutOfBoundsException
Attempting to access the 8th character in a 7 character String throws a ___________________________.
runtime exception. This occurs because while not all parent types may be of the child type, all instances of the child type will also be of the parent type.
Attempting to cast a parent object to a child object will generate a __________________ _________________.
direct superclass
Before a subclass is initialized, its ______________ ____________________ must be initialized.
object creation
Bicycle myBike = new Bicycle(); is an example of an ____________________ ____________________ statement.
TemporalAmount
Both Period and Duration implement the ________________________ interface.
backed, array.
Callings Arrays.asList() on an array creates a ______________ List. This means that as the List changes, so does the _____________.
downcasting
Casting a superclass object to a subclass object is known as ___________________.
java.lang.String
Character strings are represented by the class __________________.
property
Characteristics of an object that users can set, such as the color of a window.
A
Choose the option that is equivalent to this if-then-else statement: int x = 1; if ( x > 1 ) { System.out.println(">"); } else if ( x < 1 ) { System.out.println("<"); } else { System.out.println("="); } A.System.out.println(x>1?">":x<1?"<":"="); B.System.out.println(x>1?">":"<":"="); C.System.out.println(x>1?">"?"<":"="); D.System.out.println(x>1?">"?"<"?"="); E.None of the above
True
Classes and Interfaces in the same package and all derived classes (Package and Family) can access the members of a protected class?
checked exceptions
Code that may throw ______________ _________________ (2 words) must be placed within a try/catch block.
Multi-line, end-of-line
Comments can be of either ________________ or ___________________ type.
superclass, subclass, extends
Common behavior can be defined in a ___________________ and inherited into a ___________________ using the ___________________ keyword.
>, +
Consider the following code snippet: arrayOfInts[ j ] > arrayOfInts[ j+1 ] What operators does the code contain?
String, ArrayList. Note, ArrayList actually doesn't directly implement the equals( ) method, but rather, it extends AbstractList which does. Ultimately, however, even this implementation simply uses a ListIterator to iterate through the lists checking that each element is equal using the equals( ) method from the Object class. The point here is that contains( ) will use the equals( ) method from the element type.
Consider the following code: ArrayList<String> a1 = new ArrayList<>(); ArrayList<String> a2 = new ArrayList<>(); a1.add("one"); a2.add("one"); a1.contains("one"); //1 a1.equals(a2); //2 The code at //1 calls the equals( ) method from the ________________ class and the code at //2 calls the equals from the ____________________ class.
static, final, abstract
Default methods in interfaces not be marked as _______________, _____________ or ____________, because they require an instance of the class implementing the interface to be invoked are allowed to be overridden in subclasses but are not required to be overridden.
compile time
Errors that occur when you violate the rules of writing syntax are known as ___________-___________ errors.
run time
Errors which occur during program execution after successful compilation are called ___________-___________ exceptions.
casting
Explicit conversion from one data type to another.
statements
Expressions are the core components of _________________________.
removeIf, ArrayList
For the OCA, the only built-in predicate you will need to remember is used in ___________________ method of the ________________ class.
RuntimeException, Error
For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either _____________________ or _____________ are regarded as checked exceptions.
"MMMM d, yyyy hh:mm:ss a". Note, the day is patterned "d" so no leading zero.
Give the DateTimeFormatter pattern that would produce the following output: January 3, 2020 12:15:30 PM
B, A, D, C
Give the order of initialization for a class (e.g., C, A, B) A. static vars/static initializers in order they appear B. superclass C. the constructor. D. instance vars/instance initializers in order appear
C, D, B, F, A, E
Give the order of the data types below in size from smallest to largest: A. float B. int C. byte D. short E. double F. long
A. Test( Test b) { } The constructor can take the same type as a parameter.
Given a class named Test, which of these would be valid definitions for the constructors for the class? Select 1 option A. Test( Test b) { } B. Test Test( ) { } C. private final Test( ) { } D. void Test( ) { } E. public static void Test( String args[ ] ) { }
false 2. Remember, && is short-circuited on a right-operand of true, so it doesn't evaluate the right operand.
Given an int x equal to 2, what will the following output? System.out.println((false && (x++==3)) + " " + x);
true 3. Remember, bitwise operators aren't short-circuited so both operands are evaluated. Further, the pre-increment first increments then returns the value.
Given an int x equal to 2, what will the following output? System.out.println((true & (++x==3)) + " " + x);
true 2. Remember, || is short-circuited on a left-operand of true, so it doesn't evaluate the right operand.
Given an int x equal to 2, what will the following output? System.out.println((true || (x++==3)) + " " + x);
5. There is only one count variable since it is static. It is set to 4, then 6, and finally winds up as 5. All the Koala variables are just distractions.
Given that Koala has a static field count, what is the output of the code?
D. The package name represents any folders underneath the current path, which is named.A in this case. Option B is incorrect because package names are case sensitive, just like variable names and other identifiers.
Given the following class in the file /my/directory/named/A/Bird.java: INSERT CODE HERE public class Bird { } Which of the following replaces INSERT CODE HERE if we compile from /my/directory? (Choose all that apply) A. package my.directory.named.a; B. package my.directory.named.A; C. package named.a; D. package named.A; E. package a; F. package A; G. Does not compile.
B. Option B is correct because arrays start counting from zero and strings with spaces must be in quotes. Option A is incorrect because it outputs Blue. C is incorrect because it outputs Jay. Option D is incorrect because it outputs Sparrow. Options E and F are incorrect because they output Error: Could not find or load main class Bird- Display.class.
Given the following class, which of the following calls print out Blue Jay? (Choose all that apply) A. java BirdDisplay Sparrow Blue Jay B. java BirdDisplay Sparrow "Blue Jay" C. java BirdDisplay Blue Jay Sparrow D. java BirdDisplay "Blue Jay" Sparrow E. java BirdDisplay.class Sparrow "Blue Jay" F. java BirdDisplay.class "Blue Jay" Sparrow G. Does not compile.
A, B. Adding the variable at line 2 makes result an instance variable. Since instance variables are in scope for the entire life of the object, option A is correct. Option B is correct because adding the variable at line 4 makes result a local variable with a scope of the whole method. Adding the variable at line 6 makes result a local variable with a scope of lines 6-7. Since it is out of scope on line 8, the println does not compile and option C is incorrect. Adding the variable at line 9 makes result a local variable with a scope of lines 9 and 10. Since line 8 is before the declaration, it does not compile and option D is incorrect. Finally, option E is incorrect because the code can be made to compile.
Given the following class, which of the following is true? (Choose all that apply) A. If String result = "done"; is inserted on line 2, the code will compile. B. If String result = "done"; is inserted on line 4, the code will compile. C. If String result = "done"; is inserted on line 6, the code will compile. D. If String result = "done"; is inserted on line 9, the code will compile. E. None of the above changes will make the code compile.
B, C, D. 0b is the prefix for a binary value and is correct. 0x is the prefix for a hexadecimal value. This value can be assigned to many primitive types, including int and double, making options C and D correct. Option A is incorrect because 9L is a long value. long amount = 9L would be allowed. Option E is incorrect because the underscore is immediately before the decimal. Option F is incorrect because the underscore is the very last character.
Given the following class, which of the following lines of code can replace INSERT CODE HERE to make the code compile? (Choose all that apply) A. int amount = 9L; B. int amount = 0b101; C. int amount = 0xE; D. double amount = 0xE; E. double amount = 1_2_.0_0; F. int amount = 1_2_; G. None of the above.
E. The first two imports can be removed because java.lang is automatically imported. The second two imports can be removed because Tank and Water are in the same package, making the correct answer E. If Tank and Water were in different packages, one of these two imports could be removed. In that case, the answer would be option D.
Given the following classes, what is the maximum number of imports that can be removed and have the code still compile? A. 0 B. 1 C. 2 D. 3 E. 4 F. Does not compile.
C, D. Option C is correct because it imports Jelly by classname. Option D is correct because it imports all the classes in the jellies package, which includes Jelly. Option A is incorrect because it only imports classes in the aquarium package—Tank in this case—and not those in lower-level packages. Option B is incorrect because you cannot use wildcards anyplace other than the end of an import statement. Option E is incorrect because you cannot import parts of a class with a regular import statement. Option F is incorrect because options C and D do make the code compile.
Given the following classes, which of the following can independently replace INSERT IMPORTS HERE to make the code compile? (Choose all that apply) A. import aquarium.*; B. import aquarium.*.Jelly; C. import aquarium.jellies.Jelly; D. import aquarium.jellies.*; E. import aquarium.jellies.Jelly.*; F. None of these can make the code compile.
A, B, C. Option A is correct because it imports all the classes in the aquarium package including aquarium.Water. Options B and C are correct because they import Water by classname. Since importing by classname takes precedence over wildcards, these compile. Option D is incorrect because Java doesn't know which of the two wildcard Water classes to use. Option E is incorrect because you cannot specify the same classname in two imports.
Given the following classes, which of the following snippets can be inserted in place of INSERT IMPORTS HERE and have the code compile? (Choose all that apply) A. import aquarium.*; B. import aquarium.Water; import aquarium.jellies.*; C. import aquarium.*; import aquarium.jellies.Water; D. import aquarium.*; import aquarium.jellies.*; E. import aquarium.Water; import aquarium.jellies.Water; F. None of these imports can make the code compile.
B. Note, A and C are incorrect because the source code file name must be fully specified, and D (C also) is incorrect because the code accesses the element at index 1, so a minimum of 2 arguments must be passed
Given the following code - public class MyFirstClass{ public static void main(String[] args){ System.out.println(args[1]); } } Which of the following commands will compile and then print "hello"? A. javac MyFirstClass java MyFirstClass hello hello B. javac MyFirstClass.java java MyFirstClass hello hello C. javac MyFirstClass java MyFirstClass hello D. javac MyFirstClass.java java MyFirstClass hello
A
Given the following code, what could be inserted at //1 to print Jan 20, 2020 11:12:34 AM? LocalDate date = LocalDate.of(2020, 1, 20); LocalTime time = LocalTime.of(11, 12, 34); LocalDateTime dateTime=LocalDateTime.of(date,time); DateTimeFormatter mediumF = //1 System.out.println(mediumF.format(dateTime)); A. DateTimeFormatter .ofLocalizedDateTime(FormatStyle.MEDIUM); B. DateTimeFormatter .ofLocalizedDateTime(FormatStyle.SHORT); C. DateTimeFormatter .ofLocalizedDate(FormatStyle.MEDIUM); D. None of the above.
E. Note, the Datetimeformatter.ofLocalizedDateTime ( ) method was passed FormatStyle.SHORT, which prints an abbreviated date format (e.g., "1/20/20, 11:12 AM").
Given the following code, what could be inserted at //1 to print Jan 20, 2020 11:12:34 AM? LocalDate date = LocalDate.of(2020, 1, 20); LocalTime time = LocalTime.of(11, 12, 34); LocalDateTime dateTime=LocalDateTime.of(date,time); DateTimeFormatter mediumF = DateTimeFormatter .ofLocalizedDateTime(FormatStyle.SHORT); System.out.println(//1); A. mediumF.format(dateTime) B. dateTime C. mediumF(dateTime) D. dateTime.format(mediumF); E. None of the above.
B, C, G. B and C are incorrect because child method cannot declare a new checked exception. C is incorrect because child method cannot declare a broader checked exception.
Given two methods in two different classes, a Parent class and a Child subclass, and a Child method that overrides a Parent method, assuming all thrown exceptions are handled, which of the following will generate a compiler error? A. Parent method declares IOException, Child method declares RuntimeException. B. Parent method declares RuntimeException, Child method declares Exception. C. Parent method declares no exception, Child method declares Exception. D. Parent method declares IllegalArgumentException, Child method declares NumberFormatException. E. Parent method declares no exception, Child declares RuntimeException. F. Parent method declares NullPointerException, Child method declares RuntimeException. G. Parent method declares FileSystemNotFoundException, Child method declares IOException.
E. Size or length of the array is the number of elements in an array. Index positions of an array start from zero, so the last index is 1 less than the length. Here array has 5 elements, so the size of the array is 5 and the last index is 4. So we can access the last element by using chars.length-1 or 4. So option D is correct. Options A and B are incorrect since they are not the last indexes of the array
Given: char [ ] chars = {'A', 'B', '1', '2', '@'}; Which of the following can access the value of @ in this given array? A. chars[3]; B. chars[5]; C. chars[chars.last]; D. chars[chars.length-1]; E. Given array is invalid.
A
Given: String mStr = "123"; long m = // 1 Which of the following options when put at //1 will assign 123 to m? A. new Long(mStr); B. Long.parseLong(mStr); C. Long.longValue(mStr); D. (new Long()).parseLong(mStr); E. Long.valueOf(mStr).longValue();
data encapsulation
Hiding internal state and requiring all interaction to be performed through an object's methods is known as ________________ ________________.
Period.of(0, 1, 1);. Note, the method signature is Period.of(int years, int months, int days).
How do you create a Period of a month and a day?
LocalDateTime.now()
How do you create an object with the current date and time?
16
How many bits in a char?
64
How many bits in a double?
32
How many bits in a float?
64
How many bits in a long?
16
How many bits in a short?
32
How many bits in an int?
0 or more.
How many instance variables, methods, and constructors can a class define?
B. Note, garbage collection removes objects not references from the heap, and the questions indicates as much by asking 'How many objects...'. So, p and p1 are both references to the same Pc object. However, by assigning them both to null, there is no longer a reference to that Pc object by Line 14. c still holds its reference to a Capacitor object so it's not elegible for GC, leaving the single Pc Object eligible.
How many objects are eligible for GC at line 14?
Only once, if at all
How many times can a package statement appear in a class?
F. In this example, the update statement of the for loop is missing, which is fine as the statement is optional, so option D is incorrect. The expression inside the loop increments i but then assigns i the old value. Therefore, i ends the loop with the same value that it starts with: 0. The loop will repeat infinitely, outputting the same statement over and over again because i remains 0 after every iteration of the loop.
How many times will the code print "Hello World"? A. 9 B. 10 C. 11 D. The code will not compile because of line 3. E. The code will not compile because of line 5. F. The code contains an infinite loop and does not terminate.
infinite loop
How might this loop be characterized? for ( ; ; ) { } ?
LocalDate.now().plusDays(7);
How might you return a LocalDate object representing the date 7 days from today?
Period.of(1,6,0)
How would you create a TemporalAmount object that represents 1 year, 6 months, and 0 days?
Duration.of(270, ChronoUnit.MINUTES);
How would you create a TemporalAmount object that represents every 4 and a half hours?
numbers
Identifi ers may not begin with ________________.
first
If a class defines a package statement, where should it be in the class definition?
default constructor, Object
If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the _________________ _________________. This constructor calls the class parent's no-argument constructor, or the ______________ constructor if the class has no other parent.
Default
If a class is defined without an access modifier what access does it have?
typecast
If a parent class holds a reference to a child object, it may access child members if it is first _______________.
hidden
If a subclass field has the same name as a superclass field, the superclass field is said to be _______________.
package-private
If a subclass is in the same package as its parent, it also inherits the ________________-______________ members of the parent.
left
If bitwise AND is used with two non-boolean operators, it will return the ____________ operand.
right
If bitwise OR is used with two non-boolean operators, it will return the ____________ operand.
abstract
If class B implements interface A, class B must implements all of the methods declared in interface A, unless class B is _______________.
integral, floating-point
If one of the values is integral and the other is floating-point, Java will automatically promote the ______________ value to the ____________________ value's data type.
overridden, default
If subclass B of interface B wants to call method c( ) with an implementation defined in the interface, the method must not be __________________ by B and must be declared with the _____________ keyword in the interface.
overridden
If two methods in a parent and a child class have the same name, but a different signature, the parent method is said to be ___________________.
overloaded
If two methods in a parent and a child class have the same name, but a different signature, they are said to be __________________.
larger
If two values have different data types, Java will automatically promote one of the values to the _____________ of the two data types.
subtype
If type X extends or implements type Y, then X is a ________________ of Y.
numeric
In Java you cannot perform a logical inversion of a __________________ value.
right, left
In Java, two assignment operators on the same line are evaluated ___________ to _____________.
first
In a Constructor, If this() is present, it must be the _________ statement in the constructor.
line terminator
In a String literal, it is a compile-time error for a __________ ___________________ to appear after the opening " and before the closing matching ".
int. Note, otherwise a compile-time error occurs.
In an array access expression the, index expression must be promotable to ___________.
public, static, final
In an interface, all fields are automatically ____________ , ____________ , and __________________.
static
In order for a subclass method to hide a superclass method, both must be _________________.
static import
In order to use a static member from another class without having to specify the class name every time you reference it, you can use a _______________ _________________.
single precision
In the Java programming language specification, ______________ _______________ describes a floating point number that holds 32 bits of data.
double precision
In the Java programming language specification, ______________ _______________ describes a floating point number that holds 64 bits of data.
method declarations, statements
In the body of an anonymous class, _____________ _________________ are allowed, but _____________ are not.
client
In the client/server model of communications, the ____________ is a process that remotely accesses resources of a compute server, such as compute power and large memory capacity.
enum
In the code below, 'Day' is an example of an _________: public ***** Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
varargs, 0, more
In the code snippet public Polygon polyFrom(Point... corners) { }, 'Point... corners' is an example of using ______________ and can be called with _____ or __________ Point arguments.
b, dangling else
In the following code, the else statement is associated with which if test (a or b), and this is known as a ___________________ ______________: if (a) if (b) d++; else e++;
int
In the following declaration statement, variable b is of type ________. int [ ] a, b;
initialization, termination, increment
In the for loop: for (int x = 0; x<11; x++ { System.out.println(x); } int x = 0 is the _______________ expression, x < 11 is the _________________ expression, and x++ is the _____________________ expression.
parse, valueOf. Note, this is easy to remember because the parse methods specify the primitive data type of their return value (e.g., parseInt, parseLong, etc.).
In the primitive wrapper classes, the ____________ methods return a primitive from a String or a primitive of the same type and the _____________ methods return an object of the same type as the wrapper class.
octal, 64. Note, octal conversion involves multiplying the number at position by 8 raised to the position number.
In the statement int x = 0100; 0100 is an example of an _____________ literal and has the decimal value of ________.
G. Array brackets can only be placed after type declaration or after variable names.
In the statement int x[ ], y, [ ][ ]z; (choose all that apply) A. x is an int B. y is a 1D array C. z is a 2D array D. y is an int E. z is a 3D array F. x is a 1D array G. Does not compile.
C, D, F
In the statement int x[ ], y, z[ ] [ ]; (choose all that apply) A. x is an int B. y is a 1D array C. z is a 2D array D. y is an int E. z is a 3D array F. x is a 1D array G. Does not compile.
a[0]
Indexes begin with 0 and elements are referred to using ________.
return statement
Instance initializers can not include a ____________ __________________.
null
Instance variables default to _________________.
serialization
Java _____ is the standard mechanism for saving an object as a sequence of bytes (stream) that can later be rebuilt into a copy of the object
finally
Java keyword that executes a block of statements regardless of whether a Java Exception, or run time error, occurred in a block defined previously by the try keyword.
T
Java separates date and time with a ________ when converting LocalDateTime to a String.
non-static
Local classes are ______________ because they have access to instance members of the enclosing block.
Trick question, local variables do not have a default value and must be initialized or does not compile.
Local variables default to __________________.
bytecode
Machine-independent code generated by the Java compiler and executed by the Java interpreter.
from. For example, YearMonth.from(LocalDate date), Month.from(LocalDate date), DayOfWeek.from(LocalDate date), DayOfMonth(LocalDate date).
Many of the classes in java.time can retrieve date parts from a date object using the _____________ method.
0. Note, rounding is a standard mathematical procedure where the number that lies exactly between two numbers always rounds up to the higher one.
Math.round( ) will round -0.5 to _________.
static
Member classes of interfaces are implicitly ______________.
interface
Methods not defined as default or static in an ________________ are implictly abstract.
static nested, inner
Nested classes that are declared static are called ____________ ____________ classes. Non-static nested classes are called _______________ classes.
underscores
Numeric literals are also allowed to contain _________________ as long as they are directly between two other numbers.
expressions
Operators may be used in building __________________, which compute values.
All of them.
Package and Import statements apply to which class and interface definitions in a source code file?
Parentheses, Array Access, Dot Unary Post Unary Pre Cast, New Arithmetic Bitwise Shifts Relational Equality Bitwise And Bitwise Or Bitwise Exclusive Or Logical And Logical Or Ternary Assignment
Period Parents of Poster Preteens! U Nary should Cast Anew these Times for Math Shifts to Relate Equally, and kids would Bitwise And Exclusively mOre Logical to HAnd Or to Ternary your Assignments.
by value
Primitive arguments, such as an int or a double, are passed into methods ____ _____________. This means that any changes to the values of the parameters exist only within the scope of the method the arguments were passed to. When the method returns, the parameters are gone and any changes to them are lost.
fields
Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's _____________ can be changed in the method, if they have the proper access level.
boolean
Refers to an expression or variable that can have only a true or false value.
int
Smaller data types, namely byte, short, and char, are first promoted to _____ any time they're used with a Java binary arithmetic operator.
state, behavior, fields, methods
Software objects have two key characteristics; ____________ and _____________, represented by _________________ and ________________.
Class
Static attributes are also known as ______ fields or ______ methods because they're said to belong to their class, not to any instance of that class.
immutable, mutable
String is an __________________ class, meaning its value cannot be changed, StringBuilder is a _________________ class, meaning its value can be changed.
string pool
String literals are stored in the __________ ___________.
string pool
String literals are stored in the _____________ _________.
content, address
String.equals() performs _________________ comparison, while '==' performs __________________ comparison.
ArrayList
StringBuilder is to String as ___________________ is to Array.
overriding
Subclass methods with the same signature as superclass methods are referred to as ___________________ methods.
B, D. The Rabbit object from line 3 has two references to it: one and three. The references are nulled out on lines 6 and 8, respectively. Option B is correct because this makes the object eligible for garbage collection after line 8. Line 7 sets the reference four to the now null one, which means it has no effect on garbage collection. The Rabbit object from line 4 only has a single reference to it: two. Option D is correct because this single reference becomes null on line 9. The Rabbit object declared on line 10 becomes eligible for garbage collection at the end of the method on line 12. Calling System.gc() has no effect on eligibility for garbage collection.
Suppose we have a class named Rabbit. Which of the following statements are true? (Choose all that apply) A. The Rabbit object from line 3 is first eligible for garbage collection immediately following line 6. B. The Rabbit object from line 3 is first eligible for garbage collection immediately following line 8. C. The Rabbit object from line 3 is first eligible for garbage collection immediately following line 12. D. The Rabbit object from line 4 is first eligible for garbage collection immediately following line 9. E. The Rabbit object from line 4 is first eligible for garbage collection immediately following line 11. F. The Rabbit object from line 4 is first eligible for garbage collection immediately following line 12.
java.lang.Error
System problems that are considered 'unrecoverable' are indicated by the ______________________________ class.
method invocation
System.out.println("Hello World!"); is an example of a __________________ _________________ statement.
expression statement
Terminating an expression with a semicolon ( ; ) forms an _________________ __________________.
diamond
The <> in List<Integer> a = new ArrayList<>(); is called the _______________ operator.
elements, order. Note, ArrayList actually doesn't directly implement the equals( ) method, but rather, it extends AbstractList which does.
The ArrayList class's implementation of the equals ( ) method checks if two ArrayLists have the same ______________ in the same _____________.
boolean, object, E
The ArrayList remove( ) method returns a _______________ if passed an index position and an ___________________ of type ________ if passed an object.
compiles, executes
The JDK ________________ code, the JRE _______________ code.
hours, minutes, seconds, nanoseconds
The LocalTime.now( ) method returns ___________, ______________, _____________, and _________________.
Abstract and Static
The OCA Java SE 7 Programmer I exam covers only two nonaccess modifiers: What are they?.
Object
The String equals() method acceps a parameter of type _______________.
J
The StringBuilder insert and append methods accept which of the following data types? A. Object B. StringBuffer C. StringBuilder D. String E. int F. char G. byte H. long I. short J. All of the above.
switch
The ___ statement allows for any number of possible execution paths.
JDK
The _________ is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.
new
The _________ operator instantiates a class by allocating memory for a new object and returning a reference to that memory.
JRE
The _________ provides the libraries, the JVM, and other components to run applets and applications written in the Java programming language.
while
The ____________ statement continually executes a block of statements while a particular condition is true.
bitwise AND
The _____________ ________ operator evaluates both operands and returns true if both are true, false if not, and always evaluates the right operand regardless of whether the left operand is true or not.
logical AND
The _____________ ________ operator evaluates both operands and returns true if both are true, false if not, but does not evaluate the right operand if the left operand is false.
Period
The ______________ class represents a number of days, months, or years to add or subtract from a LocalDate or LocalDateTime.
default
The ______________ section handles all values that are not explicitly handled by one of the case sections.
finalize
The ______________() method will run once for each object if/when it is fi rst garbage collected.
bitwise AND
The _______________ ________ operator compares the bits of two binary values and returns a 1 for each bit position that is equal to 1 in both of the binary values.
bitwise OR
The _______________ ________ operator compares the bits of two binary values and returns a 1 for each bit position that is equal to 1 in either of the binary values.
bitwise XOR
The _______________ ________ operator compares the bits of two binary values and returns a 1 for each bit position that is equal to 1 in either, but not both, of the binary values.
hashcode
The _______________ method returns an integer value generated by a hashing algorithm.
return
The _______________ statement exits from the current method, and control flow returns to where the method was invoked.
instanceof
The ________________ operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
critical section
The _________________ _______________ is a segment of code in which a thread uses resources (such as certain instance variables) that can be used by other threads, but that must not be used by them at the same time.
extends, implements
The _________________ keyword can only be used to inherit from one class, while the ________________ can be used to inherit from multiple classes.
JVM
The ___________________ is responsible for the hardware- and operating system-independence of the Java SE platform, the small size of compiled code (bytecodes), and platform security.
continue
The ___________________ statement skips the current iteration of a for, while , or do-while loop.
compiler
The ___________________ translates source code written in the Java programming language into bytecode for the Java virtual machine
assignment, access, parentheses
The _____________________ operators have the lowest precedence and ________________/_______________ operators have the highest.
pre
The _______fix increment increments, then return the value.
post
The _______fix increment returns the value, then increments.
autoboxing
The automatic conversion between primitive and reference types is called _____________________.
autoboxing
The automatic conversion from a primitive value to a corresponding wrapper object is known as ______________.
java.lang.Throwable
The base class of all exceptions is ___________________________.
literal
The basic representation of any integer, floating point, or character value.
thread
The basic unit of program execution. A process can have several running concurrently, each performing a different job, such as waiting for events or performing a time-consuming job that the program doesn't need to complete before going on.
class
The blueprint from which individual objects are created is called a ___________.
short-circuit
The boolean operators && and || are known as _____________-_____________ operators.
nearest inner. The optional label parameter allows us to break out of a higher level outer loop.
The break statement will terminate the ____________ ____________ loop it is currently in the process of executing.
a/b/c/
The bytecode for a class named Hello in the a.b.c package must appear in what directory structure?
Exception, Throwable
The class _______________ and its subclasses are a form of ____________________ that indicates conditions that a reasonable application might want to catch.
superclass
The class from which a subclass is derived is called a _______________.
D. Note, while it is true that the method has not been implemented, the JVM never makes that determination has it first hits the NullPointerException when it attempts to call the method on x, which is null.
The code will throw which of the follow: A. MethodNotImplementedException B. NoSuchMethodError C. It will not compile. D. NullPointerException
javac, bytecode
The command-line command ____________ compiles java source code into _______________.
javaw
The command-line command _____________ starts a Java runtime environment, loads a specified class, and calls that class's main method, but does not open a console window.
java
The command-line command _____________ starts a Java runtime environment, loads a specified class, and calls that class's main method.
javac MyClass.java java MyClass
The correct syntax for compiling and executing a class named MyClass, that takes no arguments, from the command-line would be ___________________________________________.
16
The default capacity of a StringBuilder object is _______.
classname, hashcode
The default implementation of the toString( ) method on the Object class returns "_______________@_____________".
false
The default value for a boolean variable is ________________.
0.0F
The default value for a float variable is _________________.
null
The default value of a reference variable is _________.
'\u0000', null
The default value of char variables is the unicode character _______________ (answer with apostrophes), which represents ____________.
bottom, execute at least once
The difference between a while and a do-while loop is that the do-while loop evaluates its expression at the ______________ of the loop, and therefore, the statements within the do block always __________ ____ ________ ______.
enhanced
The following form of the for-loop is referred to as the _________________________ for statement: int[ ] numbers = { 1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); }
abstract. Note, the absence of an implementation (i.e., code block) indicates that the method is abstract.
The following method declaration indicates an _______________ method: public int methodName;
ofLocalizedDate, ofLocalizedDateTime, ofLocalizedTIme, ofPattern
The four Static methods in the DateTimeFormatter class that may be used to return a DateTimeFormatter instance for subsequent date/time formatting are _________________, _____________________, _____________________, and _________________.
JVM
The main method accepts an array of type String containing the method arguments passed to it by the ___.
exception handler
The mandatory block of code following a catch is known as the _______________ ________________.
MAX_VALUE, enum
The maximum value for a Numeric class can be retrieved via ________________ which an ___________ given in each of the Numeric types.
Same class
The members of a class defined using a private access modifier are accessible where?
name, parameter, signature
The method __________________ and the __________________ types comprise the method __________________.
if
The most basic control flow statement supported by the Java programming language is the ___ statement.
instantiation
The new keyword is a Java operator that creates the object. This is referred to as _________________.
initialization
The new operator is followed by a call to a constructor. This is referred to as ____________________.
constructor
The new operator requires a single, postfix argument: a call to a ___________________.
hexadecimal
The numbering system that uses 16 as its base. The marks 0-9 and a-f (or equivalently A-F) represent the digits 0 through 15.
octal
The numbering system using 8 as its base, using the numerals 0-7 as its digits.
NumberFormatException
The numeric types will throw a ________________________ is a string that cannot be converted to their respective type is passed to their parse or valueOf methods.
varargs
The parameters pass to the code below are example of ________________. List<String> list = Arrays.asList("one","two");
commit
The point in a transaction when all updates to any resources involved in the transaction are made permanent.
set, reference to a new String, element that was replaced
The replace( ) method is to String as the _________( ) method is to ArrayList, except the former returns a _________________ _____ ____ ________ _____________ and the latter returns the ___________________ ________ ______ ______________.
bit
The smallest unit of information in a computer, with a value of either 0 or 1.
constants
The static modifier, in combination with the final modifier, is also used to define _______________.
contains
The str._______________( ) method is convenience method for str.indexOf(otherString) != -1
covariant return type
The technique referred to as ________________ ________________ ______________, means that the return type is allowed to vary in the same direction as the subclass.
static field
The term "class variable" is another name for a _________________.
non-static field
The term "instance variable" is another name for a ______________.
Consistency
The transaction property represented by the letter C in ACID stands for _________________.
Durability
The transaction property represented by the letter D in ACID stands for _________________.
Isolation
The transaction property represented by the letter I in ACID stands for _________________.
FormatStyle.SHORT, FormatStyle.MEDIUM
The two DateTimeFormatter styles that may show up on the exam are __________________________ and __________________________.
parent, child
To cast from a ________________ to a ____________________, the cast must be explictly typed.
Period
To create a TemporalAmount of a day or more, you should use the ________________ class.
Duration
To create a TemporalAmount of less than a day, you should use the ________________ class.
parse, format, default format
To create a date/time object from a string, you can call the static method ______________ ( ) in the LocalDate, LocalTime, or LocalDateTime classes, which takes a String argument as its first parameter and an optional ______________ argument as its second parameter. If no second parameter is passed, the ______________ ______________ for the class from which the static method was called will be used.
target
To determine the _____________ type of a lambda expression, the Java compiler uses the target type of the context or situation in which the lambda expression was found.
~
To get the two's complement of any number, you can use the bitwise operator ____ (answer with symbol).
binarySearch
To use the Arrays.________________( ) method, you must have a sorted array.
False. An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int, so an int can't be assigned 1L.
True or False. 1L is valid as both an integer literal and as an assignment value for an int variable.
True
True or False. A case statement must be literals, enum constants, or final constant variables.
True. A class can, and actually must, use the interface class to access static methods, regardless of whether it implements the interface or not (e.g., InterfaceClass.staticMethod();)
True or False. A class can access a static interface method without implementing the interface.
False. A class can only implement an interface.
True or False. A class can extend an interface.
True
True or False. A class can not extend an interface.
False
True or False. A class declared as a final can be subclassed.
False. If the identical default methods are overriden by the implementing class, the code will compile.
True or False. A concrete class or abstract class that implements two or more interfaces containing identical default methods will always generate a compile-time error.
False. There are no default values assigned for local variables.
True or False. A local variable of type String will default to null.
False
True or False. A method declared as final can be overriden.
True. If a checked exception is thrown anywhere, it must be handled or declared.
True or False. A method that throws an IOException with IOException or a superclass of IOException declared throws in its signature or that of an overriden superclass method will generate a compile-time error.
False
True or False. A non-abstract class may contain abstract methods.
False. A reference to a class may be automatically used as a reference to a superclass without an explicit cast.
True or False. A reference to a class may be automatically used as a reference to a subclass without an explicit cast.
True
True or False. A return statement contained within the body of an instance initializer or static initializer block will generate a compile-time error.
False. If the return statement has no expression, it will not generate a compile-time error.
True or False. A return statement included in a constructor will always generate a compile-time error.
True. The effect of doing this is to effectively define the class as not an inner-class.
True or False. A static class may be declared within a non-static class.
False (except through a reference to a class instance)
True or False. A static method is allowed to reference an instance variable.
False. A switch statement cannot have a boolean target variable. It must be one of the numeric primitives or their wrappers, String, or an enum.
True or False. A switch statement must have a boolean target variable.
True
True or False. A switch statement must have one of the following date types: char, byte, short, int, Character, Byte, Short, Integer, String, or an enum.
True
True or False. A variable can begin with a letter, a dollar sign, or an underscore, and nothing else.
True
True or False. Abstract class can be subclassed.
True. When an interface extends another interface that contains a default method, it may choose to ignore the default method, in which case the default implementation for the method will be used. Alternatively, the interface may override the definition of the default method using the standard rules for method overriding, such as not limiting the accessibility of the method and using covariant returns. Finally, the interface may redeclare the method as abstract, requiring classes that implement the new interface to explicitly provide a method body. Analogous options apply for an abstract class that implements an interface.
True or False. Abstract classes that implement or interfaces that extend an interface with default methods may override or re-declare those methods as abstract.
True
True or False. All classes and interfaces in the same package visible to each other by default.
True
True or False. All numeric operations with NaN as an operand produce NaN as a result.
True
True or False. An Exception may be declared as a method return type?
False.
True or False. An abstract class can be instantiated.
False. Only applies to concrete classes.
True or False. An abstract class that implements an interface must implement any abstract methods declared in that interface.
False. This one is tricky. An abstract method may also be declared in an interface, which is implictly abstract.
True or False. An abstract method can only be declared inside an abstract class.
True
True or False. An if statement may be followed by an empty code block, e.g., if(x=2) { }
True
True or False. An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
False. An interface may only extend zero or more other interfaces.
True or False. An interface can implement zero or more other interfaces.
False. While an interface shares many properties of an abstract class, it is not actually an abstract class.
True or False. An interface is a type of abstract class.
False. An interface may only extend one or more other interfaces.
True or False. An interface may extend one or more classes.
False. Arrays.asList( ) returns an array-backed List.
True or False. Arrays.asList( ) returns an ArrayList.
False. It's static, it doesn't need an instance.
True or False. Attempting to access a static member using a null reference will result in a NullPointerException.
False. Both of these are class variables in the Boolean wrapper class and are of type boolean. Boolean.TRUE == new Boolean(true); and Boolean.FALSE == new Boolean(false);
True or False. Boolean.TRUE is equal to the String "true" and Boolean.FALSE is equal to the String "false".
True
True or False. Both the insert and append methods of the StringBuilder class can accept a boolean argument.
False. For static members, the JVM uses the reference type for access, not the object type.
True or False. Calling a Static method from reference with a pointer to null will throw a NullPointerException.
False. DateTimeFormatter is in the java.time.format package.
True or False. DateTimeFormatter is in the java.time package.
False
True or False. Field initialization and instance initializer blocks are executed after the constructor is executed.
True. Remember, immutable is only measured after the object is constructed. Immutable classes are allowed to have values. They just can't change after instantiation.
True or False. Fields in immutable classes can be changed in the constructor.
False. All fields in interfaces are public static and final.
True or False. Fields with a default implementation in an interface can be re-assigned in the constructors of classes that implement them.
False. Only the last exception is thrown.
True or False. Given a try-catch-finally block of code, if the try, catch, and finally all throw exceptions, all three will be thrown by the JVM.
False. Note, subList( ) method is exclusive, meaning neither the first argument fromIndex or the second argument toIndex are included. This will return an empty list (i.e., no elements).
True or False. Given that myList is an ArrayList, mylist.subList(1, 1) will return a list with 1 element.
True. Note, String.replace( ) should be preferred where the first argument is not a regex, for performance reasons.
True or False. Given the same arguments, String.replace() and String.replaceAll will produce the same result.
True. Two wrapper objects created using autoboxing from the same primitive (i.e., no new keyword) are the same object.
True or False. Given two Integer objects x and y, equal to 5, x.equals(y).
False.
True or False. If !x.equals(y), then x.hashcode() must not produce the same value as y.hashcode().
False
True or False. If a subclass field hides a superclass field, the subclass field must have the same type as the superclass field.
False. The more general catch blocks must appear below the more specific ones.
True or False. If a try statement has catch blocks for IllegalArgumentException and RuntimeException, the catch blocks can be in either order.
False. Only the first concrete class that extends an abstract class must implement all the abstract methods defined it it.
True or False. If abstract class B extends abstract class A, B must implement all the abstract methods defined in A.
False. If an exception is caught in the try clause, the JVM stopes executing the try clause, moves and executes the exception handler, then moves on, either to the finally clause or the next statement outside the try-catch. Code remaining in the try clause beyond the exception does not get executed.
True or False. If an exception is caught halfway through a try clause, the JVM moves straight to the catch clause, executes it, then returns to the try clause and executes any remaining statements there.
False. Static classes cannot be instantiated.
True or False. If static class B is declared within non-static class A, and A is instantiated as instanceA, instanceA holds an instance of class B.
True
True or False. If there is a return statement in the finally block of a try-catch-finally, it will override return statements in the try and/or catch blocks.
True
True or False. If x.equals(y), then x.hashcode() must equal y.hashcode().
True.
True or False. In Java, all objects are accessed by reference.
False
True or False. In a method, if there is a return statement in the finally block of a try-catch-finally, statements may follow the try-catch-finally as long as they are not returns.
False. The index expression is not evaluated only in cases where the array reference expression completes abruptly. In this case the abrupt completion doesn't occur until the attempt to access the null array reference, which doesn't happen until after the index expression is evaluated.
True or False. In an array access expression, if the array reference expression is null, then the index expression is not evaluated.
False. Null references in System.out.print() will return the string "null".
True or False. Including a null reference in a System.out.print() will result in a NullPointerException.
False
True or False. Inner classes may use local variables that have been declared, but not intialized..
False. An exception must be thrown in the try clause in order for the exception handler to execute.
True or False. It is possible for an exception to be thrown in a catch clause even if one is not thrown in its corresponding try clause.
False
True or False. Java allows operator overloading.
True
True or False. Java compiled on Windows can run on Linux.
False. Java has references, not pointers.
True or False. Java has pointers to specific locations in memory.
False. Fundamentally, it is OOP, although, it does allow for the implementation of some functional programming concepts.
True or False. Java is a functional programming language.
False
True or False. Java is a procedural language.
True
True or False. Java is an object-oriented language.
False.
True or False. Static variables can be defined inside methods.
False. StringBuilder extends Object.
True or False. StringBuilder extends String.
False.
True or False. StringBuilder overrides the equals method.
True.
True or False. The Number class can be extended.
False. The StringBuilder class does not provide an implementation of the equals( ) methods and therefore checks only to see if two objects hold references to same StringBuilder object.
True or False. The StringBuilder.equals( ) method checks to see if the contents of two StringBuilder instances is the same.
True. But it is not necessary.
True or False. The abstract keyword can be used when declaring an interface.
True
True or False. The class will fail to compile if you place an import statement before a package statement.
True. Note, System.out.println attempts conversion of objects to String, calling the toString( ) method. In this case, the StringBuilder class provides an implementation of toString( ) that returns the String value of its contents.
True or False. The code snippet below prints "Hello World". StringBuilder sb = new StringBuilder(" World"); System.out.println("Hello" + sb);
False. Interfaces can extend multiple interfaces. This statement is true, however, for classes.
True or False. The extends keyword can never be followed by a comma-separated list of parents.
constants
True or False. The fields of an interface are ________________ by default.
False. Note, null is a valid return type for all the primitive wrapper classes, but returning null like this is generally discouraged. If the return type was the primitive boolean, this would not compile.
True or False. The following code causes a compile-time error: public Boolean getBool( ) { return null; }
False. Note, this a notable exception to the general reull of thumb regarding objects and equality. Remember that String literals are pooled, meaning only one object is placed in the string pool and multiple objects can hold a reference to that same object. Here, x and y both hold references to the same String object in the string pool.
True or False. The following code outputs true: String x = "Hello World"; String y = "Hello World"; System.out.println(x == y);
False. The code will print false. Note, because the dot(.) operator has the same precedence as the parentheses operator, the JVM will use left-to-right associativity (the associativity of those operators). So, it works out the dot(.) first, evaluating first the left hand side of the dot(.), e.g., "one".equals(str1 = str2). Then, it moves to the right operand of the dot(.) operator, but before it can call equals, it must evaluate the expression inside the parentheses, e.g., "one".equals("two").
True or False. The following code snippet will print true. String str1 = "one"; String str2 = "two"; System.out.println( str1.equals(str1=str2) );
False. Note, if the start and end parameters passed to the delete method of the StringBuilder class are the same, no change is made.
True or False. The following code will delete the character at index position 3 in StringBuilder sb (assume no compile-time errors or exceptions are thrown). sb.delete(3, 3);
True. When either operand of the '+' operator is a String, it acts like concat. Note, however, that if one of the operands is a String and the other is not, it actually first AutoBoxes the non-String operand and then calls toString(), here "a".concat(new Character('b').toString())
True or False. The following code will print "ab": String a = "a"; char b = 'b'; System.out.print(a + b);
False. When both operands of an arithmetic operator are char, they are first converted to ints representing their ASCII value, in this case 98 and 97, so the output would 195.
True or False. The following code will print "ab": char a = 'a'; char b = 'b'; System.out.print(a + b);
False. Even though there are only 6 index positions in the String, the substring( ) method's second paramater, toIndex, is the equivalent of "stop at". In other words, the JVM will not attempt to access that index position, so as long at the argument passed to this parameter is no greater than the length of the String, it is allowed.
True or False. The following code will throw a StringIndexOutOfBoundsException: String s = "0123456"; s.substring(0, 7);
True
True or False. The following method will compile and run without any problems. public void switchTest(byte x){ switch(x){ case 'b': // 1 default : // 2 case -2: // 3 case 80: // 4 } }
True
True or False. The package statement is optional in a class.
True
True or False. The str.trim( ) method will remove tab, newline, and carriage return characters from the beginning and end of String.
False. The ! operator inverts a boolean value, it is not possible to negate (an arithmetic operation) a boolean value.
True or False. To negate a boolean value, you use the ! operator.
True
True or False. Two String objects, x and y, are both assigned the string literal value "one". x == y and x.equals(y).
False. Variabls defined in interfaces are constants by default.
True or False. Variables defined in interfaces can be changed by classes that implement them.
False. Only the direct superclass is initalized (i.e., the class that was extended, not classes that were implemented).
True or False. When a class is initialized, any interfaces implemented by that class are first initialized.
False
True or False. When declaring a method, the access modifer may be specified after the return type.
False. The optional specifiers may be placed before or after the access modifier, but not after the return type.
True or False. When declaring a method, the optional specifiers abstract, final, or static must be specified after the access modifier, if an access modifier is present.
True
True or False. When declaring a method, the optional specifiers abstract, final, or static must be specified before the return type.
False. The child method may not throw an exception that is new or broader.
True or False. When overriding a method, the method in the child class may not throw a checked exception that is new or more specific than the class of any exception thrown in the parent class method.
True. However, this is the old way. The new way, using LocalDate objects and the LocalDate.now( ) static method is preferred.
True or False. You can create a new Date object by calling the LocalDate constructor, e.g., Date d = new Date();.
False. The java date and time classes have private constructors. Instead, you must use the Static methods provided by thoses classes to create date/time objects. Note, attempting to do this will throw a compile-time error.
True or False. You can create a new LocalDate object by calling the LocalDate constructor, e.g., LocalDate d = new LocalDate();.
False. You may only have one vararg parameter.
True or False. You may have multiple varargs parameters, as long as they are specified at the end of the parameter list.
True
True or False. You must specify a size for a single dimension array that is not initialized with content.
False. You must only specify a size for the first dimension.
True or False. You must specify a size for every dimension in a multi-dimension array.
False
True or False. boolean and Boolean are supported date types in switch statements.
True
True or False. byte, short, and char variables are automatically promoted to int.
True
True or False. java.lang.ClassCastException extends java.lang.RuntimeException.
False. Note, java.lang.GeneralSecurityException extends Exception, but java.lang.SecurityException extends java.lang.RuntimeException.
True or False. java.lang.GeneralSecurityException extends java.lang.RuntimeException.
False
True or False. java.lang.IOException extends java.lang.RuntimeException.
True
True or False. java.lang.IndexOutOfBoundsException extends java.lang.RuntimeException.
False
True or False. long and Long are supported date types in a switch statement.
True
True or False. str.startswith( ) and str.endswith( ) are case sensitive.
True
True or False. try block and try clause refer to same thing.
True
True or False: A Java source code file can define multiple classes and interfaces.
False: A class can include multiple import statements.
True or False: A class can have only one import statement.
True
True or False: A class from a default package can't be used in any named packaged class, regardless of whether it's defined within the same directory or not.
True
True or False: A class may define an instance variable before or after the definition of a method and still use it.
True. However, a compile-time error will result if the fields are referenced from that class. The qualified name must be used.
True or False: A class may inherit two fields with the same simple name.
True
True or False: A comment can appear before or after a package statement, before or after the class definition, and before, within, or after a method definition.
True
True or False: A static variable or method can be accessed using the name of a reference object variable or the name of a class.
True
True or False: A top-level class must be uniquely named within its package.
False
True or False: A variable can be defined as an abstract variable.
False, a void method does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method.
True or False: A void method cannot include a return statement.
False
True or False: A volatile variable may be final.
False
True or False: All classes and interfaces in separate packages and sub-packages are visible to each other by default.
False
True or False: An abstract class can be instantiated.
False. An abstract method doesn't have a body, which means it's implemented by the class that extends the class defining the abstract method.
True or False: An abstract method has a body.
True
True or False: An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
True
True or False: An interface is an abstract entity by default.
True
True or False: Class declarations and class definitions are components of a Java class.
True
True or False: Class methods can access class variables and class methods directly.
True
True or False: Classes and interfaces defined using the public access modifier are accessible to related and unrelated classes outside the package in which they're defined.
True
True or False: Comments can include any characters including characters from the Unicode charset.
True
True or False: Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable.
True
True or False: Identifi ers may contain letters, numbers, $, or _.
True
True or False: In a lambda expressions, you can omit the parentheses if there is only one parameter.
True
True or False: Instance methods can access instance variables and instance methods directly.
False
True or False: Instance methods cannot access class variables and class methods directly.
True
True or False: It is a compile-time error if the same keyword appears more than once as a modifier for a class declaration.
True
True or False: Members defined in the same directory have access to the members of a default package?
True. As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
True or False: Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
True
True or False: Only classes inside the same package. (Package) can access members of a class with default access.
False. RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
True or False: Runtime Exceptions must be handled or declared to be thrown.
False. Static initialization blocks are executed once, when the class is loaded. Initializer blocks (also known as Instance Initialization Blocks) are executed whenever the class constructor is called (instance is created).
True or False: Static initialization blocks are executed after initializer blocks.
False
True or False: Static methods can access instance variables and instance methods directly.
False. A static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
True or False: Static nested classes have access to other members of the enclosing class.
False
True or False: The Enum class can be subclassed.
False. The JVM loads classes when they are referenced in executing code.
True or False: The JVM loads every class in an application once when the application starts.
True
True or False: The abstract keyword, when prefixed to the definition of a concrete class, can change it to an abstract class, even if it doesn't define any abstract methods.
True
True or False: The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions.
False
True or False: The execution statements that follow a case statement in a switch statement must be enclosed in curly braces { }.
False. You cannot numerically negate a boolean value. You need to use the logical inverse operator (!).
True or False: The following statement will compile: boolean y = -true;
True. You cannot take the logical complement of a numeric value, nor can you assign an integer to a boolean variable.
True or False: The following statement will not compile: boolean z = !0;
True
True or False: The import statement can't be used to import multiple classes or interfaces with the same name.
True
True or False: The import statement uses simple names of classes and interfaces from within the class.
False: The keyword java and the name of the class aren't passed on as command parameters to the main method.
True or False: The keyword java and the name of the class are passed on as command parameters to the main method.
False
True or False: The order of the definition of instance variables, constructors, and methods matters in a class.
False
True or False: The package statement can appear within a class declaration or after the class declaration.
True
True or False: The positions of static and public can be interchanged, and the method parameter can use any valid name.
True: You can import either a single member or all members of a package using the import statement.
True or False: You can import a single member of a package with an import statement.
False: You cannot import classes from a sub-package by using the wildcard character, an asterisk (*), in the import statement.
True or False: You can import classes from a sub-package by using the wildcard character, an asterisk (*), in the import statement.
True
True or False: You cannot use the import statement to access multiple classes or interfaces with the same names from different packages.
False. All enums implicitly extend java.lang.Enum. Because a class can only extend one parent, the Java language does not support multiple inheritance of state, and therefore an enum cannot extend anything else.
True or False: an Enum type can be a subclass of java.lang.String.
overloaded
Two methods with the same name but different number and/or types of parameters are referred to as __________________ methods.
switch
Unlike if-then and if-then-else statements, the _____________ statement can have a number of possible execution paths.
compile-time constants. Note, these are replaced throughout the code with their actual value. If changes to the value are desired, the code must be re-compiled.
Variables of primitive or string data type declared static and final are known as _________________-___________ _____________________.
zero, null
Variables that represent fields in a class are automatically initialized to their corresponding "_______" or ________ value during object instantiation.
length, size( ). Note, the former is a field, the latter is a method.
We use Array.______________ to determine the number of elements in an array, and ArrayList._____________ to determine the number of elements in an ArrayList.
Public, Protected, Default, Private
What are the 4 Java Access Modifiers?
B, D, E. length() is simply a count of the number of characters in a String. In this case, there are six characters. charAt() returns the character at that index. Remember that indexes are zero based, which means that index 3 corresponds to d and index 6 corresponds to 1 past the end of the array. A StringIndexOutOfBoundsException is thrown for the last line.
What are the results of the code? (choose all that apply) A. 5 B. 6 C. c D. d E. An exception is thrown. F. The code does not compile.
A, D. Note, A is correct because the test( ) method of Predicate returns a boolean. So all you need for your body part in your lambda expression is an expression that returns a boolean. isEmpty() is a valid method of ArrayList, which returns true if there are no elements in the list. Therefore, al.isEmpty() constitutes a valid body for the lambda expression in this case. D is correct because the add( ) method of ArrayList returns a boolean. Further, it returns true if the list is altered because of the call to add. In this case, al.add("hello") indeed alters the list because a new element is added to the list.
What can be inserted in the code below so that it will print true when run (choose two)? A. checkList(new ArrayList(), al -> al.isEmpty()); B. checkList(new ArrayList(), ArrayList al -> al.isEmpty()); C. checkList(new ArrayList(), al -> return al.size() == 0); D. checkList(new ArrayList(), al -> al.add("hello")); E. checkList(new ArrayList(), (ArrayList al) -> al.isEmpty());
A, B, D. The value x + y is automatically promoted to int, so int and data types that can be promoted automatically from int will work. Options A, B, D are such data types. Option C will not work because boolean is not a numeric data type. Options E and F will not work without an explicit cast to a smaller data type.
What data type (or types) will allow the following code snippet to compile? (Choose all that apply) byte x = 5; byte y = 10; _____ z = x + y; A. int B. long C. boolean D. double E. short F. byte
//
What do end-of-line comments start with?
"/* */"
What do multi-line comments start and end with?
packages
What do you use to group together a related set of classes and interfaces?
A. While the code on line 3 does compile, it is not a constructor because it has a return type. It is a method that happens to have the same name as the class. When the code runs, the default constructor is called and count has the default value (0) for an int.
What does the code output? A. 0 B. 4 C. Compilation fails on line 3. D. Compilation fails on line 4. E. Compilation fails on line 7. F. Compilation fails on line 8.
java.lang.ClassCastException
What exception/error would the following code throw? Object s = "asdf"; StringBuffer sb = (StringBuffer) s;
java.lang.AssertionError. Note, this error is thrown to indicate when an assert statement's boolean test expression returns false.
What exception/error would the following code throw? assert (false) ;
java.lang.ArithmethicException
What exception/error would the following code throw? int k = 10/0;
java.lang.ArrayIndexOutOfBoundsException
What exception/error would the following code throw? int[ ] ia = new int[ ]{ 1, 2, 3}; System.out.println(ia[3]);
java.lang.ExceptionInInitializerError. Note, this error is thrown whenever an exception is thrown when initializing a static variable or a static block.
What exception/error would the following code throw? public class X { static int k = 0; static { k = 10/0; } }
java.lang.StackOverflowError. Note, this error is thrown when the stack is full. Usually thrown when a method calls itself and there is no boundary condition.
What exception/error would the following code throw? public void m1(int k){ m1(k++); }
-3. The number isn't found but would be inserted at index 2 to preserve sort order. Remember that we negate that number and subtract 1 to get the answer.
What is returned by the following search? int[] numbers = {2,4,6,8}; Arrays.binarySearch(numbers, 5)
PS, CS, PIC, CIC
What is the acronym for order of initialization?
DateTimeFormatter
What is the class used for formatting a date?
double. In this case, we must apply all of the rules. First, x will automatically be promoted to int solely because it is a short and it is being used in an arithmetic binary operation. The promoted x value will then be automatically promoted to a float so that it can be multiplied with y. The result of x * y will then be automatically promoted to a double, so that it can be multiplied with z, resulting in a double value.
What is the data type of x * y / z? short x = 14; float y = 13; double z = 30;
long. If we follow the first rule, since one of the values is long and the other is int, and long is larger than int, then the int value is promoted to a long, and the resulting value is long.
What is the data type of x * y? int x = 1; long y = 33;
Code does not compile. This is actually a trick question, as this code will not compile! Floating-point literals are assumed to be double, unless postfixed with an f, as in 2.1f. If the value was set properly to 2.1f, both operands would be promoted to a double, and the result would be a double value.
What is the data type of x + y? double x = 39.21; float y = 2.1;
int. In this case, we must apply the third rule, namely that x and y will both be promoted to int before the operation, resulting in an output of type int. Pay close attention to the fact that the resulting output is not a short.
What is the data type of x / y? short x = 10; short y = 3;
The super() command calls the constructor of the parent class and is used in the first line of every child constructor, whereas super is a keyword used to reference a member of the parent class.
What is the difference between super() and super?
.java
What is the extension for a java source file?
E. Note, java.lang is automatically imported and classes in the same the package do not have to import one another.
What is the maximum number of imports that can be removed and have the code still compile? A. 0 B. 1 C. 2 D. 3 E. 4 F. Does Not Compile
F. In this example, the ternary operator has two expressions, one of them a String and the other a boolean value. The ternary operator is permitted to have expressions that don't have matching types, but the key here is the assignment to the String reference. The compiler knows how to assign the first expression value as a String, but the second boolean expression cannot be set as a String; therefore, this line will not compile.
What is the output of the application? A. Greater than,10 B. false,10 C. Greater than,11 D. false,11 E. The code will not compile because of line 4. F. The code will not compile because of line 5.
A. The expression on line 5 is true when row * col is an even number. On the first iteration, row = 1 and col = 1, so the expression on line 6 is false, the continue is skipped, and count is incremented to 1. On the second iteration, row = 1 and col = 2, so the expression on line 6 is true and the continue ends the outer loop with count still at 1. On the third iteration, row = 2 and col = 1, so the expression on line 6 is true and the continue ends the outer loop with count still at 1. On the fourth iteration, row = 3 and col = 1, so the expression on line 6 is false, the continue is skipped, and count is incremented to 2. Finally, on the fifth and final iteration, row = 3 and col = 2, so the expression on line 6 is true and the continue ends the outer loop with count still at 2. The result of 2 is displayed, so the answer is option B.
What is the output of the code snippet? A. 1 B. 2 C. 3 D. 4 E. 6 F. The code will not compile because of line 6.
D. The code compiles without issue, so option F is incorrect. After the first execution of the loop, i is decremented to 9 and result to 13. Since i is not 8, keepGoing is false, and the loop continues. On the next iteration, i is decremented to 8 and result to 11. On the second execution, i does equal 8, so keepGoing is set to false. At the conclusion of the loop, the loop terminates since keepGoing is no longer true. The value of result is 11, and the correct answer is option D.
What is the output of the code snippet? A. 7 B. 9 C. 10 D. 11 E. 15 F. The code will not compile because of line 8.
2020-01-20. Note, calling plusDays( ) has no effect here as we don't store the return value anywhere and the LocalDate object referenced by d is immutable.
What is the output of the following code? LocalDate d = LocalDate.of(2020,1, 20); d.plusDays(10); System.out.println(d);
D. You cannot call date/time methods on date/time Objects that do not contain the relevant date parts for those methods (i.e., plusHours cannot be called on a LocalDate object because the LocalDate object only contains the year, month, and day).
What is the output of the following code? LocalDate d = LocalDate.of(2020,1, 20); date = d.plusHours(24); System.out.println(d); A. 2020-01-20 B. 2020-01-21 C. DateTimeException is thrown. D. Does not compile.
B. Code executes as follows: 1. x is set to 20 2. x is greater than 0, so x enters the do-while, is reduced by 2 until it reaches 4 and is no longer greater than 5. 3. x is decremented by 1 to 3. 4. '3' is printed. 5. x is still greater than 1, so the top-level while loop iterates again. 6. x enters the do-while loop and decremented by 2 to 1. 7. x is not greater than 5, so do-while loop exits. 8. x is decremented by 1 to 0. 9. '0' is printed.
What is the output? A.420 B.30 C.52-1 D.An infinite loop E.Compilation fails
G. G. Line 5 does not compile. This question is checking to see if you are paying attention to the types. numFish is an int and 1 is an int. Therefore, we use numeric addition and get 5. The problem is that we can't store an int in a String variable. Supposing line 5 said String anotherFish = numFish +1 + "";. In that case, the answer would be options A and D. The variable defined on line 5 would be the string "5", and both output statements would use concatenation.
What is the output? (choose all that apply) A. 4 1 B. 41 C. 5 D. 5 tuna E. 5tuna F. 51tuna G. The code does not compile.
A, D. Note, First, main calls override(), override() initializes the local variable str to "World", then override moves into the try and calls overridden(). Overriden intializes its own local variable str to "Hello", then calls throwIO( ). throwIO() immediately throws an IOException and stops exception. That IOException is passed back up to overridden(), which in turn passes it back to override(). Override() stops executing its try clause and catches the IOException in the first catch clause. The first catch exception handler prints B, then the execution of the try-catch terminates and the local variable str from override is returned to main(). main() prints World. The local variable str belonging to overridden is never returned, the IOException thrown in the try is never reached, and the second exception handler is never executed.
What is the printed by the code? (choose all that apply) A. A B. B C. Hello D. World D. Exactly one IOException stacktrace E. Exactly two IOException stacktraces F. Uncaught exception stacktrace. G. Does not compile.
Autoboxing
What is the process called when Java automatically converts an int to an Integer?
fiddlers12
What is the result of "fiddlers" + 1 + 2?
3fiddlers
What is the result of 1 + 2 + fiddlers?
A. Note, the boolean operator (!=) has a higher precedence than the assignment operator (=). So, in the if-statement, b2 != b1 is evaluated first, making the statement false = !b2. This is invalid because false is a value, not a variable, and thus cannot be assigned a value. Note also that this error is known at compile-time because the compiler knows that it will evaluate the if-statement as described above and will therefore be first resolving the boolean expression to a boolean value, then attempting to assign a value to that boolean value.
What is the result of executing the code? A. It will fail to compile. B. It will print true. C. It will print false. D. Runtime exception. E. It will print nothing.
D. Prior to the first iteration, m = 9, n = 1, and x = 0. After the iteration of the first loop, m is updated to 8, n to 3, and x to the sum of the new values for m + n, 0 + 11 = 11. After the iteration of the second loop, m is updated to 7, n to 5, and x to the sum of the new values for m + n, 11 + 12 = 23. After the iteration of the third loop, m is updated to 6, n to 7, and x to the sum of the new values for m + n, 23 + 13 = 36. On the fourth iteration of the loop, m > n evaluates to false, as 6 < 7 is not true. The loop ends and the most recent value of x, 36, is output, so the correct answer is option D.
What is the result of the code snippet? A. 11 B. 13 C. 23 D. 36 E. 50 F. The code will not compile because of line 7.
C. This question is trying to see if you know that String objects are immutable. Line 4 returns "PURR" but the result is ignored and not stored in s. Line 5 returns "purr" since there is no whitespace present but the result is again ignored. Line 6 returns "ur" because it starts with index 1 and ends before index 3 using zero-based indexes. The result is ignored again. Finally, on line 6 something happens. We concatenate four new characters to s and now have a String of length 8.
What is the result of the code? A. 2 B. 4 C. 8 D. 10 E. An exception is thrown. F. The code does not compile.
ArrayStoreException
What is the result of the following code: List<String> list = new ArrayList<>(); list.add("one"); list.add("two"); Integer[ ] intArr = list.toArray(new Integer[0]); for (Integer i: intArr) {System.out.print(i);}
1234. Note, the first parameter of the StringBuilder delete method is inclusive and the second parameter is exclusive. The same is true for the StringBuilder replace method.
What is the result of the following code? StringBuilder sb = new StringBuilder("01234"); sb.delete(0,1);
E. Line 6 adds 1 to total because substring() includes the starting index but not the ending index. Line 7 adds 0 to total. Line 8 is a problem: Java does not allow the indexes to be specified in reverse order and the code throws a StringIndexOutOfBoundsException.
What is the result? A. 1 B. 2 C. 3 D. 7 E. An exception is thrown F. The code does not compile.
D. Note, even though binarySearch( ) will return 2 (Option A) every time because the element is present in the array, the javaDoc for Arrays.list( ) states "The array must be sorted (as by the sort(byte[]) method) prior to making this call. If it is not sorted, the results are undefined", so the correct answer is D.
What is the result? A. 2 B. 4 C. 6 D. The result is undefined. E. An exception is thrown. F. The code does not compile.
B. The first if statement is false because the variables do not point to the same object. The second if statement is true because ArrayList implements equality to mean the same elements in the same order.
What is the result? A. A B. B C. C D. An exception is thrown. E. The code does not compile.
C. Note, m1( ) throws an exception. However, there is no catch, so main ( ) throws the exception up to the caller, meaning neither "A" nor "C" prints are executed. However, because the finally block is always executed, "B" prints, then the exception is thrown.
What letters, and in what order, will be printed? A. It will print C and B, in that order. B. It will print A and B, in that order. C. It will print B and throw exception. D. It will print A, B, and C in that order. E. Compile-time error.
B. All interface methods are implicitly public, so option B is correct and option A is not. Interface methods may be declared as static or default but are never implicitly added, so options C and F are incorrect. Option D is incorrect—void is not a modifier; it is a return type. Option E is a tricky one, because prior to Java 8 all interface methods would be assumed to be abstract. Since Java 8 now includes default and static methods and they are never abstract, you cannot assume the abstract modifier will be implicitly applied to all methods by the compiler.
What modifiers are implicitly applied to all interface methods? (Choose all that apply) A. protected B. public C. static D. void E. abstract F. default
A, C, G
What of the following modifiers may be applied to fields in interfaces? A. public B. protected C. static D. private E. abstract F. default G. final
double
What type will the 'z' variable be? double w = 1d; float x = 2F; long y = 3L; z = w + x + y;
float
What type will the 'z' variable be? float x = 1F; long y = 2L; z = x + y;
long
What type will the 'z' variable be? int x = 1; long y = 2L; z = x + y;
C. Note, Class A's constructor has no access modifier, meaning it is package-private. Therefore, Class B, in a different package, will not have access to it and so can neither extend nor instantiate it.
What will be printed when you try to compile and run class B? A. It will print A. B. It will print B. C. It will not compile. D. It will compile but not run. E. None of the above.
E. Note, compilation fails because an attempt is made to access a non-static field ( j ) from a static context ( calc ). Also note that it is valid to pass the char argument ( c ) to calc due to automatic type conversion.
What will be the ouput? A. 97 B. a C. A D. Compilation fails due to error at line 6. E. Compilation fails due to error at line 10.
D. Note, The first two outputs are true because String [ ] is an object and the Object class equals( ) method is equivalent to ==, meaning that it simply checks to see if two operands hold references to the same object. The third output is false because specifying the new keyword explicity tells the JVM to create a new object on the heap, rather than using the same reference (e.g., String bug4 = bug3) or the string pool (e.g., String bug4 = "bug"). The fourth output is true because the equals( ) method is being called from an Object of type String and the String implementation of equals checks to see if the content of two Strings is the same.
What will be the output of the code? A. true true true true B. true false true true C. false false true true D. true true false true E. The code will not compile.
D. Note, because h is a primitive, the JVM will attempt to unbox the Integer wrapped element from the List. Attempts to unbox a null reference will throw a NullPointerException.
What will be the output of the following code: List<Integer> heights = new ArrayList<>(); heights.add(null); int h = heights.get(0); System.out.println(h); A. 0 B. null C. The code will fail to compile. D. NullPointerException
D. Note, Arrays.binarysearch( ) requires a sorted array, otherwise the output is unpredictable.
What will be the output of the following code: int[ ] numbers = {2,7,6,1,10}; System.out.print(numbers.binarySearch(9)); A. -1 B. 1 C. -5 D. The output is unpredictable. E. The code will not compile.
A. Note that Answer B is incorrect because the cast on Line 4 is valid. It is valid to cast obj, which has type Double to Number because Double extends Number.
What will be the output of the program? A.3.0 B.ClassCastException C.IllegalArgumentException D.NumberFormatException E.Compilation fails
C. String[ ][ ] can not be case to Comparable which is necessary for the Arrays.sort() call.
What will be the output of this program code? A. ACDLSZ B. ZSLDCA C. A ClassCastException is thrown. D. An ArrayIndexOutOfBoundsException is thrown. E. Compilation fails.
A. Note that the code on Line 7 does not execute because it is an initialization block (lacking the static keyword) and is typically used in a class to initialize variables and is used in conjunction with a constructor. The code on Line 9 does execute because it is a static initialization block and it executes once, on class load.
What will be the output of this program? A. Static Main B. Whiz Static Main C. Whiz Main D. Main E. Compilation fails.
D
What will be the output? A.33 B.312 C.1212 D.123 E.Compilation fails
B. Note, the variables are initialized first in the for-loop to 0, then the for-loop terminates because the first test fails, then print.
What will be the output? A. 0 0 will be printed twice. B. 0 0 will be printed once. C. It will keep on printing 0 0. D. It will not compile. E. It will print 0 0 and then 0 1.
C. Note, the static initialization block can only initialize static fields. Alternatively, an instance initialization block might be used to initialize x, but then psvm would not be able to access it because non-static fields cannot be access from static contexts.
What will be the output? A. 2 B. 0 C. Compilation fails due to an error at line 3. D. Compilation fails due to an error at line 11. E. Compilation fails due to multiple errors.
B. Note, the Animal class provides its own implementation of the getSpeed( ) method and the JVM selects the most specific implementation.
What will be the output? A. 5 B. 6 C. 10 D. Compilation fails due to an error at line 13. E. Compilation fails due to multiple errors.
B. The JVM first converts the octal 013 to decimal, 11.
What will be the output? A. Code will produce the output 1. B. Code will produce the output 2. C. Compilation fails due to an error at line 2. D. Compilation fails due to an error at line 7. E. Compilation fails due to multiple errors.
D. Note, Class A is package private.
What will be the output? A. Compilation succeeds. B. Compilation fails due to error at line 5 of class B C. Compilation fails due to error at line 7 of class B D. Both B and C
C. Read JLS 15.11.1
What will be the output? A. It will fail to compile. B. A ClassCastException will be thrown. C. It will print 30, 20. D. It will print 30, 30. E. It will print 10, 20.
C. Note, because the for loop tests for i <= numbers.length, the last iteration attempts to access numbers[10] which does not exist in an array that is 10 elements in length (index 0 to 9).
What will be the output? A. It will not compile. B. It will print the numbers 0 thru 9. C. It will throw an ArrayIndexOutOfBoundsException.
C. The logical operators at //2 and //4 do not evaluate the right operand because they are short-circuited and therefore do not increment i.
What will be the output? A. It will print 0. B. It will print 1. C. It will print 2. D. It will print 3. E. It will fail to compile.
D. Note, the delete method of the StringBuilder class removes the character substring starting at the index position specified by the first argument (inclusive) and ending with the character at the index position specified by the second argument - 1, so in the case it removes the single character at index position 3 (i.e., '4').
What will be the output? A. The code will fail to compile. B. "1234" C. A StringIndexOutOfBoundsException will be thrown. D. "123" E. None of the above.
C
What will be the output? A. The code will not compile because unlike in c++, operator '=' cannot be chained i.e. a = b = c = d is invalid. B. The code will not compile as 'j' is being used before getting initialized. C. The code will compile correctly and will display '9' when run. D. The code will not compile as 'j' and 'i' are being used before getting initialized. E. All the variables will get a value of 9.
A. Note, whenever the the loop iterates on "b", it terminates the iteration (not the entire loop) at the first if-statement, then reiterates. Note, this also means that the break is never reached.
What will be the output? A. a a again c c again B. a a again b A. a a again b b again A. c c again
A. The first call is a String and finds a direct match. There's no reason to use the Object version when there is a nice String parameter list just waiting to be called. The second call looks for an int parameter list. When it doesn't find one, it autoboxes to Integer. Since it still doesn't find a match, it goes to the Object one.
What will be the output? A. string object B. object C. string D. object string E. The code does not compile.
D. Note, the only Character class constructor take a single char argument. Further this constructor has been deprecated and it is suggested to use the static factory Character.valueOf( ), which returns a Character instance, instead.
What will be the output? A. true B. false C. An Exception is thrown. D. Compilation fails due to error at line 3. E. Compilation fails due to error at line 4.
E. Note, because the if- statement on Line 7 does not use braces { } for its execution block, only the statement that immediately follows it will is attached to the if-statement. The else statement, on Line 10 is therefore not attached to an if-statement, resulting in a compile time error.
What will be the output? A.>6 or B.<6 C.or <6 D.No output. E.Compilation fails
E. The code fails at Line 11, the first time the variable x is accessed within the switch. This is because the value of the expression inside the switch statement must be known at compile-time, that is, before the code executes. Because x is first initialized, but not assigned, its value is unknown at compile-time.
What will be the output? A.ABdefault B.default C.defaultC D.C E.Compilation fails
D. The sound() method cannot be called by the 'dog' object because 'dog' is an Animal object and even though Animal is a parent of Dog, Parent classes cannot call Child methods (unless it is typecast), only the reverse is true.
What will be the output? A.Bark Dog runs B.Bark Animal runs C.Compilation fails due to an error at line 9. D.Compilation fails due to an error at line 20. E.Compilation fails due to multiple errors.
C. Person p1 = new Manager(); first loads the Person and Manager classes. As the classes are loading, the Person static initialization block executes, printing "SP". If the Manager class had a static initialization block, it would execute next. Then, the JVM begins to execute the statement. Person p1 declares the p1 Person object reference (Note: this does not initialize or instantiate it). Then, the JVM moves to the right operand where it instantiates a new Manager instance. Because Manager is a child of Person, the JVM first calls the default super constructor of Person, printing "CP" (Note, if an instance initialization block were present in Person, it would also be executed, prior to the constuctor, at this time). Next, the instance initialization block in Manager is executed, printing "IT", and finally the Manager constructor is executed, printing "CT".
What will be the output? A.SP IT CP CT B.CP CP IT SP C.SP CP IT CT D.SP CP IT CT SP E.Compilation fails
D. In case of overriding, the return type of the overriding method must match exactly to the return type of the overridden method if the return type is a primitive. (In case of objects, the return type of the overriding method may be a subclass of the return type of the overridden method.)
What will be the result of compiling and executing the code? A. It will print 1. B. It will print 2. C. Compile-time error at //1. D. Compile-time error at //2 E. Compile-time error at //3.
A, D. If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at runtime, but only after all parts of the array reference expression have been evaluated and only if these evaluations completed normally. This means, first index = 2 will be executed, which assigns 2 to index. After that null[2] is executed, which throws a NullPointerException. But this exception is caught by the catch block, which prints nothing. So it seems like NullPointerException is not thrown but it actually is. In other words, the embedded assignment of 2 to index occurs before the check for array reference produced by getArray(). In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated. Note that if evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated.
What will be the result of compiling and running the code (choose all that apply)? A. It will print "index=2". B. It will print "Index=1". C. It will fail to compile. D. It will throw a NullPointerException.
B. Note, typically an overriding method in a subclass must have the same return type as the overriden method in the superclass; however, this is a covariant return type (since 1.5), and is allowed because the overriding return type is a subclass of the overridden return type.
What will be the result of the code? A. It will print the hash code of the object. B. It will prent hello. C. Compile time error at Line 1. D. Compile time error at Line 2. E. Compile time error at Line 3.
E. Passing an argument outside the range of one the date/time Static method parameters will throw a DateTimeException. In this case, the month parameter range is 1 thru 12.
What will be the result of the following code: LocalDate d = LocalDate.of(2020,13,25); System.out.print(Month.from(d)); A. 13 B. 12 C. December D. Code does not compile. E. DateTimeException is thrown.
C. For arithmetic operators, byte, short, and char are automatically promoted to int and the result is int. Here, even though we have a case, we are only casting a to byte, which is then automatically promoted to int. To fix this, you would need to cast the result of a + b, e.g., byte c = (byte) (a+b)
What will be the result of the following code? byte a = 0; byte b = 1; byte c = (byte) a + b; System.out.println(c); A. 1 B. 0 C. The code does not compile.
E. Method local variables are not initialized to their default values, so they should be initialized before using. However, it is not illegal to declare them without initializing. So, at line 7, trying to use an uninitialized local variable results in a compile time error.
What will be the result? A. 100 B. 10 C. 0 D. Compilation fails due to an error on line 6. E. Compilation fails due to an error on line 7.
D. Shot plus an int is an int.
What will be the result? A. 21 B. 22 C. Compilation fails due to error on line 4. D. Compilation fails due to error on line 6. E. Compilation fails due to multiple errors.
C. The subclass can redeclare a field from an interface, but it cannot re-assign it because it public static final by default.
What will be the result? A. Value: 10 B. Whiz: 10 C. Compilation fails due to an error on line 3 D. Compilation fails due to multiple errors E. An exception will be thrown at runtime
E. Note, as a rule, fields defined in an interface are public, static, and final. The methods are public.Here, the interface IInt defines thevalue and thus any class that implements this interface gets this field. Therefore, it can be accessed using s.thevalue or just thevalue inside the class. Also, since it is static, it can also be accessed using IInt.thevalue or Sample.thevalue.
What will happen when the code is compiled and run? A. It will give an error at compile time at line //1. B. It will give an error at compile time at line //2. C. It will give an error at compile time at line //3 D. It will give an error at compile time at line //4. E. It will compile and run without any problem.
D. When the program is run, the JVM looks for a method named main() which takes an array of Strings as input and returns nothing (i.e. the return type is void).But in this case, it doesn't find such a method ( the given main() method is returning long!).
What will the code print when run? A. Hello B. It will not print anything. C. It will not compile. D. It will throw an Error at runtime. E. None of the above.
"". Note, Strings are immutable so while the calls to concat( ) do return new Strings, they do not modify the original String variable.
What will the code print?
C. Note, getClass is a public instance method in Object class. That means it is polymorphic. In other words, this method is bound at run time and so it returns the name of the class of the actual object to which the reference points. Here, at run time, both - a and aa, point to an object of class AA. So both will print AA.
What will the code print? A. It will not compile. B. It will throw a ClassCaseException. C. a == class AA aa == class AA D. a == class A aa == class AA
"12". Note, Strings are immutable. This means that the thrid line here returns a new String without modifying the original string.
What will the following code print? String s1 = "1"; String s2 = s1.concat("2"); s2.concat("3"); System.out.println(s2);
3c
What will the following code print? System.out.println(1 + 2 + "c");
C. Note, the intValue( ) method is not available in Object. Because the dot (.) operator has precedence over the cast operator, the compiler wants to check t for the intvalue( ) method, however, at compile-time, the compiler doesn't have access to instances, so it checks the reference class, Object, not the object class, Integer.
What will the following code snippet print? Object t = new Integer(107); int k = (Integer) t.intValue()/9; System.out.println(k); A. 11 B. 12 C. It will not compile. D. It will throw an exception at runtime.
B. Note, the StringBuilder class is mutable, meaning the object itself can be changed. Further, most of the mutation methods of StringBuilder return a reference to the mutated StringBuilder object. Here, sb and sc are references to the same object and therefore have the same hashcode.
What will the output of the code be? A. false B. true C. start middle end D. The code will not compile.
E. NullPointerException is thrown because the concat( ) method calls the length ( ) method on a null object.
What would be the output? A. null 0 null 1 B. 0 1 C. 0 1 D. null null E. It will throw a RunTimeException
E. Note, F is incorrect because, even though a non-static variable is being access from a static context, it is being accessed using an object instance, which does not cause a compile error.
What would be the result? A. 12 B. 1234 C. 1235 D. 124 E. 1245 F. Line 15 causes to code not to compile. G. An uncaught exception is thrown.
B. Note, Having ambiguous fields or methods does not cause any problem by itself (except in the case of default methods) but referring to such fields or methods in an ambiguous way will cause a compile time error. Having m1() in T3 is also fine because even though m1() is declared in T2 as well as T3 , the definition to both resolves unambiguously to only one m1(). Explicit cast is not required for calling the method m1() : ( ( T2) t).m1();m1(int x) is valid because it is a totally independent method declared by T3.
What, if anything, is wrong with this code? A. T3 cannot implement both T1 and T2 because it leads to ambiguity. B. There is nothing wrong with the code. C. The code will work fine only if VALUE is removed from T2 interface. D. The code will work fine only if m1() is removed from either T2 or T3. E. None of the above.
C
When are you required to use a finally block in a regular try statement (not a try-with-resources)? A. Never. B. When the program code doesn't terminate on its own. C. When there are no catch blocks in a try statement. D. When there is exactly one catch block in a try statement. E. When there are two or more catch blocks in a try statement.
StringIndexOutOfBoundsException, ArrayIndexOutOfBoundsException, IndexOutOfBoundsException.
When attempting to access an invalid index position, the StringBuilder class throws a _________________________________ , the Array class throws an __________________________________, and the ArrayList class throws an ___________________________________.
E, Object
When typing an array, ________ is used by convention in generics to mean "any class that this array can hold." If you don't specify a type, it refers to the _____________ class.
after
Where do import statements go in relation to package statements in the class definition?
Public
Which access modifier is the least restrictive?
B, C, E. Immutable means the state of an object cannot change once it is created. Immutable objects can be garbage collected just like mutable objects. String is immutable. StringBuilder can be mutated with methods like append(). Although StringBuffer isn't on the exam, you should know about it anyway in case older questions haven't been removed.
Which are true statements? (Choose all that apply) A. An immutable object can be modified. B. An immutable object cannot be modified. C. An immutable object can be garbage collected. D. An immutable object cannot be garbage collected. E. String is immutable. F. StringBuffer is immutable. G. StringBuilder is immutable.
A, B, C, D
Which following types of members may an interface include? (choose all that apply) A. abstract methods B. default methods C. static methods D. static final variables E. non-static methods
C, D. Note, because the remove( ) method interprets an int passed as an argument as an index position, we can instead use the version of the method that searches for a passed-in Object argument, in this case Integer. Option A would actually remove 2 from the ArrayList, as would option E (remember the parse methods return a primitive), and note that option B calls the remove( ) method on a variable (number, singular) that has not been declared.
Which line of code, inserted at //1, will remove 1 from the list (choose all that apply): List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); //1 System.out.println(numbers); A. numbers.remove(1); B. number.remove(0) C. numbers.remove(new Integer(1)); D. numbers.remove(Integer.valueOf(1)); E. numbers.remove(Integer.parseInt(1)); F. None of the above.
Private
Which modifier is the most restrictive modifier?
A, D
Which of the following Java operators can be applied to boolean variables (choose all that apply): A. == B. + C. -- D. ! E. % F. <=
A, D. Option A is the equality operator and can be used on numeric primitives, boolean values, and object references. Options B and C are both arithmetic operators and cannot be applied to a boolean value. Option D is the logical complement operator and is used exclusively with boolean values. Option E is the modulus operator, which can only be used with numeric primitives. Finally, option F is a relational operator that compares the values of two numbers.
Which of the following Java operators can be used with boolean variables? (Choose all that apply) A. == B. + C. -- D. ! E. % F. <=
A, B, D, G, H. Note, charAt returns a char, and substring and toString both return a String.
Which of the following StringBuilder methods mutates the StringBuilder object? A. insert B. delete C. charAt D. append E. substring F. toString G. reverse H. replace
E. Option E is the canonical main() method signature. You need to memorize it. Option A is incorrect because the main() method must be public. Options B and F are incorrect because the main() method must have a void return type. Option C is incorrect because the main() method must be static. Option D is incorrect because the main() method must be named main.
Which of the following are legal entry point methods that can be run from the command line? (Choose all that apply) A. private static void main(String[] args) B. public static final main(String[] args) C. public void main(String[] args) D. public static void test(String[] args) E. public static void main(String[] args) F. public static main(String[] args) G. None of the above.
A, C, D. Remember, E is incorrect because the t is an explicitly created, new object.
Which of the following are output by this code? (choose all that apply) A. one B. two C. three D. four E. five F. The code does not compile.
A, D, E, G, H, I
Which of the following are supported data types in a swithc statement? (choose all that apply) A. byte and Byte B. boolean and Boolean C. float and Float D. short and Short E. char and Character F. double and Double G. int and Integer H. String I. enum values
B,E
Which of the following are true in reference to the Java 'garbage collector'? (choose 2) A. Java applications never run out of memory as GC manages the memory? B. An object is eligible for GC when there is no reference to it. C. The purpose of the GC is to delete objects that have no use at the moment? D. When you request GC to run, it will run immediately. E. The Object class has a finalize() method that runs the GC.
A, B, D. Lines 5 and 7 use autoboxing to convert an int to an Integer. Line 6 does not because valueOf() returns an Integer. Line 8 does not because null is not an int. The code does compile. However, when the for loop tries to unbox null into an int, it fails and throws a NullPointerException.
Which of the following are true statements about the code? (choose all that apply) A. The code compiles. B. The code throws a runtime exception. C. Exactly one of the add statements uses autoboxing. D. Exactly two of the add statements use autoboxing. E. Exactly three of the add statements use autoboxing.
B, E. C++ has operator overloading and pointers. Java made a point of not having either. Java does have references to objects, but these are pointing to an object that can move around in memory. Option B is correct because Java is platform independent. Option E is correct because Java is object oriented. While it does support some parts of functional programming, these occur within a class.
Which of the following are true statements? (Choose all that apply) A. Java allows operator overloading. B. Java code compiled on Windows can run on Linux. C. Java has pointers to specific locations in memory. D. Java is a procedural language. E. Java is an object-oriented language. F. Java is a functional programming language.
G. Option G is correct because local variables do not get assigned default values. The code fails to compile if a local variable is not explicitly initialized. If this question were about instance variables, options D and F would be correct. A boolean primitive defaults to false and a float primitive defaults to 0.0.
Which of the following are true? (Choose all that apply) A. A local variable of type boolean defaults to null. B. A local variable of type float defaults to 0. C. A local variable of type Object defaults to null. D. A local variable of type boolean defaults to false. E. A local variable of type boolean defaults to true. F. A local variable of type float defaults to 0.0. G. None of the above.
A, C, D, E. An array is not able to change size and can have multiple dimensions. Both an array and ArrayList are ordered and have indexes. Neither is immutable. The elements can change in value.
Which of the following are true? (Choose all that apply) A. An array has a fixed size. B. An ArrayList has a fixed size. C. An array allows multiple dimensions. D. An array is ordered. E. An ArrayList is ordered. F. An array is immutable. G. An ArrayList is immutable.
A, D. Options A and D are correct because boolean primitives default to false and int primitives default to 0.
Which of the following are true? (Choose all that apply) A. An instance variable of type boolean defaults to false. B. An instance variable of type boolean defaults to true. C. An instance variable of type boolean defaults to null. D. An instance variable of type int defaults to 0. E. An instance variable of type int defaults to 0.0. F. An instance variable of type int defaults to null. G. None of the above.
C, D. Option C is correct because all non-primitive values default to null. Option D is correct because float and double primitives default to 0.0. Options B and E are incorrect because int primitives default to 0.
Which of the following are true? (Choose all that apply) A. An instance variable of type double defaults to null. B. An instance variable of type int defaults to null. C. An instance variable of type String defaults to null. D. An instance variable of type double defaults to 0.0. E. An instance variable of type int defaults to 0.0. F. An instance variable of type String defaults to 0.0. G. None of the above.
A, E. Bunny is a class, which can be seen from the declaration: public class Bunny. bun is a reference to an object. main() is a method.
Which of the following are true? (Choose all that apply) A. Bunny is a class. B. bun is a class. C. main is a class. D. Bunny is a reference to an object. E. bun is a reference to an object. F. main is a reference to an object. G. None of the above.
B, D, E. Option A (line 4) compiles because short is an integral type. Option B (line 5) generates a compiler error because int is an integral type, but 5.6 is a floating-point type. Option C (line 6) compiles because it is assigned a String. Options D and E (lines 7 and 8) do not compile because short and int are primitives. Primitives do not allow methods to be called on them. Option F (line 9) compiles because length() is defined on String.
Which of the following are true? (Choose all that apply) A. Line 4 generates a compiler error. B. Line 5 generates a compiler error. C. Line 6 generates a compiler error. D. Line 7 generates a compiler error. E. Line 8 generates a compiler error. F. Line 9 generates a compiler error. G. The code compiles as is.
B, C. An array does not override equals() and so uses object equality. ArrayList does override equals() and defines it as the same elements in the same order. The compiler does not know when an index is out of bounds and thus can't give you a compiler error. The code will throw an exception at runtime, though.
Which of the following are true? (Choose all that apply) A. Two arrays with the same content are equal. B. Two ArrayLists with the same content are equal. C. If you call remove(0) using an empty ArrayList object, it will compile successfully. D. If you call remove(0) using an empty ArrayList object, it will run successfully. E. None of the above.
C, D. Java puts source code in .java files and bytecode in .class files. It does not use a .bytecode file. When running a Java program, you pass just the name of the class without the .class extension.
Which of the following are true? (Choose all that apply) A. javac compiles a .class file into a .java file. B. javac compiles a .java file into a .bytecode file. C. javac compiles a .java file into a .class file. D. Java takes the name of the class as a parameter. E. Java takes the name of the .bytecode file as a parameter. F. Java takes the name of the .class file as a parameter.
B, C. An array does not override equals() and so uses object equality. ArrayList does override equals() and defines it as the same elements in the same order. The compiler does not know when an index is out of bounds and thus can't give you a compiler error. The code will throw an exception at runtime, though.
Which of the following are true? (Choose all that apply) A. Two arrays with the same content are equal (i.e., .equals()). B. Two ArrayLists with the same content are equal (i.e., .equals()). C. If you call remove(0) using an empty ArrayList object, it will compile successfully. D. If you call remove(0) using an empty ArrayList object, it will run successfully. E. None of the above.
A, C, D, E. An array is not able to change size and can have multiple dimensions. Both an array and ArrayList are ordered and have indexes. Neither is immutable. The elements can change in value.
Which of the following are true? (Choose all that apply) A. An array has a fixed size. B. An ArrayList has a fixed size. C. An array allows multiple dimensions. D. An array is ordered. E. An ArrayList is ordered. F. An array is immutable. G. An ArrayList is immutable.
B, C, E.
Which of the following are true? (choose all that apply) A. An immutable object can be modified. B. An immutable object cannot be modified. C. An immutable object can be garbage collected. D. An immutable object cannot be garbage collected. E. String is immutable. F. StringBuffer is immutable. G. StringBuilder is immutable.
A, B, E. Option A is valid because you can use the dollar sign in identifiers. Option B is valid because you can use an underscore in identifiers. Option C is not a valid identifier because true is a Java reserved word. Option D is not valid because the dot (.) is not allowed in identifiers. Option E is valid because Java is case sensitive, so Public is not a reserved word and therefore a valid identifier. Option F is not valid because the first character is not a letter, $, or _.
Which of the following are valid Java identifiers? (Choose all that apply) A. A$B B. _helloWorld C. true D. java.lang E. Public F. 1980_s
A, B, E. Note, because answer E, 'Public', is capitalized, it is not a java keyword, and therefore there is no conflict.
Which of the following are valid java identifiers? (choose all that apply) A. A$B B. _hello C. false D. java.util E. Public F. 19_abs
C, E, F. Option C uses the variable name as if it were a type, which is clearly illegal. Options E and F don't specify any size. Although it is legal to leave out the size for later dimensions of a multidimensional array, the first one is required. Option A declares a legal 2D array. Option B declares a legal 3D array. Option D declares a legal 2D array. Remember that it is normal to see on the exam types you might not have learned. You aren't expected to know anything about them.
Which of the following array declarations is not legal? (choose all that apply) A. int[ ][ ] scores = new int[5][ ]; B. Object[ ][ ][ ] cubbies = new Object[3][0][5]; C. String beans[ ] = new beans[6]; D. java.util.Date[ ] dates[ ] = new java.util.Date[2][ ]; E. int[ ][ ] types = new int[ ]; F. int[ ][ ] java = new int[ ][ ];
A, C, D, E.
Which of the following can be inserted to make this code compile? A. System.out.println("it's ok"); B. throw new Exception(); C. throw new IllegalArgumentException(); D. throw new java.io.IOException(); E. throw new RuntimeException();
A, C, D, E. The method is allowed to throw no exceptions at all, making option A correct. It is also allowed to throw runtime exceptions, making options D and E correct. Option C is also correct since it matches the signature in the interface.
Which of the following can be inserted to make this code compile? A. public void roar(){} B. public void roar() throws Exception{} C. public void roar() throws HasSoreThroatException{} D. public void roar() throws IllegalArgumentException{} E. public void roar() throws TiredException{}
A, C. The reverse() method is the easiest way of reversing the characters in a StringBuilder; therefore, option A is correct. Option B does not reverse the string. However, substring() returns a String, which is not stored anywhere. Option C uses method chaining. First it creates the value "JavavaJ$". Then it removes the first three characters, resulting in "avaJ$". Finally, it removes the last character, resulting in "avaJ". Option D throws an exception because you cannot delete the character after the last index. Remember that deleteCharAt() uses indexes that are zero based and length() counts starting with 0.
Which of the following can replace line 4 to print "avaJ"? (choose all that apply) A. puzzle.reverse(); B. puzzle.append("vaJ$").substring(0, 4); C. puzzle.append("vaJ$").delete(0,3) .deleteCharAt(puzzle.length() - 1); D. puzzle.append("vaJ$").delete(0,3) .deleteCharAt(puzzle.length()); E. None of the above.
B. Note, the import wildcard only matches in that package directly, not subpackages.
Which of the following classes does import a.b.* actually import: (choose all that apply) A. a.A B. a.b.B C. a.b.c.C
C
Which of the following creates a Boolean wrapper of false? A. Boolean b1 = "false"; B. Boolean b2 = new Boolean("true"); C. Boolean b3 = new Boolean("T"); D. Boolean b4 = 4>3; E. None of the above.
B, C, D, G. Note, A does not compile because you cannot assign a long value to an int.
Which of the following declarations will compile (choose all that apply): A. int x = 9L; B. int x = 0b101; C. int x = 0XE; D. double x = 0XE; E. double x = 1_2_.0_0; F. int x = 1_2_; G. short y = 1; int x = y; H. None of the above.
A, B, D. java.io.IOException is thrown by many methods in the java.io package, but it is always thrown programmatically. The same is true for NumberFormatException; it is thrown programmatically by the wrapper classes of java.lang. The other three exceptions are all thrown by the JVM when the corresponding problem arises.
Which of the following exceptions are thrown by the JVM? (Choose all that apply) A. ArrayIndexOutOfBoundsException B. ExceptionInInitializerError C. java.io.IOException D. NullPointerException E. NumberFormatException
C, D
Which of the following exceptions are typically thrown by the programmer (and not the JVM)? (choose all that apply) A. ArrayIndexOutOfBoundsException B. ClassCastException C. IllegalArgumentException D. NumberFormatException
A, D, F
Which of the following generates a compile-time error (choose all that apply): A. int myNumber = 5.6; B. short myPets = 5; C. String theString = "Scruffy"; D. myPets.length(); E. theString.length(); F. myNumber.length();
D. Note, Y is accessing LOGICID through X so we do not need the static import. If Y had not done so (i.e., System.out.println(LOGICID);), then would have need the static import (i.e., import static com.foo.X.*;).
Which of the following imports, inserted at //1, will successfully execute the program: A. import static X; B. import static com.foo.*; C. import static com.foo.X.*; D. import com.foo.*; E. import com.foo.X.LOGICID;
E
Which of the following is a basic principle of object orientation? (choose all that apply) A. Abstraction B. Encapsulation C. Inheritance D. Polymorphism E. All of the above.
C. Note, Object is the a superclass to all classes, so this allowed due to covariant return types.
Which of the following is a legal return type of a method overriding the given method: public Object myMethod() {...} (Select the best option.) A. Object B. String C. Any class (not primitive). D. void E. None of the above.
E. Note, A top-level class cannot be declared Static, Protected, or Private. Further, A is incorrect because switch is java keyword.
Which of the following is a valid top level class declaration? A. class switch{ } B. public static class Test{} C. protected class Test{ } D. private class Test{ } E. None of the above.
B
Which of the following is a valid way of compiling java source file with the name "Whizlabs"? A. javac Whizlabs.class B. javac Whizlabs.java C. java Whizlabs.java D. javac Whizlabs E. java Whizlabs.class
E. Note, they are also equivalent.
Which of the following is an invalid array declaration: A. int[ ] numAnimals; B. int [ ] numAnimals2; C. int numAnimals3[ ]; D. int numAnimals4 [ ]; E. All of the above choices are valid.
D. The prefix '0B' indicates a binary numeral. A binary numeral consists of the leading ASCII characters 0b or 0B followed by one or more of the ASCII digits 0 or 1 interspersed with underscores, and can represent a positive, zero, or negative integer. 2 is not allowed.
Which of the following is not a valid int literal? A. 10 B. 1_000 C. 012 D. 0B021 E. 0X33
E, I, J. Note, E is invalid because an _ cannot be the last digit in a binary numeral. I is invalid because an int literal cannot be larger than 2^31 (i.e., 32-bits) which is approximately 2.15 billion.
Which of the following is not a valid integer literal? A. 1_000 B. 012 C. 0B01 D. 0XE E. 0B1_1_1_1_1_1_1_1_ F. 0B1_1_1_1_1_1_1_1 G. 0x00_FF__00_FF H. 0xDad I. 10000000000 J. 1L E. None of these
B. Concrete classes are, by definition, not abstract, so option A is incorrect. A concrete class must implement all inherited abstract methods, so option B is correct. Option C is incorrect; a superclass may have already implemented an inherited interface, so the concrete subclass would not need to implement the method. Concrete classes can be both final and not final, so option D is incorrect. Finally, abstract methods must be overridden by a concrete subclass, so option E is incorrect.
Which of the following is true about a concrete subclass? (Choose all that apply) A. A concrete subclass can be declared as abstract. B. A concrete subclass must implement all inherited abstract methods. C. A concrete subclass must implement all methods defined in an inherited interface. D. A concrete subclass cannot be marked as final. E. Abstract methods cannot be overridden by a concrete subclass.
A, C, D, E. Option A is correct because it is the traditional main() method signature and variables may begin with underscores. Options C and D are correct because the array operator may appear after the variable name. Option E is correct because varargs are allowed in place of an array. Option B is incorrect because variables are not allowed to begin with a digit. Option F is incorrect because the argument must be an array or varargs. Option F is a perfectly good method. However, it is not one that can be run from the command line because it has the wrong parameter type.
Which of the following legally fill in the blank so you can run the main() method from the command line? (Choose all that apply) public static void main( ____________ ) A. String[ ] _names B. String[ ] 123 C. String abc[ ] D. String _Names[ ] E. String... $n F. String names E. None of the above.
A, E. Underscores are allowed as long as they are directly between two other digits. This means options A and E are correct. Options B and C are incorrect because the underscore is adjacent to the decimal point. Option D is incorrect because the underscore is the last character.
Which of the following lines of code compile? (Choose all that apply) A. int i1 = 1_234; B. double d1 = 1_234_.0; C. double d2 = 1_234._0; D. double d3 = 1_234.0_; E. double d4 = 1_234.0; F. None of the above.
A, D, E, F. First off, options B and C are incorrect because protected and public methods may be overridden, not hidden. Option A is correct because private methods are always hidden in a subclass. Option D is also correct because static methods cannot be overridden, only hidden. Options E and F are correct because variables may only be hidden, regardless of the access modifier.
Which of the following may only be hidden and not overridden? (Choose all that apply) A. private instance methods B. protected instance methods C. public instance methods D. static methods E. public variables F. private variables
F
Which of the following occurrences causes a class or interface (named T) to be initialized: A. T is a class and an instance of T is created. B. T is a class and a static method declared by T is invoked. C. A static field declared by T is assigned. D. A static field declared by T is used and the field is not a constant variable. E. T is a top level class, and an assert statement lexically nested within T is executed. F. All of the above.
F
Which of the following represents a multidimensional array? (choose all that apply) A. int[ ][ ] vars1; B. int vars2 [ ][ ]; C. int[ ] vars3[ ]; D. int[ ] vars4 [ ], space [ ][ ]; E. int[ ][ ] vars5 = {{1, 4}, {3}, {9,8,7}}; F. All of the above.
C
Which of the following sets contains only primitive literals? A. 1, 'c', "a" B. 1, 1.5f, True C. 'BF', 10, "Sure", D. 1.2D 1f, 'c' E. None of the Above
D. D is correct because the String.equals method returns true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object, while '==' returns true if both objects point to the same memory location. Because s2 is a new instance, it holds a reference to a different memory location than s1.
Which of the following statement is true? I. String s2 = "Rekha"; II. String s2 = new String("Rekha"); A.Inserting the statement II at line 5, will produce the output as "true true" . B.Inserting the statement I at line 5, will produce the output as "true false" . C.Inserting the statement I at line 5, will produce the output as "false false" . D.Inserting the statement II at line 5, will produce the output as "true false" . E.None of the above
B
Which of the following statement is true? A. Java applications never run out of memory as GC manages the memory. B. An object is eligible for GC when there is no reference to that object. C. The purpose of GC is to delete objects that are of no use at the moment. D. When you request GC to run, it will start immediately. E. Object Class has a final() method. *GC - Garbage Collector
D.
Which of the following statement is true? A. Upcasting increases the capabilities of the object. B. Upcasting can't be done implicitly. C. Casting a subclass object to a superclass object is known as downcasting. D. When downcasting, a ClassCastException is possible. E. None of the above.
B, C. A reference to an object requires an explicit cast if referenced with a subclass, so option A is incorrect. If the cast is to a superclass reference, then an explicit cast is not required. Because of polymorphic parameters, if a method takes the superclass of an object as a parameter, then any subclass references may be used without a cast, so option B is correct. All objects extend java.lang.Object, so if a method takes that type, any valid object, including null, may be passed; therefore, option C is correct. Some cast exceptions can be detected as errors at compile-time, but others can only be detected at runtime, so D is incorrect. Due to the nature of polymorphism, a public instance method can be overridden in a subclass and calls to it will be replaced even in the superclass it was defined, so E is incorrect.
Which of the following statements about polymorphism are true? (Choose all that apply) A. A reference to an object may be cast to a subclass of the object without an explicit cast. B. If a method takes a superclass of three objects, then any of those classes may be passed as a parameter to the method. C. A method that takes a parameter with type java.lang.Object will take any reference. D. All cast exceptions can be detected at compile-time. E. By defining a public instance method in the superclass, you guarantee that the specific method will be called in the parent class at runtime.
A. The method() method in the parent class A will be called because it is Static, and bound when the class is first loaded rather than at runtime.
Which of the following statements is true about this program code? A.The output will be A B B.The output will be C D C.The output will be A B C D D.Run-time exception is thrown. E.Compilation fails due to error at line 8.
A
Which of the following statements is true? I. If statement must contain else or else if. II. We can't place any other statements between if and else (or else if) blocks. III. If statement may have more than one else statements. A.Only II. B.Only III. C.Only I and II. D.Only I and III. E.Only II and III.
A. Note, B and C are incorrect because when you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
Which of the following statements will override method() in class Sub? A. public final void method(){ } B. private void method() { } C. void method() { } D. public void method(int i) { } E. protected int method() { return 0; }
A
Which of the following will compile the code successfully when inserted at line 2? A. public static void main(String [ ] args)throws java.io.IOException, ClassNotFoundException { B. public static void main(String [ ] args)throws java.io.IOException, SecurityException { C. public static void main(String [ ] args)throws java.io.IOException|SecurityException { D. public static void main(String [ ] args)throws ClassNotFoundException { E. None of the above.
A, B, D, E, G, H, J, K
Which of the following will generate a compiler error? A. A call to a private constructor. B. abstract void myMethod(){}; C. protected abstract void myMethod(); D. static import java.util.Arrays.asList; E. int i = 0248; F. int i = 'a' + 'b' + 'c'; G. default void myMethod(); H. int[ ] a = {1,2,3}; System.out.print(a.length()); I. StringBuilder sb = new StringBuilder(5); System.out.print(sb.size()); J. static class A {} K. protected abstract class Class() {}
D. Non-static field 'x' cannot be referenced from a static context.
Which of the following will produce a compile-time error when inserted at line 4? A. System.out.print(ab.x); B. System.out.print(B.j); C. System.out.print(ab.j); D. System.out.print(A.x); E. System.out.print(A.j);
D. Inside the parentheses 'false | true' evaluates to true because the bitwise OR '|' operator returns true if either operand is equal to true. The expression then becomes 'true ^ true', which is false because the bitwise XOR (eXclusive or, '^') returns true if one, but not both, of the operands is true, false otherwise.
Which of the following will result false? A.true ^ false | true B.(true ^ false) | true C.(true ^ false | true) D.true ^ (false | true) E.None of the above
B. Note, the pattern outputs the hours and minutes of a given date/time object, so an object that has date only would throw a UnsupportedTemporalTypeException.
Which of the following will throw an exception for a DateTimeFormatter f = DateTimeFormatter.ofPattern("hh:mm"): A. f.format(dateTime); B. f.format(date); C. f.format(time);
D. It is illegal to access instance variables using class name. To access them, we have to do so through a valid object reference.
Which of the following, inserted at line 4, will produce compile time errors? A. System.out.print(ab.x): B. System.out.print(B.j): C. System.out.print(ab.j): D. System.out.print(A.x): E. None of the above.
C. Arrays define a property called length. It is not a method, so parentheses are not allowed.
Which of these compile when replacing line 8? (Choose all that apply) 7: char[ ]c = new char[2]; 8: // INSERT CODE HERE A. int length = c.capacity; B. int length = c.capacity(); C. int length = c.length; D. int length = c.length(); E. int length = c.size; F. int length = c.size(); G. None of the above.
F. The ArrayList class defines a method called size().
Which of these compile when replacing line 8? (Choose all that apply) 7: ArrayList l = new ArrayList(); 8: // INSERT CODE HERE A. int length = l.capacity; B. int length = l.capacity(); C. int length = l.length; D. int length = l.length(); E. int length = l.size; F. int length = l.size(); G. None of the above.
F. The ArrayList class defines a method called size().
Which of these will compile if inserted after the following line of code? (choose all that apply) ArrayList1 = new ArrayList(); A. int length = l.capacity; B. int length = l.capacity(); C. int length = l.length; D. int length = l.length(); E. int length = l.size; F. int length = l.size(); G. None of the above.
C. Arrays define a property called length. It is not a method, so parentheses are not allowed.
Which of these will compile if inserted after the following line of code? (choose all that apply) char[ ] c = new char[2]; A. int length = c.capacity; B. int length = c.capacity(); C. int length = c.length; D. int length = c.length(); E. int length = c.size; F. int length = c.size(); G. None of the above.
C, D, E. package and import are both optional. If both are present, the order must be package, then import, then class. Option A is incorrect because class is before package and import. Option B is incorrect because import is before package. Option F is incorrect because class is before package. Option G is incorrect because class is before import.
Which represent the order in which the following statements can be assembled into a program that will compile successfully? (Choose all that apply) A: class Rabbit {} B: import java.util.*; C: package animals; A. A, B, C B. B, C, A C. C, B, A D. B, A E. C, A F. A, C G. A, B
B, C, E, F. Option A is wrong, because an abstract class may contain concrete methods. Since Java 8, interfaces may also contain concrete methods in form of static or default methods. Although all variables in interfaces are assumed to be public static final, abstract classes may contain them as well, so option B is correct. Both abstract classes and interfaces can be extended with the extends keyword, so option C is correct. Only interfaces can contain default methods, so option D is incorrect. Both abstract classes and interfaces can contain static methods, so option E is correct. Both structures require a concrete subclass to be instantiated, so option F is correct. Finally, though an instance of an object that implements an interface inherits java.lang. Object, the interface itself doesn't; otherwise, Java would support multiple inheritance for objects, which it doesn't. Therefore, option G is incorrect.
Which statements are true for both abstract classes and interfaces? (Choose all that apply) A. All methods within them are assumed to be abstract. B. Both can contain public static final variables. C. Both can be extended using the extend keyword. D. Both can contain default methods. E. Both can contain static methods. F. Neither can be instantiated directly. G. Both inherit java.lang.Object.
StringBuilder is faster because it doesn't need to be thread-safe.
Why is StringBuilder better than StringBuffer?
D. Note, A, B, and C are all false statements. C is the particularly tricky one here as you have to pay attention to whether or not an intermediary abstract class has already provided an implementation for the abstract method. If it has, the concrete class doesn't have to provide an implementation for that method.
Why won't the code compile? A. The getname method in Animal must have a body. B. The abstract class BigCat cannot provide an implementation for the abstract class Animal. C. The concrete class, Lion, must provide an implementation for both getName and getRoar. D. Nothing is wrong with it, it compiles.
Static Import
You can import an individual static member of a class or all its static members by using a ______ ______ statement.
Static
You can't prefix the definition of a top-level class or an interface with the keyword _______. A top-level class or interface is one that isn't defined within another class or interface.
B, D. Note, A is non-sensical because in order to do anything with the exception, you first have to catch it. C is incorrect because IOException doesn't extend RuntimeException.
You have a method that currently does not handle any exception thrown from the code contained in its method body. You are now changing this method to call another method that throws IOException. What changes, independent of each other, can you make to your method so that it will compile? (choose two) A. Set the exception to null and don't rethrow it. B. Declare IOException in the throws clause of your method. C. Wrap the call to another method within a try-catch block that catches RuntimeException. D. Wrap the call to another method within a try-catch block that catches Exception.
B
You read the following statement in a Java program that compiles and executes: car.drive(speed) What observation can you make for sure? A. speed must be a double B. drive must be a method C. drive must be the name of an instance field D. drive must be the name of a class E. car must be a method
Arrays, Collections
You use the ________________ helper class to sort arrays and the _____________________ helper class to sort ArrayLists.
this, current object
_______ is a reference to the _____________ _______________, the object whose method or constructor is being called.
Static
________ attributes exist independent of any instances of a class and may be accessed even when no instances of the class have been created.
Import
_____________ statements allow the use of simple names for packaged classes and interfaces defined in other packages.
D, C, B
_______________ are unchecked exceptions, __________________ are ___________________ exceptions. (Choose the appropriate answers to fill in the blanks, in order.) A. Throwables B. checked C. compile-time errors D. runtime exceptions
length, array, length(), String
_______________ is an int field describing the number of elements in an __________, and ______________ is a method that returns the length of the sequence of characters in a _____________.
parameters, arguments
___________________ refers to the list of variables in a method declaration. ___________________ are the actual values that are passed in when the method is invoked.
overloaded, overridden
____________________ methods can have different return types, while _________________ methods must return the same or covariant return types.
Immutability
____________________ refers to preventing callers from changing the instance variables at all.
StringBuilders
______________________ are mutable sequences of characters.
Associativity
______________________ determines the order of evaluation in an expression containing two or more operators with the same precedence.
StringBuffer
_______________________ is an older, thread-safe version of StringBuilder.