COP 2800 Java 1: Practice Exam Correct Answers

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Module 2: Which of the following do not denote a primitive data value in Java? Select the two correct answers. "hello" false 50.5F "t" 'k'

"hello" "t" *(String is a class, and "hello" and "t" denote String objects. Java has the following primitive data types: boolean, byte, short, char, int, long, float, and double.)*

Module 1: Which is the first line of a constructor declaration in the following code? Select the one correct answer. public class Counter { // (1) int current, step; public Counter(int startValue, int stepValue) { // (2) setCurrent(startValue); // (3) setStep(stepValue); } public int getCurrent() { return current; } // (4) public void setCurrent(int value) { current = value; } // (5) public void setStep(int stepValue) { step = stepValue; } // (6) } (6) (1) (4) (2) (5) (3)

(2) *((2) is the first line of a constructor declaration. A constructor in Java is declared like a method, but does not specify a return value. (1) is the header of a class declaration, (3) is the first line in the constructor body, and (4), (5), and (6) are instance method declarations.)*

Module 3: What will the following program print when run? public class ParameterPass { public static void main(String[] args) { int i = 0; addTwo(i++); System.out.println(i); } static void addTwo(int i) { i += 2; } } Select the one correct answer. 0 2 1 3

1 *(The correct answer is 1. Evaluation of the actual parameter i++ yields 0, and increments i to 1 in the process. The value 0 is copied into the formal parameter i of the method addTwo() during method invocation. However, the formal parameter is local to the method, and changing its value does not affect the value in the actual parameter. The value of the variable i in the main() method remains 1.)*

Module 2: Which of the following is not a legal identifier? Select the one correct answer. _class _8to5 ca$h 52pickup a2z odipus

52pickup *(52pickup is not a legal identifier. The first character of an identifier cannot be a digit. An underscore is treated as a letter in identifier names.)*

Module 1: Which statement is true about instance members? Select the one correct answer. An instance member belongs to an instance, not to the class as a whole An instance member always represents an operation An instance member is never a method An instance member is always a field An instance member is also called a static member

An instance member belongs to an instance, not to the class as a whole *(An instance member is a field or an instance method. These members belong to an instance of the class rather than to the class as a whole. Members that are not explicitly declared as static in a class declaration are instance members.)*

Module 1: Which statement is true about objects? Select the one correct answer. An object is a variable. An object is what classes are instantiated from. An object is an instance of a class. An object is a reference. An object is a blueprint for creating concrete realization of abstractions.

An object is an instance of a class. *(An object is an instance of a class. Objects are created from classes that implement abstractions. The objects that are created are concrete realizations of those abstractions. An objects is neither a reference nor a variable.)*

Module 3: Given a class named Book, which one of these constructor declarations is valid for the class Book? Select the one correct answer. void Book() {} Book(Book b) {} Book Book() {} public static void Book(String[] args) {} abstract Book() {} private final Book() {}

Book(Book b) {} *(Book(Book b) {} is the only valid constructor. A constructor cannot specify any return type, not even void. A constructor cannot be final, static, or abstract.)*

Module 3: Is it possible to create arrays of length zero? Select the one correct answer. Yes, you can create arrays of any type with length zero. Yes, but only for arrays of reference types. Yes, but only for primitive data types. No, it is not possible to create arrays of length zero in Java. No, you cannot create zero-length arrays, but the main() method may be passed a zero-length array of Strings when no program arguments are specified.

Yes, you can create arrays of any type with length zero. *(Java allows arrays of length zero. Such an array is passed as an argument to the main() method when a Java program is run without any program arguments.)*

Module 2: Which of the following declarations are valid? Select the three correct answers. char a = '\u0061'; char 'a' = 'a'; ch'a'r a = 'a'; char \u0061 = 'a'; ch\u0061r a = 'a';

char a = '\u0061'; char \u0061 = 'a'; ch\u0061r a = 'a'; *(The correct choices are: char a = '\u0061'; char \u0061 = 'a'; ch\u0061r a = 'a'; The \uxxxx notation can be used anywhere in the source to represent Unicode characters.)*

Module 2: Which of the following is not a legal comment in Java? Select the one correct answer. /* */ // /* // */ // // /* /* */ */ /* /* */ // /* */

/* /* */ */ *(Everything from the start sequence (/*) of a multiple-line comment to the first occurrence of the end sequence (*/) of a multiple-line comment is ignored by the compiler. Everything from the start sequence (//) of a single-line comment to the end of the line is ignored by the compiler. In /* /* */ */ the multiple line comment ends with the first occurrence of the end sequence (*/), leaving the second occurrence of the end sequence (*/) unmatched.)*

Module 9: How many objects are eligible for garbage collection when control reaches (1)? public class Link { private Link next; Link(Link next) { this.next = next; } public void finalize() { System.out.print("X"); } public static void main(String[] args) { Link p = null; for (int i = 0; i < 5; i++) { p = new Link(p); } System.gc(); //(1) } } Select the one correct answer. 0 Hard to say 10 5

0 *(The correct answer is 0. All the objects created in the loop are reachable via p when control reaches (1).)*

Module 9: Which method headers will result in a correct implementation of a finalizer for the following class? public class Curtain { // (1) INSERT METHOD HEADER HERE ... { System.out.println("Final curtain"); super.finalize(); } } Select the two correct answers. private void finalize() throws Exception protected void finalize() throws Exception protected void finalize() throws Throwable void finalize() public void finalize() public void finalize() throws Throwable private void finalize() private void finalize() throws Throwable void finalize() throws Exception void finalize() throws Throwable public void finalize() throws Exception protected void finalize()

protected void finalize() throws Throwable public void finalize() throws Throwable *(protected void finalize() throws Throwable and public void finalize() throws Throwable are correct. Any choice which reduces the visibility of the inherited method is not correct. Any choice which throws Exception is not correct since the Throwable superclass is not assignable to the Exception subclass.)*

Module 2: Which statement is true? Select the one correct answer. new and delete are keywords in the Java language. exit, class, and while are keywords in the Java language. for, while, and next are keywords in the Java language. try, catch, and thrown are keywords in the Java language. return, goto, and default are keywords in the Java language. static, unsigned, and long are keywords in the Java language.

return, goto, and default are keywords in the Java language. *(In Java, the identifiers delete, thrown, exit, unsigned, and next are not keywords. Java has a goto keyword, but it is reserved and not currently used.)*

Module 4: Given the following source code, which comment line can be uncommented without introducing errors? abstract class MyClass { abstract void f(); final void g() {} //final void h() {} // (1) protected static int i; private int j; } final class MyOtherClass extends MyClass { //MyOtherClass(int n) { m = n; } // (2) public static void main(String[] args) { MyClass mc = new MyOtherClass(); } void f() {} void h() {} //void k() { i++; } // (3) //void l() { j++; } // (4) int m; } Select the one correct answer. (4) (1) (3) (2)

(3) *(Line (3) void k() { i++; } can be reinserted without introducing errors. Reinserting line (1) will cause the compilation to fail, since MyOtherClass will try to override a final method. Reinserting line (2) will fail, since MyOtherClass will no longer have the (no-argument) default constructor. The main() method needs to call the no-argument constructor. Reinserting line (3) will work without any problems, but reinserting line(4) will fail, since the method will try to access a private member of the superclass.)*

Module 10: Which statements are true about the following code? import java.util.function.Predicate; public class RQ12A98 { public static final String lock1 = "Brinks"; private static String lock2 = "Yale"; public static void main(String[] args) { Predicate<Object> p; p = lock -> { boolean p = lock.equals("Master"); return p; }; // (1) p = lock -> { return lock.toString().equals("YALE"); }; // (2) p = lock -> { (args.length > 0) ? lock.equals(args[0]) : false; }; // (3) p = lock -> { return lock.equals(lock1); }; // (4) p = lock -> { return lock.equals(lock2); }; // (5) p = lock2 -> { return lock2.equals(RQ12A98.lock2); }; // (6) } } Select the two correct answers. (2) will not compile. (6) will not compile. (5) will not compile. (4) will not compile. (3) will not compile. (1) will not compile.

(3) will not compile. (1) will not compile. *((1) will not compile. and (3) will not compile. (1) redeclares the local variable p from the enclosing scope, which is not legal. In (2), the equals() method of the String class is called, because it is invoked on the textual representation of the parameter. In the other elements, the equals() method of the object referred to by the return statement. The lambda body in (3) is a statement block with an expression whose value must be returned by the return statement. (4) and (5) access static members in the class, which is legal. In (6), the parameter name lock2 shadows the static variable by the same name, but is a local variable in the lambda expression. The static variable is referred to using the class name.)*

Module 4: Which lines that are marked will compile in the following code? // File name: A.java package packageA; public class A { protected int pf; } ************************************************************************** // File name: B.java package packageB; import packageA.A; public class B extends A { void action(A obj1, B obj2, C obj3) { pf = 10; // (1) obj1.pf = 10; // (2) obj2.pf = 10; // (3) obj3.pf = 10; // (4) } } class C extends B { void action(A obj1, B obj2, C obj3) { pf = 10; // (5) obj1.pf = 10; // (6) obj2.pf = 10; // (7) obj3.pf = 10; // (8) } } class D { void action(A obj1, B obj2, C obj3) { pf = 10; // (9) obj1.pf = 10; // (10) obj2.pf = 10; // (11) obj3.pf = 10; // (12) } } Select the five correct answers. *Not* (7) (9) (12) (6) (2) (11) (10)

(4) (3) (5) (8) (1) *(The correct answers are (1), (3), (4), (5), and (8). A protected member of a superclass is always inherited by a subclass. Direct access to the protected field pf is permitted in subclasses B and C at lines (1) and (5), respectively. A subclass in another package can access protected members in the superclass only via references of its own type or it subtypes. In packageB, the subclass B can access the protected field pf in the superclass packageA.A via references of type B (parameter obj2) and references of its subclass C (parameter obj3). However, the subclass C can access the protected field pf in the superclass packageA.A only via references of type C (parameter obj3). This is the case at (3), (4), and (8). The class D does not have any inheritance relationship with any of the other classes, and therefore the protected field pf is not accessible in the class D. This rules out the lines from (9) to (12).)*

Module 10: Which statements are true about the following code? interface Funky1 { void absMethod1(String s); } interface Funky2 { String absMethod2(String s); } public class RQ12A99 { public static void main(String[] args) { Funky1 p1; p1 = s -> System.out.println(s); // (1) p1 = s -> s.length(); // (2) p1 = s -> s.toUpperCase(); // (3) p1 = s -> { s.toUpperCase(); }; // (4) p1 = s -> { return s.toUpperCase(); }; // (5) Funky2 p2; p2 = s -> System.out.println(s); // (6) p2 = s -> s.length(); // (7) p2 = s -> s.toUpperCase(); // (8) p2 = s -> { s.toUpperCase(); }; // (9) p2 = s -> { return s.toUpperCase(); }; // (10) } } Select the four correct answers. (2) will not compile. (8) will not compile. (9) will not compile. (4) will not compile. (6) will not compile. (10) will not compile. (1) will not compile. (5) will not compile. (7) will not compile. (3) will not compile.

(9) will not compile. (6) will not compile. (5) will not compile. (7) will not compile. *(The correct answers are (5) will not compile (6) will not compile (7) will not compile (9) will not compile We must check whether the function type of the target type and the type of the lambda expression are compatible. The function type of the target type p1 in the assignment statements from (1) to (5) is String -> void, or a void return. The function type of the target type p2 in the assignment statements from (6) to (10) is String -> String, or a non-void return. The non-void return of a lambda expression with an expression statement as the body can be interpreted as a void return, if the function type of the target type returns void.)*

Module 2: Which of the following are not legal literals in Java? Select the four correct answers. "What\'s your fancy?" 1_2e4f +_825 09 '\x' 0B_101_101 0xbad

+_825 09 '\x' 0B_101_101 *(0B_101_101, 09, +_825, and '\x' are not legal literals. In 0B_101_101, the first underscore is not between digits In 09, the digit 9 is not a valid octal (base 8) digit (valid octal digits are 0-7). In +_825, again, the underscore is not between digits. In '\x', there is no such escape sequence. While we can escape some letters (e.g. '\t' for tab characters), we can't arbitrarily escape any letter.)*

Module 4: Given the following directory structure: /proj |--- src | |--- A.java | | |--- bin |--- top |--- sub |--- A.class Assume that the current directory is /proj/src. Which class path specifications will find the file A.class of the class top.sub.A declared in the file /proj/src/A.java? Select the two correct answers. -cp .:../bin -cp /proj/bin/top -cp /proj/bin/top/sub/A.class -cp /proj -cp /proj/bin -cp /proj/bin/top/sub

-cp .:../bin -cp /proj/bin *(The correct answers are -cp .:../bin -cp /proj/bin The parent directory of the package must be specified. cp .:../bin specifies the current directory (.) first, but there is no file top/sub/A.class under the current directory. Searching under ../bin finds the file top/sub/A.class.)*

Module 1: Given the following code, which statements express the most accurate association? class Carriage { } class TrainDriver { } class Train() { private Carriage carriages[]; private TrainDriver driver; Train(TrainDriver trainDriver, int noOfCarriages) { carriages = new Carriage[noOfCarriages]; driver = trainDriver; } void insertCarriage(Carriage newCarriage) { /* ... */ } } Select the three correct answers. A Train object owns an array of Carriage objects. An array of Carriage objects is part of a Train object. A Train object owns Carriage objects. A TrainDriver object is part of a Train object. A Train object has a TrainDriver object. A Train object has an array of Carriage objects. A Train object owns a TrainDriver object. Carriage objects are part of a Train object.

A Train object owns an array of Carriage objects. An array of Carriage objects is part of a Train object. A Train object has a TrainDriver object. *(A Train object can share both the TrainDriver object and its Carriage objects with other Train objects when it is not using them. In other words, they can outlive the Train object. This is an example of aggregation. However, in a Train object the array object is used for handling its carriages. The lifetime of an array object is nested in the lifetime of its Train object. This is an example of composition.)*

Module 4: Which statement is true? Select the one correct answer. A static method can call other non-static methods in the same class by using the this keyword. A class may contain both static and non-static variables, and both static and non-static methods. Instance methods may access local variables of static methods All methods in a class are implicitly passed the this reference as an argument, when invoked. Each object of a class has its own instance of the static variables declared in the class.

A class may contain both static and non-static variables, and both static and non-static methods. *(The keyword this can be used only in non-static code, as in non-static methods, constructors, and instance initializer blocks. Only one occurrence of each static variable of a class is created, when the class is loaded by the JVM. This occurrence is shared among all the objects of the class (and for that matter, by other clients). Local variables are accessible only with the block scope, regardless of whether the block scope is defined within a static context.)*

Module 3: What will be the result of compiling the following program? Select the one correct answer. public class MyClass { long var; public void MyClass(long param) { var = param; } // (1) public static void main(String[] args) { MyClass a, b; a = new MyClass(); // (2) b =new MyClass(5); // (3) } } A compile-time error will occur at (1) A compile-time error will occur at (2) The program will compile without errors. A compile-time error will occur at (3)

A compile-time error will occur at (3) *(A compile-time error will occur at (3) since the class does not have a constructor accepting a single argument of type int. The declaration at (1) declares a method, not a constructor, since it is declared as void. The method happens to have the same name as the class, but that is irrelevant (and a bad idea). The class has a default constructor, since the class contains no constructor declarations. This constructor will be invoked to create a MyClass object at (2).)*

Module 3: Which statements are true? Select the two correct answers. A constructor can return a value. A class must define a constructor. A constructor can access the non-static members of a class. A constructor can be declared private. A constructor must initialize all fields when a class is instantiated.

A constructor can access the non-static members of a class. A constructor can be declared private. *(A constructor can be declared as private, but this means that this constructor can be used only with the class. Constructors need not initialize all the fields when a class is instantiated. A field will be assigned a default value if not explicitly initialized. A constructor is non-static and, as such, it can directly access both the static and non-static members of the class.)*

Module 1: Which statement is true about methods? Select the one correct answer. A method is an attribute defining the property of a particular abstraction. A method is an implementation of an abstraction. A method is a blueprint for making operations. A method is a category of objects. A method is an operation defining the behavior for a particular abstraction.

A method is an operation defining the behavior for a particular abstraction. *(A method is an operation defining the behavior for a particular abstraction. Java implements abstractions using classes that have properties and behavior. Behavior is defined by the operations of the abstraction.)*

Module 4: Which statement is true about the accessibility of members? Select the one correct answer. A private member can be accessed only within the class of the member. A private member is always accessible within the same package. A member with default accessibility can be accessed by any subclass of the class in which it is declared. A private member cannot be accessed at all. Package / default accessibility for a member can be declared using the keyword default.

A private member can be accessed only within the class of the member. *(A private member is accessible only with the class of the member. If no accessibility modifier has been specified for a member, the member has default accessibility, also known as package accessiblity. The keyword default is not an accessibility modifier. A member with package accessibility is accessible only from classes in the same package. Subclasses in other packages cannot access a member with default accessibility.)*

Module 4: Which statements about modifiers are true? Select the two correct answers. Fields can be declared as native. Abstract classes can declare final methods. Non-abstract methods can be declared in abstract classes. Abstract classes can be declared as final. Classes can be declared as native.

Abstract classes can declare final methods. Non-abstract methods can be declared in abstract classes. *(The correct answers are Abstract classes can declare final methods. Non-abstract methods can be declared in abstract classes. Abstract classes can declare both final methods and non-abstract methods. Non-abstract classes cannot, however, contain abstract methods. Nor can abstract classes be final. Only methods can be declared native.)*

Module 9: Identify the location in the following program where the object, initially referenced by arg1, is eligible for garbage collection. public class MyClass { public static void main(String[] args) { String msg; String pre = "This program was called with "; String post = " as first argument."; String arg1 = new String((args.length > 0)? "'" + args[0] + "'" : "<no argument>"); msg = arg1; arg1 = null; //(1) msg = pre + msg + post; //(2) pre = null; //(3) System.out.println(msg); msg = null; //(4) post = null; //(5) args = null; //(6) } }

After the line labeled (2) Select the one correct answer. After the line labeled (1) After the line labeled (6) After the line labeled (4) After the line labeled (5) After the line labeled (3) *(After the line labeled (2). Before (1), the String object initially referenced by arg1 is denoted by both msg and arg1. After (1), the String object is denoted by only msg. At (2), reference msg is assigned a new reference value. This reference value denotes a new String object created by concatenating the contents of several other String objects. After (2), there are no references to the String object initially referenced by arg1. The String object is now eligible for garbage collection.)*

Module 9: Which of the following statements is true? Select the one correct answer. The finalize() method can be declared with any accessibility. All objects have a finalize() method. If an exception is thrown during execution of the finalize() method of an eligible object, the exception is ignored and the object is destroyed. The compiler will fail to compile code that defines an overriding finalize() method that does not explicitly call the overridden finalize() method from the superclass. Objects can be destroyed by explicitly calling the finalize() method.

All objects have a finalize() method. *(The Object class defines a protected finalize() method. All classes inherit from Object, so all objects have a finalize() method. Classes can override the finalize() method and, as with all overriding, the new method must not reduce the accessibility. The finalize() method of an eligible object is called by the garbage collector to allow the object to do any cleaning up before the object is destroyed. When the garbage collector calls the finalize() method, it will ignore any exceptions thrown by the finalize() method. If the finalize() method is called explicitly, normal exception handling occurs when an exception is thrown during the execution of the finalize() method; exceptions are not simply ignored. Calling the finalize() method does not in itself destroy the object. Chaining of the finalize() method is not enforced by the compiler, and it is not mandatory to call the overridden finalize() method.)*

Module 4: Given the source file A.java: // File: A.java package net.alphabet import java.util.ArrayList; public class A {} class B {} Select the two correct answers. Only class A will be placed in the package net.alphabet. Class B will be placed in the default package. Only class A can access the imported class java.util.ArrayList by its simple name. Both class A and class B can access the imported class java.util.ArrayList by its simple name. Both class A and class B will be placed in the package net.alphabet.

Both class A and class B can access the imported class java.util.ArrayList by its simple name. Both class A and class B will be placed in the package net.alphabet. *(The correct answers are: Both class A and class B will be placed in the package net.alphabet. Both class A and class B can access the imported class java.util.ArrayList by its simple name. Bytecode of all reference type declarations in the file is placed in the designated package, and all reference type declarations in the file can access the imported types.)*

Module 4: Given the following class, which of these alternatives are valid ways of referring to the class from outside of the package net.basemaster? package net.basemaster; public class Base { // ... } Select the two correct answers. By simply referring to the class as net.basemaster.Base By simply referring to the class as Base By importing with net.*, and referring to the class as basemaster.Base By importing with net.basemaster.*, and referring to the class as Base By simply referring to the class as basemaster.Base

By simply referring to the class as net.basemaster.Base By importing with net.basemaster.*, and referring to the class as Base *(The correct answers are By simply referring to the class as net.basemaster.Base By importing with net.basemaster.*, and referring to the class as Base A class or interface name can be referred to by using either its fully qualified name or its simple name. Using the fully qualified name will always work, but to use the simple name it must be imported. When net.basemaster.* is imported, all the type names from the package net.basemaster will be imported and can now be referred to by using simple names. Importing net.* will not import the subpackage basemaster.)*

Module 1: Given the following code, which statements are true? class A { protected int value1; } class B extends A { int value2; } Select the two correct answers. Class B is a subclass of class A. Objects of class B have a field named value1. Class B is the superclass of class A. Objects of class A have a field named value2. Class A extends class B. Class A inherits from class B.

Class B is a subclass of class A. Objects of class B have a field named value1. *(Given the declaration class B extends A, we can conclude that class B extends class A, class A is the superclass of class B, class B is a subclass of class A, and class B inherits from class A, which means that objects of class B will inherit the field value1 from class A.)*

Module 4: Given the following directory structure: /top |--- wrk |--- pkg |--- A.java |--- B.java Assume that the two files A.java and B.java contain the following code, respectively: // File: A.java package pkg; class A { B b; } _______________________________________________________ // File: B.java package pkg; class B { ... } For which combinations of the current directory and command is the compilation successful? Select the one correct answer. *Not* Current directory: /top/wrk Command: javac -cp .:pkg A.java Current directory: /top/wrk Command: javac -cp .:pkg pkg/A.java Current directory: /top/wrk/pkg Command: javac -cp . A.java Current directory: /top/work/pkg Command: javac A.java Current directory: /top/wrk Command: javac -cp pkg A.java

Current directory: /top/wrk Command: javac -cp . pkg/A.java *(The correct answer is: Current directory: /top/wrk Command: javac -cp . pkg/A.java Incorrect answers: In Current directory: /top/wrk Command: javac -cp .:pkg A.java and Current directory: /top/wrk Command: javac -cp pkg A.java class A cannot be found. In Current directory: /top/wrk/pkg Command: javac A.java and Current directory: /top/wrk/pkg Command: javac -cp . A.java class B cannot be found -- there is no package under the current directory /top/wrk/pkg to search for class B. In Current directory: /top/wrk Command: javac -cp .:pkg pkg/A.java class B also cannot be found (the textbook erroneously marks this as a correct choice, but it isn't). Specifying pkg in the classpath in javac -cp .:pkg pkg/A.java is superfluous. The parent directory of the package must be specified, meaning the location of the package.)*

Module 2: In which of these variable declarations will the variable remain uninitialized unless it is explicitly initialized? Select the one correct answer. Declaration of a local variable of type float Declaration of an instance variable of type int[] Declaration of a static variable of type Object Declaration of an instance variable of type int Declaration of a static variable of type float

Declaration of a local variable of type float *(The local variable of type float will remain uninitialized. Fields and static variables are initialized with a default value. An instance variable of type int[] is a reference variable that will be initialized with the null value. Local variables remain uninitialized unless explicitly initialized. The type of the variable does not affect whether a variable is initialized.)*

Module 5: Which statements are true about the following code? public class RQ05A100 { public static void main(String[] args) { int n1 = 10, n2 = 10; int m1 = 20, m2 = 30; int result = n1 != n2? n1 : m1 != m2? m1 : m2; System.out.println(result); } } Select the one correct answer. When run, the program throws an ArithmeticException at runtime. When run, the program will print 30. When run, the program will print 10. When run, the program will print 20. The program will not compile.

When run, the program will print 20. *(When run, the program will print 20. The condition in the outer conditional expression is false. The condition in the nested conditional expression is true, resulting in the value of m1 (i.e. 20) being printed.)*

Module 4: Given the following declaration of a class, which field is accessible from outside the package com.corporation.project? package com.corporation.project; public class MyClass { int i; public int j; protected int k; private int l; } Select the one correct answer. Field l is accessible in subclasses only in other packages. Field l is accessible in all classes in other packages. Field k is accessible in all classes in other packages. Field i is accessible in all classes in other packages. Field j is accessible in all classes in other packages. Field k is accessible in subclasses only in other packages.

Field j is accessible in all classes in other packages. *(Outside of the package, the member j is accessible to any class, whereas the member k is only accessible to subclasses of MyClass. The field i has package accessibility, and is accessible only to classes inside the package. The field j has public accessibility, and is accessible from anywhere. The field k has protected accessibility and is accessible from any class inside the package and from subclasses anywhere. The field l has private accessibility and is accessible only within its own class.)*

Module 9: How many objects are eligible for garbage collection when control reaches (1)? public class Eligible { public static void main(String[] args) { for (int i = 0; i < 5; i++) { Eligible obj = new Eligible(); new Eligible(); } System.gc(); //(1) } } Select the one correct answer. Hard to say 5 10 0

Hard to say *(It is difficult to say how many objects are eligible for garbage collection when control reaches (1), because some of the eligible objects may have already been finalized.)*

Module 9: Which of the following statements is true? Select the one correct answer. If object obj1 is accessible from object obj2, and object obj2 is accessible from obj1, then obj1 and obj2 are not eligible for garbage collection. Objects can be explicitly destroyed using the keyword delete. If object obj1 can access object obj2 that is eligible for garbage collection, then obj1 is also eligible for garbage collection. Once an object has become eligible for garbage collection, it will remain eligible until it is destroyed. An object will be garbage collected immediately after it becomes unreachable.

If object obj1 can access object obj2 that is eligible for garbage collection, then obj1 is also eligible for garbage collection. *(If object obj1 can access object obj2 that is eligible for garbage collection, then obj1 is also eligible for garbage collection. An object is eligible for garbage collection only if all remaining references to the object are from other objects that are also eligible for garbage collection. Therefore, if an object obj2 is eligible for garbage collection and object obj1 contains a reference to it, the object obj1 must also be eligible. Java does not have a keyword delete. An object will not necessarily be garbage collected immediately after it becomes unreachable, but the object will be eligible for garbage collection. Circular references do not prevent objects from being garbage collected; only reachable references do. An object is not eligible for garbage collection as long as the object can be accessed by any live thread. An object that is eligible for garbage collection can be made non-eligible if the finalize() method of the object creates a reachable reference to the object.)*

Module 6: Given the following program, which statements are true? public class Exceptions { public static void main(String[] args) { try { if (args.length == 0) return; System.out.println(args[0]); } finally { System.out.println("The end"); } } } Select the two correct answers. If run with one argument, the program will simply print the given argument. If run with no arguments, the program will produce no output. The program will throw an ArrayIndexOutOfBoundsException. If run with no arguments, the program will print The end. If run with one argument, the program will print the given argument followed by "The end".

If run with no arguments, the program will print The end. If run with one argument, the program will print the given argument followed by "The end". *(If run with no arguments, the program will print The end. If run with one argument, the program will print the given argument followed by "The end". The finally clause will always be executed, no matter how control leaves the try block.)*

Module 9: Which of the labeled lines in the following code can be independently uncommented by removing the // characters, such that the code will still compile. class GeomInit { //int width = 14; /* Line A */ { // area = width * height; /* Line B */ } int width = 37; { // height = 11; /* Line C */ } int height, area;//area = width * height; /* Line D */ { // int width = 15; /* Line E */ area = 100; } } Select the two correct answers. Line E Line C Line B Line D Line A

Line E Line C *(Line A will cause an illegal redefinition of the field width. Line B uses an illegal forward reference to the fields width and height. The assignment in Line C is legal. Line D is an assignment statement, so it is illegal in this context. Line E declares a local variable inside an initializer block, with the same name as the instance variable width, which is allowed. The simple name in this block will refer to the local variable. To access the instance variable width, the this reference must be used in this block.)*

Module 2: Given the following code within a method, which statement is true? int i, j; j = 5; Select the one correct answer. Local variable j is initialized but not declared. Local variable i is not declared. Local variable j is declared but not initialized. Local variable i is declared but not initialized. Local variable j is not declared.

Local variable i is declared but not initialized. *(Local variable i is declared but not initialized. The first line of code declares the local variables i and j. The second line of code initialized the local variable j. Local variable i remains uninitialized.)*

Module 11: Which declarations will correctly create the date 13 August 2009? Select the four correct answers. LocalDate date2 = LocalDate.of(2009, Month.AUGUST, 13); LocalDate date6 = LocalDate.of(1, 1, 1).plus(Period.of(2008, 7, 12)); LocalDate date3 = LocalDate.of(0, 0, 0).withYear(2009).withMonth(8).withDayOfMonth(13); LocalDate date4 = LocalDate.of(2008, 7, 12).plusYears(1).plusMonths(1).plusDays(1); LocalDate date5 = new LocalDate(2009, 8, 13); LocalDate date1 = LocalDate.of(2009, 8, 13); LocalDate date0 = LocalDate.of(2009, 7, 13);

LocalDate date2 = LocalDate.of(2009, Month.AUGUST, 13); LocalDate date6 = LocalDate.of(1, 1, 1).plus(Period.of(2008, 7, 12)); LocalDate date4 = LocalDate.of(2008, 7, 12).plusYears(1).plusMonths(1).plusDays(1); LocalDate date1 = LocalDate.of(2009, 8, 13); *(The correct answers are: LocalDate date1 = LocalDate.of(2009, 8, 13); LocalDate date2 = LocalDate.of(2009, Month.AUGUST, 13); LocalDate date4 = LocalDate.of(2008, 7, 12).plusYears(1).plusMonths(1).plusDays(1); LocalDate date6 = LocalDate.of(1, 1, 1).plus(Period.of(2008, 7, 12)); LocalDate date0 = LocalDate.of(2009, 7, 13); is not correct because the month numbers start with 1; August has month value 8. LocalDate date3 = LocalDate.of(0, 0, 0).withYear(2009).withMonth(8).withDayOfMonth(13); is not correct because the month and day arguments (0's) in the call to the of() method result in a DateTimeException being thrown at runtime. LocalDate date5 = new LocalDate(2009, 8, 13); is not correct because the LocalDate class does not provide a public constructor.)*

Module 11: Which code, when inserted at (1), will make the program compile and execute normally? import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class RQ11A75 { public static void main(String[] args) { String pattern = "MM/dd/yyyy 'at' HH:mm:ss"; String inputStr = "02/29/2015 at 00:15:30"; DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); // (1) INSERT CODE HERE. } } Select the four correct answers. LocalDateTime dateTime = LocalDateTime.parse(inputStr, dtf); LocalTime time = LocalTime.parse(inputStr, dtf); String dateStr = LocalDate.of(2015, 12, 24).format(dtf); LocalDate date = LocalDate.parse(inputStr, dtf); String timeStr = LocalTime.MIDNIGHT.format(dtf); String dateTimeStr = LocalDateTime.of(2015, 12, 24, 0, 0).format(dtf);

LocalDateTime dateTime = LocalDateTime.parse(inputStr, dtf); LocalTime time = LocalTime.parse(inputStr, dtf); LocalDate date = LocalDate.parse(inputStr, dtf); String dateTimeStr = LocalDateTime.of(2015, 12, 24, 0, 0).format(dtf); *(LocalTime time = LocalTime.parse(inputStr, dtf); LocalDate date = LocalDate.parse(inputStr, dtf); LocalDateTime dateTime = LocalDateTime.parse(inputStr, dtf); are 3 of 4 correct answers. The input string matches the pattern. The input string specifies the mandatory parts of both a date and a time, needed by the respective method to construct either a LocalTime, a LocalDate, or a LocalDateTime. To use the pattern for formatting, the temporal object must provide the parts corresponding to the pattern letters in the pattern. The LocalTime object in String timeStr = LocalTime.MIDNIGHT.format(dtf); does not have the date part required by the pattern. The LocalDate object in String dateStr = LocalDate.of(2015, 12, 24).format(dtf); does not have the time part required by the pattern. Both of these statements will throw an UnsupportedTemporalTypeException. Only the LocalDateTime object in the remaining correct answer (4 of 4) String dateTimeStr = LocalDateTime.of(2015, 12, 24, 0, 0).format(dtf); has both the date and time parts required by the pattern.

Module 1: Which statement is true about Java? Select the one correct answer. Only Java programs can be executed by a JVM. A Java program can be executed by any JVM. None of these choices are correct. A Java program can create and destroy objects. Java bytecode cannot be translated to machine code.

None of these choices are correct. *(None of these choices are correct. The JVM must be compatible with the Java Platform on which the program was developed. The JIT feature of the JVM translates bytecode to machine code. Other languages, such as Scala, also compile to bytecode and can be executed by a JVM. A Java program can only create objects; destroying objects occurs at the direction of the automatic garbage collector.)*

Module 11: Which declarations will correctly assign an instance of the LocalTime class to the declared reference? Select the three correct answers. LocalTime time4 = LocalTime.NOON.minusHours(12); LocalTime time6 = LocalTime.of(12,00).plusMinutes(-15); LocalTime time3 = LocalTime.NOON.plusHours(-3); LocalTime time2 = new LocalTime(12, 60); LocalTime time1 = LocalTime.of(12, 60); LocalTime time5 = LocalTime.MIDNIGHT.withHours(12);

LocalTime time4 = LocalTime.NOON.minusHours(12); LocalTime time6 = LocalTime.of(12,00).plusMinutes(-15); LocalTime time3 = LocalTime.NOON.plusHours(-3); *(LocalTime time3 = LocalTime.NOON.plusHours(-3); LocalTime time4 = LocalTime.NOON.minusHours(12); LocalTime time6 = LocalTime.of(12,00).plusMinutes(-15); are the correct answers. LocalTime time1 = LocalTime.of(12, 60); uses an invalid argument for the minutes (0-59). LocalTime time2 = new LocalTime(12, 60); The LocalTime class does not provide a public constructor. LocalTime time5 = LocalTime.MIDNIGHT.withHours(12); There is no withHours() method, but there is a withHour() method in the LocalTime class.)*

Module 4: How restrictive is the default accessibility compared to public, protected, and private accessibility? Select the one correct answer More restrictive than protected, but less restrictive than private More restrictive than public, but less restrictive than protected More restrictive than private Less restrictive than protected from within a package, and more restrictive than protected from outside a package Less restrictive than public

More restrictive than protected, but less restrictive than private *(The default accessibility for members is more restrictive than protected accessibility, but less restrictive than private accessibility. Members with default accessibility are accessible only with the class itself and from classes in the same package. Protected members are, in addition, accessible from subclasses anywhere. Members with private accessibility are accessible only within the class itself.)*

Module 10: What statement is true about the java.util.ArrayList class? Select the one correct answer. The method append() can be used to append an element at the end of an ArrayList. The method replace() can be used to replace the element at a specific index with another element in an ArrayList. The method deleteA11() can be used to delete all elements in an ArrayList. The method capacity() can be used to determine the current capacity of an ArrayList. None of the above. The method delete() can be used to delete an element at a specific index in an ArrayList. The method find() can be used to determine whether an element is in an ArrayList. The method insert() can be used to insert an element at a specific index in an ArrayList.

None of the above. *(None of the above is the correct answer. The method remove() can be used to delete an element at a specific index in an ArrayList. The method clear() can be used to delete all elements in an ArrayList. The method add(int, E) can be used to insert an element at a specific index in an ArrayList. The method add() can be used to append an element at the end of an ArrayList. The method set() can be used to replace the element at a specific index with another element in an ArrayList. The method contains() can be used to determine whether an element is in an ArrayList. The is no method to determine the current capacity of an ArrayList.)*

Module 11: Which statement is true about formatting and parsing of temporal objects? Select the one correct answer. The pattern "yy-mm-dd" can be used to create a formatter that can format a LocalDate object. The DateTimeFormatter class provides only factory methods to obtain predefined formatters. The styles defined by the java.time.format.FormatStyle enum type are based on the ISO standard. The ofLocalizedDate() method of the DateTimeFormatter class returns a formatter that is based on a letter pattern passed as argument to the method. None of the above.

None of the above. *(None of the above. The DateTimeFormatter class provides factory methods to obtain both predefined and customized formatters. The styles defined by the java.time.format.FormatStyle enum type are locale sensitive. The ofLocalizedDate() method of the DateTimeFormatter class returns a formatter that is based on a format style (a constant of the FormatStyle enum type) passed as an argument to the method. The pattern "yy-mm-dd" cannot be used to create a formatter that can format a LocalDate object. The letter m stamds for minutes of the hour, which is not part of a date.)*

Module 11: Which statement is true about the Date and Time API? Select the one correct answer. The classes LocalTime, LocalDate, and Period provide the plusWeeks() method, which returns a new object, where the number of days corresponding to the specified number of weeks has been added. The classes LocalTime, LocalDate, and LocalDateTime provide the isEqual() method to test whether two temporal objects of the same type are equal. The class Period provides the withWeeks() method, which returns a copy of this period, where the number of days is set according to the number of weeks specified. The classes LocalDate and LocalDateTime provide the isLeapYear() method to check for a leap year. None of the above.

None of the above. *(None of the above. The LocalDateTime class does not provide the isLeapYear() method. The LocalTime class does not provide the isEqual() method . The Period class does not provide the withWeeks() method, but does provide the ofWeeks() method. Both the Period and LocalTime classes do not provide the plusWeeks() method.)*

Module 10: Which statement is true about functional interfaces and lambda expressions? Select the one correct answer. In the body of a lambda expression, only public members in the enclosing class can be accessed. A functional interface declaration can have only one method of declaration. A lambda expression in a program can implement only one functional interface. None of the above. In the body of a lambda expression, all local variables in the enclosing scope can be accessed. A functional interface can be implemented only by lambda expressions.

None of the above. *(The correct answer is none of the above. A functional interface can be implemented by lambda expressions and classes. A functional interface declaration can have only one abstract method declaration. In the body of a lambda expression, all members in the enclosing class can be accessed. In the body of a lambda expression, only effectively final local variables in the enclosing scope can be accessed. A lambda expression in a program can implement more than one functional interface. For example, the lambda expression (i -> i % 2 == 0) can be the target type of both the functional interfaces IntPredicate and Predicate<Integer>.)*

Module 10: What will the following program print when compiled and run? import java.util.ArrayList; import java.util.List; public class RQ12A15 { public static void main(String[] args) { doIt1(); doIt2(); } public static void doIt1() { List<StringBuilder> sbListOne = new ArrayList<>(); sbListOne.add(new.StringBuilder("Anna")); sbListOne.add(new.StringBuilder("Ada")); sbListOne.add(new.StringBuilder("Bob")); List<StringBuilder> sbListTwo = new ArrayList<>(sbListOne); sbListOne.add(null); sbListTwo.get(1).reverse(); System.out.println(sbListOne); // (1) } public static void doIt2() { List<String> listOne = new ArrayList<>(); listOne.add("Anna"); listOne.add("Ada"); listOne.add("Bob"); List<String> listTwo = new ArrayList<>(listOne); String strTemp = listOne.get(0); listOne.set(0, listOne.get(listOne.size()-1)); listOne.set(listOne.size()-1,strTemp); System.out.println(listTwo); // (2) } }

Select the two correct answers. (2) will print [Anna, Ada, Bob] (1) will print [Anna, adA, Bob, null] (2) will print [Bob, Ada, Anna]. The program will throw an IndexOutOfBoundsException at runtime. (1) will print [Anna, Ada, Bob, null] (2) will print [Anna, Ada, Bob] (1) will print [Anna, adA, Bob, null] *((1) will print [Anna, adA, Bob, null] (2) will print [Anna, Ada, Bob] In the method doIt1(), one of the common elements ("Ada") between the two lists is reversed. The value null is added to only one of the lists but not the other. In the method doIt2(), the two lists have common elements. Swapping the elements in one list does not change their positions in the other list.)*

Module 11: Which code, when inserted at (1), will make the program compile and execute normally? import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class RQ11A85 { public static void main(String[] args) { String pattern = "'Date:' dd|MM|yyyy"; String inputStr = "Date: 02|12|2015"; DateTimeFormatter dft = DateTimeFormatter.ofPattern(pattern); // (1) INSERT CODE HERE. } } Select the three correct answers. String timeStr = LocalTime.MIDNIGHT.format(dtf); String dateStr = LocalDate.of(2015, 12, 24).format(dtf); LocalTime time = LocalTime.parse(inputStr, dtf); String dateTimeStr = LocalDateTime.of(2015, 12, 24, 0, 0).format(dtf); LocalDateTime dateTime = LocalDateTime.parse(inputStr, dtf); LocalDate date = LocalDate.parse(inputStr, dtf);

String dateStr = LocalDate.of(2015, 12, 24).format(dtf); String dateTimeStr = LocalDateTime.of(2015, 12, 24, 0, 0).format(dtf); LocalDate date = LocalDate.parse(inputStr, dtf); *(LocalDate date = LocalDate.parse(inputStr, dtf); String dateStr = LocalDate.of(2015, 12, 24).format(dtf); String dateTimeStr = LocalDateTime.of(2015, 12, 24, 0, 0).format(dtf); are correct. The input string matches the pattern. It specifies the date-based values that can be used to construct a LocalDate object in LocalDate date = LocalDate.parse(inputStr, dtf); based on the date-related pattern letters in the pattern. No time-based values can be interpreted from the input string, as this pattern has only date-related pattern letters. LocalTime time = LocalTime.parse(inputStr, dtf); and LocalDateTime dateTime = LocalDateTime.parse(inputStr, dtf); both require a time part, and will throw a DateTimeParseException. To use the pattern for formatting, the temporal object must provide values for the parts corresponding to the pattern letters in the pattern. The LocalTime object in String timeStr = LocalTime.MIDNIGHT.format(dtf); does not have the date part required by the pattern. This statement will throw an UnsupportedTemporalTypeException. The LocalDate object in String dateStr = LocalDate.of(2015, 12, 24).format(dtf); has the date part required by the pattern, as does the LocalDateTime object in String dateTimeStr = LocalDateTime.of(2015, 12, 24, 0, 0).format(dtf); In this statement, only the date part of the LocalDateTime object is formatted.)*

Module 11: Which code, when inserted at (1), will result in the following output: 5 minutes past 9 import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class RQ11A96 public static void main(String[] args) { // (1) INSERT CODE HERE. String inputStr = "5 minutes past 9"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); LocalTime time = LocalTime.parse(inputStr, formatter); System.out.println(time.format(formatter)); } } Select the one correct answer. String pattern = "mm' minutes past 'H"; String pattern = "M' minutes past 'h"; String pattern = "m' minutes past 'ha"; String pattern = "m' minutes past 'Ha"; String pattern = "m' minutes past 'H"; String pattern = "M' minutes past 'H"; String pattern = "m' minutes past 'h";

String pattern = "m' minutes past 'H"; *(String pattern = "m' minutes past 'H"; is correct. The parse succeeds , with the LocalTime object having the value 09:05. Formatting this object with the formatter results in the output string : 5 minutes past 9. All other answers result in a DateTimeParseException when parsing. String pattern = "m' minutes past 'h"; The pattern letter h represents hour in the day, but requires AM/PM information to resolve the hour in a 24-hour clock (i.e. pattern letter a) which is missing. String pattern = "M' minutes past 'h"; The pattern letter M is interpreted correctly as month of the year (value 5). Matching the pattern letter h is the problem, as explained for the previous answer. String pattern = "m' minutes past 'ha";String pattern = "m' minutes past 'Ha"; The pattern letter a cannot be resolved from the input string, as an AM/PM marker is missing in the input string. String pattern = "mm' minutes past 'H"; The letter pattern mm cannot be resolved, as the minutes value has only one digit (i.e. 5) in the input string. String pattern = "M' minutes past 'H"; The parse succeeds, with the resulting LocalTime object having the value 09:00. The month value 5 is ignored. Formatting this object with the formatter results in an UnsupporttedTemporalTypeException, because now the pattern letter M requires a month value, which is not part of a LocalTime object.)*

Module 9: Which scenarios can be the result of compiling and running the following program? public class MyString { private String str; MyString(String str) { this.str = str; } public void finalize() throws Throwable { System.out.print(str); super.finalize(); } public void concat(String str2) { this.str.concat(str2); } public static void main(String[] args) { new MyString("A").concat("B"); System.gc(); } } Select the two correct answers. The program may print BA. The program may print B. The program may not print anything. The program may print A. The program may print AB.

The program may not print anything. The program may print A *(The program may print A. and The program may not print anything. are correct. It is not guaranteed if and when garbage collection will occur, nor in which order the objects will be finalized. Thus the program may not print anything. If garbage collection does take place, the MyString object created in the program may get finalized before the program terminates. In that case, the finalize() method will print A, as the string in the field str is not changed by the concat() method. Keep in mind that a String object is immutable.)*

Module 3: What will be the result of compiling and running the following program? public class Passing { public static void main(String[] args) { int a = 0; int b = 0; int[] bArr = new int[1]; bArr[0] = b; inc1(a); inc2(bArr); System.out.println("a=" + a + " b=" + b + "bArr[0]=" + bArr[0]); } public static void inc1(int x) { x++; } public static void inc2(int[] x) { x[0]++; } } The code will fail to compile, since x[0]++; is not a legal statement. The code will compile ad will print a=1 b=1 bArr[0]=1 at runtime. The code will compile and will print a=0 b=1 bArr[0]=1 at runtime. The code will compile and will print a=0 b=0 bArr[0]=1 at runtime. The code will compile and will print a=0 b=0 bArr[0]=0 at runtime.

The code will compile and will print a=0 b=0 bArr[0]=1 at runtime. *(The code will compile and will print a=0 b=0 bArr[0]=1 at runtime. The variables an and b are local variables that contain primitive values. When these variables are passed as arguments to another method, the method receives copies of the primitive values in the variables. The actual variables are unaffected by operations performed on the copies of the primitive values within the called method. The variable bArr contains a reference value that denotes an array object containing primitive values. When the variable is passed as a parameter to another method, the method receives a copy of the reference value. Using this reference value, the method can manipulate the object that the reference value denotes. This allows the elements in the array object referenced by bArr to be accessed and modified in the method inc2().)*

Module 6: What will be the result of attempting to compile and run the following program? class AnotherClass { public static void main(String[] args) { int i = 0; for (; i < 10; i++) ; // (1) for (i = 0; ; i++) break; // (2) for (i = 0; i < 10; ) i++; // (3) for (; ; ) ; // (4) } } Select the one correct answer. The code will fail to compile because of errors in the for loop at (4). The code will compile without error, but will never terminate when run. The code will fail to compile because of errors in the for loop at (1). The code will compile without error, and the program will run and terminate without any output. The code will fail to compile because of errors in the for loop at (2). The code will fail to compile because of errors in the for loop at (3).

The code will compile without error, but will never terminate when run. *(The code will compile without error, but will never terminate when run. All the sections in the for header are optional and can be omitted (but not the semi-colon). An omitted loop condition is interpreted as being true. A for loop with an omitted loop condition will never terminate, unless an appropriate control transfer statement is encountered in the loop body. The program will enter an infinite loop at (4).)*

Module 9: What will be the result of compiling and running the following program? public class MyClass { public static void main(String[] args) { MyClass obj = new MyClass(n); } static int i = 5; static int n; int j = 7; int k; public MyClass(int m) { System.out.println(i + ", " + j + ", " + k + ", " + n + ", " + m); } { j = 70; n = 20; } // Instance initializer block static { i = 50; } // Static initializer block } Select the one correct answer. *Not* The code will compile, and print 5, 7, 0, 20, 0 at runtime. The code will fail to compile, because of the instance initializer block. The code will compile, and print 5, 70, 0, 20, 20 at runtime. The code will compile, and print 50, 70, 0, 20, 20 at runtime. The code will compile, and print 5, 7, 0, 20, 20 at runtime.

The code will compile, and print 50, 70, 0, 20, 0 at runtime. *(The code will compile, and print 50, 70, 0, 20, 0 at runtime. All fields are given default values unless they are explicitly initialized. Field i is assigned the value 50 in the static initializer block that is executed when the class is initialized. This assignment will override the explicit initialization of field i in its declaration statement. When the main() method is execute, the static field i is 50 and the static field n is 0. When an instance of the class is created using the new operator, the value of static field n (i.e. 0) is passed to the constructor. Before the body of the constructor is executed, the instance initializer block is executed, which assigns the values 70 and 20 to the fields j and n, respectively. When the body of the constructor is executed, the fields i, j, k and n and the parameter m have the values 50, 70, 0, 20, and 0, respectively.)*

Module 9: Which of the following statements is true? Select the one correct answer. The compiler will fail to compile code that explicitly tries to call the finalize() method. The finalize() method can be overridden, but it must be declared with protected accessibility. The body of the finalize() method can access only other objects that are eligible for garbage collection. An overriding finalize() method in any class can always throw checked exceptions. The finalize() method can be overloaded.

The finalize() method can be overloaded. *(The finalize() method can be overloaded. The finalize() method is like any other method: it can be called explicitly if it is accessible. However, such a method is intended to be called by the garbage collector to clean up before an object is destroyed. Overloading the finalize() method is allowed, but only the method with the original signature will be called by the garbage collector. The finalize() method in the Object class is protected. This means that any overriding method must be declared as protected or public. The finalize() method in the Object class specifies a Throwable object in its throws clause. An overriding definition of this method can throw any type of Throwable. Overriding methods can limit the range of throwables to unchecked exceptions or specify no exceptions at all. Further overriding definitions of this method in subclasses will then not be able to throw checked exceptions.)*

Module 11: What will the following program print when compiled and run? import java.time.LocalDate; public class RQ11A30 { public static void main(String[] args) { LocalDate date = LocalDate.of(2015, 1, 1); date = date.withYear(5).plusMonths(14); System.out.println(date); } } Select the one correct answer. The program will print 2021-03-01. The program will print 0006-03-01. The program will not compile. None of the above. The program will print 0005-15-01. The program will throw a runtime exception when run.

The program will print 0006-03-01. *(The program will print 0006-03-01. The calculation of date.withYear(5).plusMonths(14) proceeds as follows: 2015-01-01 with year 5 ==> 0005-01-01 + 14 months (i.e. 1 year 2 months) ==> 0006-03-01)*

Module 3: Given the following pairs of method declarations, which statements are true? void fly(int distance) {}int fly(int time, int speed) { return time* speed; } void fall(int time) {}int fall(int distance) { return distance; } void glide(int time) {}void Glide(int time) {} Select the two correct answers. The third pair of methods will compile, and overload the method named glide. The first pair of methods will not compile. The first pair of methods will compile, and overload the method name fly. The second pair of methods will not compile. The third pair of methods will not compile. The second pair of methods will compile, and overload the method name fall.

The first pair of methods will compile, and overload the method name fly. The second pair of methods will not compile. *(These are the correct statements: The first pair of methods will compile, and overload the method name fly. The second pair of methods will not compile. The second pair of methods will not compile, since their method signatures do not differ. The compiler has no way of differentiating between the two methods. Note that the return type and the names of the parameters are not part of the method signature. Both methods in the first pair are named fly and have different numbers of parameters, thus overloading this method name. The methods in the last pair do not overload the method name glide, since only one method has than name. The method named Glide is distinct from the method named glide, as identifiers are case sensitive in Java.)*

Module 4: Given the source file A.java: package top.sub; public class A {} and the following directory hierarchy: /proj |--- src | |--- top | |--- sub | |--- A.java |--- bin Assuming that the current directory is /proj/src, which of the following statements are true? Select the three correct answers. *Not* After successful compilation, the absolute pathname of the file A.class will be: /proj/bin/A.class The following command will compile, and place the bytecode of the class top.sub.A under /proj/bin: javac -d . top/sub/A.java The following command will compile, and place the bytecode of the class top.sub.A under /proj/bin: javac -D /proj/bin ./top/sub/A.java

The following command will compile, and place the bytecode of the class top.sub.A under /proj/bin: javac -d ../bin top/sub/A.java After successful compilation, the absolute pathname of the file A.class will be: /proj/bin/top/sub/A.class The following command will compile, and place the bytecode of the class top.sub.A under /proj/bin: javac -d /proj/bin top/sub/A.java *(The correct answers are: The following command will compile, and place the bytecode of the class top.sub.A under /proj/bin: javac -d /proj/bin top/sub/A.java The following command will compile, and place the bytecode of the class top.sub.A under /proj/bin: javac -d ../bin top/sub/A.java After successful compilation, the absolute pathname of the file A.class will be: /proj/bin/top/sub/A.class The following response is not correct because the command will place the file A.class in the same directory as the file A.java, not in /proj/bin: The following command will compile, and place the bytecode of the class top.sub.A under /proj/bin: javac -d . top/sub/A.java The following response is not correct because there is no -D option for the java command. The following command will compile, and place the bytecode of the class top.sub.A under /proj/bin: javac -D /proj/bin ./top/sub/A.java The following response is not correct because it ignores the top.sub component of the package specification: After successful compilation, the absolute pathname of the file A.class will be: /proj/bin/A.class)*

Module 4: Which statements about the use of modifies are true? Select the two correct answers. Local variables can be declared as static. The objects themselves do not have any accessibility modifiers; only field references do. If no accessibility modifier (public, protected, or private) is specified for a member declaration, the member is accessible only by classes in the package of its class and by subclasses of its class in any package. Subclasses of a class must reside in the same package as the class they extend. You cannot specify accessibility of local variables. They are accessible only within the block in which they are declared.

The objects themselves do not have any accessibility modifiers; only field references do. You cannot specify accessibility of local variables. They are accessible only within the block in which they are declared. *(The correct answers are You cannot specify accessibility of local variables. They are accessible only within the block in which they are declared. The objects themselves do not have any accessibility modifiers; only field references do. If no accessibility modifier (public, protected, or private) is given in the member declaration of a class, the member is accessible only to classes in the same package. A subclass does not have access to members with default accessibility declared in a superclass, unless they are in the same package.Local variables cannot be declared as static or have an accessibility modifier.)*

Module 11: What will the following program print when compiled and run? import java.time.LocalTime; public class RQ11A20 { public static void main(String[] args) { LocalTime time = LocalTime.NOON; time = time.plusHours(10).plusMinutes(120); System.out.println(time); } } Select the one correct answer. The program will not compile. None of the above. The program will throw a runtime exception when run. The program will print 24:00. The program will print 00:00.

The program will print 00:00. *(The program will print 00:00. Both the hour and minutes are normalized by the plus methods, and the time of day wraps around midnight. The calculation of time.plusHours(10).plusMinutes(120) proceeds as follows: 12:00 + 10 hours ==> 22:00 + 120 min (2 hours) ==> 00:00)*

Module 9: Which scenario can definitely not be the result of compiling and running the following program? public class Grade { private char grade; Grade(char grade) { this.grade = grade; } public void finalize() throws Throwable { System.out.print(grade); super.finalize(); } public static void main(String[] args) { new Grade('A'); new Grade('F'); System.gc(); } } Select the one correct answer. The program may not print anything. The program may print FA. The program may print A. The program may print F. The program may print AFA. The program may print AF.

The program may print AFA. *(The program may print AFA. is correct (correct in the sense that this will not result from running the program) It is not guaranteed if a when garbage collection will occur, now in which order the objects will be finalized. However, it is guaranteed that the finalization of an object will be run only once. Hence "The program may print AFA." cannot possibly be a result from running the program.)*

Module 10: Which statement is true about the following program? import java.util.Arrays; import java.util.function.IntPredicate; public class RQ12A96 { public static void main(String[] args) { int[] intArray = {0, -1, -2, -3, -4, -5, -6, -7, -8, -9}; filterInt(intArray, val -> val < 0 && val % 2 == 0); System.out.println(Arrays.toString(intArray)); } public static void filterInt(int[] intArr, IntPredicate predicate) { for (inti = 0; i < intArr.length; ++i) { if (predicate.test(intArr[i])) { intArr[i] = Math.abs(intArr[i]); } } } } Select the one correct answer. *Not* The program will compile, but throw an exception when run. The program will compile and print the following when run: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The program will compile and print the following when run: [0, 1, -2, 3, -4, 5, -6, 7, -8, 9] The program will not compile.

The program will compile and print the following when run: [0, -1, 2, -3, 4, -5, 6, -7, 8, -9] *(The program will compile and print the following when run: [0, -1, 2, -3, 4, -5, 6, -7, 8, -9] The lambda expression filters all integer values that are both negative and even numbers. These values are replaced with their absolute values in the integer array. The functional interface java.util.function.IntPredicate has the abstract method boolean test(int i).*

Module 3: What would be the result of compiling and running the following program? public class MyClass { public static void main(String[] args) { int size= 20; int[] arr = new int[ size ]; for (int i = 0; i < size; ++i) { System.out.println(arr[i]); } } } Select the one correct answer. The code will not compile, because the array type int[] is incorrect. The program will compile and run without error, and will print the numbers 0 through 19. The program will compile and run without error, but will produce no output. The program will compile and run without error, and will print 0 twenty times. The program will compile and run without error, and will print null twenty times. The program will compile, but will throw an ArrayIndexOutOfBoundsException when run.

The program will compile and run without error, and will print 0 twenty times. *(The program will compile and run without error, and will print 0 twenty times. The array declaration is valid, and will declare and initialize an array of length 20 containing int values. All the values of the array are initialized to their default value of 0. The for (;;) loop will prin all the values in the array; that is, it will print 0 twenty times.)*

Module 9: What will be the result of compiling and running the following program? public class Initialization { private static String msg(String msg) { System.out.println(msg); return msg; } public Initialization() { m = msg("1"); } { m = msg("2"); } String m = msg("3"); public static void main(String[] args) { Object obj = new Initialization(); } } Select the one correct answer. The program will compile, and print 1, 2, and 3 at runtime. The program will compile, and print 2, 3, and 1 at runtime. The program will compile, and print 1, 3, and 2 at runtime. The program will compile, and print 3, 1, and 2 at runtime. The program will fail to compile.

The program will compile, and print 2, 3, and 1 at runtime. *(The program will compile, and print 2, 3, and 1 at runtime. When the object is created and initialized, the instance initializer block is executed first, printing 2. Then the instance initializer expression is executed, printing 3. Finally, the constructor body is executed, printing 1. The forward reference in the instance initializer block is legal, as the use of the field m is on the left-hand side of the assignment.)*

Module 2: What will be the result of compiling and running the following program? Select the one correct answer. public class Init { String title; boolean published; static int total; static double maxPrice; public static void main(String[] args) { Init initMe = new Init(); double price; if (true) price = 100.00; System.out.println("|" + initMe.title + "|" + initMe.published + "|" + Init.total + "|" + Init.maxPrice+ "|" + price + "|"); } } *Not* The program will compile, and print |null|true|0|0.0|100.0| at runtime. The program will fail to compile. The program will compile, and print |null|false|0|0.0|0.0| at runtime. The program will compile, and print | |false|0|0.0|0.0| at runtime.

The program will compile, and print |null|false|0|0.0|100.0| at runtime. *(The program will compile. The compiler can figure out that the local variable price will always be initialized, since the value of the condition in the if statement is true. The two instance variables and the two static variables are all initialized to the respective default value of their type.)*

Module 3: What would be the result of compiling and running the following program? public class DefaultValuesTest { int[] ia = new int[1]; boolean b; int i; Object o; public static void main(String[] args) { DefaultValuesTest instance = new DefaultValuesTest(); instance.print(); } public void print() { System.out.println(ia[0] + " " + b + " " + i + " " + o); } } Select the one correct answer. The program will throw a java.lang.NullPointerException when run. The program will print 0 false NaN null. The program will fail to compile because of uninitialized variables. The program will print null false 0 null. The program will print null 0 0 null. The program will print 0 false 0 null.

The program will print 0 false 0 null. *(The program will print 0 false 0 null at runtime. All the instance variables, and the array element, will be initialized to their default values. When concatenated with a string, the values are converted to their string representation. Notice that the null pointer is converted to the string "null" rather than throwing a NullPointerException.)*

Module 11: What will the following program print when compiled and run? import java.time.LocalDate; public class RQ11A05 { public static void main(String[] args) { LocalDate date = LocalDate.of(2016, 3, 1); date.withMonth(4); System.out.println(date.getYear() + "|" + date.getMonth() + "|" + date.getDayOfMonth()); } } Select the one correct answer. The program will not compile. The program will print 2016|MARCH|1. The program will throw a runtime exception when run. The program will print 2016|7|1. The program will print 2016|3|1. The program will print 2016|JULY|1. The program will print 2016|APRIL|1. The program will print 2016|4|1.

The program will print 2016|MARCH|1. *(The program will print 2016|MARCH|1. The date reference never gets updated, as the reeturn value is ignored. If it had been updated, the correct answer would have been The program will print 2016|APRIL|1. The LocalDate().getMonth() method returns a Month enum constant - in this case, Month.MARCH. The LocalDate.getMonthValue() method returns the month as a value between 1 and 12 - in this case 3.)*

Module 11: What will the following program print when compiled and run? import java.time.Period; public class RQ11A55 { public static void main(String[] args) { Period p1 = Period.of(1, 1, 1); Period p2 = Period.of(2, 12, 30); p1 = p1.plus(p2).plus(p1); System.out.println(p1); } } Select the one correct answer. The program will print P4Y14M32D. The program will not compile. The program will throw a runtime exception when run. None of the above. The program will print P6Y26M62D.

The program will print P4Y14M32D. *(The program will print P4Y14M32D. The calculation of p1.plus(p2).plus(p1) proceeds as follows: P1Y1M1D + P2Y12M30D ==> P3Y13M31D + P1Y1M1D ==> P4Y14M32D)*

Module 10: What will the following program print when compiled and run? import java.util.ArrayList; import java.util.List; public class RQ12A30 { public static void main(String[] args) { List<String> strList = new ArrayList<>(); strList.add("Anna"); strList.add("Ada"); strList.add("Bob"); strList.add("Bob"); for (int i = 0; i < strList.size(); ++i) { if (strList.get(i).equals("Bob")) { strList.remove(i); } } System.out.println(strList); } } Select the one correct answer. The program will not compile. The program will throw an IndexOutOfBoundsException at runtime. The program will print [Anna, Ada, Bob]. The program will not terminate when run. The program will throw a NullPointerException at runtime. The program will print [Anna, Ada]. The program will throw a ConcurrentModificationException at runtime.

The program will print [Anna, Ada, Bob]. *(The program will print [Anna, Ada, Bob]. Deleting an element when traversing a list requires care, as the size changes and any elements to the right of the deleted element are shifted left. Incrementing the loop variable after deleting an element will miss the next element, as is the case with the last occurrence of "Bob". Removing elements using the for (;;) loop does not throw a ConcurrentModificationException at runtime.)*

Module 10: What will the following program print when compiled and run? import java.util.ArrayList; import java.util.List; public class RQ12A10 { public static void main(String[] args) { List<String> strList = new ArrayList<>(); strList.add("Anna"); strList.add("Ada"); strList.add("Ada"); strList.add("Bob"); strList.add("Bob"); strList.add("Adda"); for (int i = 0; i < strList.size(); /* empty */) { if (strList.get(i).length() <= 3) { strList.remove(i); } else { ++i; } } System.out.println(strList); } } Select the one correct answer. The program will not terminate when run. The program will throw a ConcurrentModificationException at runtime. The program will not compile. The program will print [Anna, Adda] The program will throw an IndexOutOfBoundsException at runtime. The program will print [Anna, Ada, Bob, Adda]

The program will print [Anna, Adda] *(The program will print: [Anna, Adda] The for (;;) loop correctly increments the loop variable s that all the elements in the list are traversed. Removing elements using the for (;;) loop does not throw a ConcurrentModificationException at runtime.)*

Module 10: Which statement is true about the following code? interface InterfaceA { void doIt(); } interface InterfaceB extends InterfaceA {} interface InterfaceC extends InterfaceB { void doIt(); boolean equals (Object obj); } class Beta implements InterfaceB { public void doIt() { System.out.print("Jazz|"); } } public class RQ12A999 { public static void main(String[] args) { InterfaceA a = () -> System.out.print("Java|"); //(1) InterfaceB b = () -> System.out.print("Jive|"); //(2) InterfaceC c = () -> System.out.print("Jingle|"); //(3) Object o = a = c; //(4) b = new Beta(); //(5) a.doIt(); //(6) b.doIt(); //(7) c.doIt(); //(8) ((InterfaceA) o) .doIt(); //(9) } } Select the one correct answer. The program will print: Jingle|Jingle|Jazz|Jingle| The program will not compile. The program will throw a ClassCastException. The program will print: Jingle| Jingle| Jingle| Jazz|

The program will print: Jingle|Jazz| Jingle|Jingle| *(The three interfaces are functional interfaces. InterfaceB explicitly provides an abstract method declaration of the public method equals() from the Object class, but such declarations are excluded from the definition of a functional interface. Thus InterfaceB effectively has only one abstract method. A functional interface can be implemented by a concrete class, such as Beta. The function type of the target type in the assignments (1) to (3) is void -> void. The type of the lambda expression in (1) to (3) is also void -> void. The assignments (1) to (3) are legal. The assignment in (4) is legal. Subtype references are assigned to supertype references. References o, a, and c refer to the lambda expression in (3). The assignment in (5) is legal. The reference b has the type InterfaceB, and class Beta implements this interface. (6), (7), and (8) invoke the method doIt(). (6) evaluates the lambda expression in (3), printing Jingle|. (7) invokes the doIt() method on an object of class Beta, printing Jazz|. (8) also evalutes the lambda expression in (3), printing Jingle|. In (9), the reference o is cast down to InterfaceA. The reference o actually refers to a subtype of InterfaceA. The subtype is cast to a supertype, which is allowed, so no ClassCastException is thrown at runtime. Invoking the doIt() method again results in evaluation of the lambda expression in (3), printing Jingle|. Apart from the declarations of the lambda expressions, the rest of the code is "plain vanilla" Java. Note also that the following assignment that defines a lambda expression would not be valid, since the Object class it not a functional interface and therefore cannot provide a target type for the lambda expression: Object obj = () -> System.out.println("Jingle"); // Compile-time error)*

Module 10: What will the following program print when compiled and run? import java.util.ArrayList; import java.util.List; public class RQ12A40 { public static void main(String[] args) { List<String> strList = ArrayList<>(); strList.add("Anna"); strList.add("Ada"); strList.add(null); strList.add("Bob"); strList.add("Bob"); strList.add("Adda"); while(strList.remove("Bob")) ; System.out.println(strList); } } Select the one correct answer. The program will print: [Anna, Ada, Bob, Adda]. The program will not compile. The program will throw a NullPointerException at runtime. The program will print: [Anna, Ada, Adda]. The program will not terminate when run. The program will print: [Anna, Ada, null, Bob, Adda] [Anna, Ada, null, Adda] The program will print: [Anna, Ada, null, Adda].

The program will print: [Anna, Ada, null, Adda]. *(The program will print: [Anna, Ada, null, Adda]. The while loop will execute as long as the remove() method returns true (as long as there is an element with the value "Bob" in the list). The while loop body is the empty statement. The remove() method does not throw an exception if an element value is null, or if it is passed a null value.)*

Module 10: What will the following program print when compiled and run? import java.util.ArrayList; import java.util.List; public class RQ12A20 { public static void main(String[] args) { List<String> strList = new ArrayList<>(); strList.add("Anna"); strList.add("Ada"); strList.add(null); strList.add("Bob"); strList.add("Bob"); strList.add("Adda"); for (int i = 0; i < strList.size(); ++i) { if (strList.get(i).equals("Bob")) { System.out.print(i); } } System.out.println(); } } Select the one correct answer. The program will throw an IndexOutOfBoundsException at runtime. The program will print 34. The program will throw a NullPointerException at runtime. The program will not compile.

The program will throw a NullPointerException at runtime *(The program will throw a NullPointerException at runtime. The element at index 2 has the value null. Calling the equals() method on this element throws the exception.)*

Module 4: Which statement is true? Select the one correct answer. The values of transient fields will not be saved during serialization. Only static methods can access static members. Constructors can be declared as abstract. A subclass of a class with an abstract method must provide an implementation for the abstract method. The initial state of an array object constructed with the statement int[] a = new int[10] will depend on whether the array variable a is a local variable or a field.

The values of transient fields will not be saved during serialization. *(The keyword transient signifies that the fields should not be stored when objects are serialized. Constructors cannot be declared as abstract. When an array object is created, as in the answer The initial state of an array object constructed with the statement int[] a = new int[10] will depend on whether the array variable a is a local variable or a field. the elements in the array object are assigned the default value corresponding to the type of the elements. Whether the reference variable denoting the array object is a local variable or a member variable is irrelevant. Abstract methods from a superclass need not be implemented by a subclass, but the subclass must then be declared as abstract. Static methods can also be accessed in a non-static context -- for example, in instance methods, constructors, and instance initializer blocks.)*

Module 1: How do objects communicate in Java? Select the one correct answer. They communicate by calling each other's instance methods. They communicate by modifying the static variables of each other's classes. They communicate by modifying each other's fields. They communicate by calling static methods of each other's classes.

They communicate by calling each other's instance methods. *(An object communicates with another object by calling an instance method of the other object.)*

Module 1: Given that Thing is a class, how many objects and how many references are created b the following code? Thing item, stuff; item = new Thing(); Thing entity = new Thing(); Select the two correct answers. One reference is created Two references are created Three objects are created one object is created Three references are created Two objects are created

Three references are created Two objects are created *(Two objects and three references are created by the code. Objects are normally created by the new operator. The declaration of a references creates a variable regardless of whether a reference value is assigned to it.)*

Module 3: Which statements, when inserted at (1), will result in a compile-time error? public class ParameterUse { static void main(String[] args) { int a = 0; final int b = 1; int[] c = { 2 }; final int[] d = { 3 }; useArgs(a, b, c, d); } static void useArgs(final int a, int b, final int[] c, int[] d) { // (1) INSERT STATEMENT HERE. } } Select the two correct answers. d[0]++; c[0]++; a++; b++; b = a; c = d;

a++; c = d; *(The correct answers are a++; c = d; A value can be assigned to a final variable only once. A final formal parameter is assigned the value of the actual parameter at method invocation. Within the method body, it is illegal to reassign or modify the value stored in a final parameter. This causes a++; and c = d; to fail. Whether the actual parameter is final does not constrain the client that invoked the method, since the actual parameter values are assigned to the formal parameters.)*

Module 4: Which one of the following class declarations is a valid declaration of a class that cannot be instantiated? Select the one correct answer. abstract class Ghost { abstract haunt() ; } abstract class Ghost { void haunt() {} ; } class Ghost { abstract void haunt() ; } abstract class Ghost { void haunt() ; } abstract Ghost { abstract void haunt() ; }

abstract class Ghost { void haunt() {} ; } *(Any non-final class can be declared as abstract. A class cannot be instantiated if the class is declared as abstract. The declaration of an abstract method cannot provide an implementation. The declaration of a non-abstract method must provide an implementation. If any method in a class is declared as abstract, then the class must be declared as abstract, so class Ghost { abstract void haunt() ; } is invalid. The declaration in abstract class Ghost { void haunt() ; } is invalid since it omits the keyword abstract in the method declaration. The declaration in abstract Ghost { abstract void haunt() ; } is not valid since it omits the keyword class. In abstract class Ghost { abstract haunt() ; } the return type of the method is missing.)*

Module 4: Which one of these is not a legal member declaration within a class? Select the one correct answer. abstract int t; static int a; static final private double PI = 3.14159265358979323846; final Object[] fudge = { null } ; native void sneeze();

abstract int t; *(The declaration abstract int t; is not legal, as variables cannot be declared as abstract. The keywords static and final are valid modifiers for both field and method declarations. The modifiers abstract and native are both valid for methods, but not together. They cannot be specified for fields.)*

Module 3: Given the following declaration, which expression returns the size of the array, assuming that the array reference has been properly initialized? Select the one correct answer. int[] array; array.size array[].size() array[].length array.length array[].length() array[].size array.size() array.length()

array[].length *(array.length is correct. In Java, arrays are objects. Each array object has a public final field named length that stores the size of the array.)*

Module 11: Which expressions, when inserted at (1), will result in the following output: date2 is after date1 import java.time.LocalDate; import java.time.Period; public class RQ11A45 { public static void main(String[] args) { LocalDate date1 = LocalDate.of(2015, 8, 19); LocalDate date2 = LocalDate.of(2015, 10, 23); if ( /*(1) INSERT CODE HERE */ ) { System.out.println("date2 is after date1"); } } } Select the five correct answers. date1.compareTo(date2) < 0 Period.between(date2, date1).isNegative() date2.isBefore(date1) date1.isBefore(date2) date1.until(date2).isNegative() date2.isAfter(date1) date2.until(date1).isNegative() Period.between(date1, date2).isNegative() date1.isAfter(date2) date2.compareTo(date1) < 0

date1.compareTo(date2) < 0 Period.between(date2, date1).isNegative() date1.isBefore(date2) date2.isAfter(date1) date2.until(date1).isNegative() *(The correct answers are: date2.isAfter(date1) date1.isBefore(date2) Period.between(date2, date1).isNegative() date2.until(date1).isNegative() date1.compareTo(date2) < 0 The between() and until() methods return a Period, which can be negative. The isAfter(), isBefore(), between(), and until() methods are strict in the sense that the end date is excluded. The compareTo() method returns 0 if the two dates are equal, a negative value if date1 is less than date2, and a positive value if date1 is greater than date2.)*

Module 4: Which one of the following class declarations is a valid declaration of a class that cannot be extended? Select the one correct answer. abstract class Link { } final class Link { } abstract final class Link { } class Link { } native class Link { }

final class Link { } *(Only a final class cannot be extended. Only methods can be declared as native. A class cannot be declared as both abstract and final.)*

Module 2: Which of the following primitive data types are not integer types? Select the three correct answers. short float boolean byte double

float boolean double *(false is a boolean data type, while float and double are floating-point data types.)*

Module 3: Which statements, when inserted at (1) in the code shown below, will not result in compile-time errors? Select the three correct answers. public class ThisUsage { int planets; static int suns; public void gaze() { int i; // (1) INSERT STATEMENT HERE } } i = this.planets; i = this.suns; this = new ThisUsage(); this.i = 4; this.suns = planets;

i = this.planets; i = this.suns; this.suns = planets; *(i = this.planets; i = this.suns; this.suns = planets; are all valid. Non-static methods have an implicit thisobject reference. The this reference cannot be changed, which eliminates this = new ThisUsage(); as a possible answer. The this reference can be used in a non-static context to refer to both instance and static members. However, it cannot be used to refer to local variables, which means this.i = 4; is not a valid answer.)*

Module 4: The contents of three separate source code files are shown below (separated by hyphens ----). Which import statements, when inserted independently at (1), will make the code compile? // File: Window.javapackage mainpkg.subpkg1;public class Window {}-------------------------------------------------------// File: Window.javapackage mainpkg.subpkg2;public class Window {}-------------------------------------------------------File: Screen.javapackage mainpkg;// (1) INSERT IMPORT STATEMENTS HEREpublic class Screen { private Window win;} Choose the four correct answers. import mainpkg.subpkg2.*; import mainpkg.subpkg1.Window; import mainpkg.subpkg2.Window; import mainpkg.subpkg1.*; import mainpkg.subpkg2.*; import mainpkg.*; import mainpkg.subpkg1.*; import mainpkg.subpkg1.Window; import mainpkg.subpkg2.*; import mainpkg.subpkg1.*; import mainpkg.subpkg2.Window;

import mainpkg.subpkg2.*; import mainpkg.subpkg1.*; import mainpkg.subpkg1.Window; import mainpkg.subpkg2.*; import mainpkg.subpkg1.*; import mainpkg.subpkg2.Window; *(The correct answers are import mainpkg.subpkg1.*; import mainpkg.subpkg2.*; import mainpkg.subpkg1.*;import mainpkg.subpkg2.Window; import mainpkg.subpkg1.Window;import mainpkg.subpkg2.*; import mainpkg.*; is not correct because the import statement imports types from the mainpkg package, but Window is not one of them. import mainpkg.subpkg1.*; is correct because the import statement imports types from the mainpkg.subpkg1 package, and Window is one of them. import mainpkg.subpkg2.*; is correct because the import statement imports types from the mainpkg.subpkg2 package, and Window is one of them. import mainpkg.subpkg1.*; import mainpkg.subpkg2.Window; This is correct; the first import statement is type-import-on-demand and the second import statement is single-type-import. Both import the type Window. The second overrides the first one. import mainpkg.subpkg1.Window; import mainpkg.subpkg2.*; This is correct; the first import statement is single-type-import and the second import statement is type-import-on-demand. Both import the type Window. The first overrides the second one. import mainpkg.subpkg1.*; import mainpkg.subpkg2.*; This is not correct. Both import statements import the type Window, making the import ambiguous. import mainpkg.subpkg1.Window; import mainpkg.subpkg2.Window; This is not correct. Both single-type-import statements import the type Window. The second import statement causes a conflict with the first.)*

Module 4: The contents of two separate source code files are shown below (separated by hyphens ----). Which import statement, when inserted independently at (1), will make the code compile? // File: Window.java package app; public class Window { final static String frame = "Top-frame"; } ------------------------------------------------------- // File: Canvas.java package app; // (1) INSERT IMPORT STATEMENT HERE public class Canvas { private String str = frame; } Select the one correct answer. import app.Window; import app.*; import java.lang.String; import static app.Window.frame; import java.lang.*;

import static app.Window.frame; *(The correct answer is import static app.Window.frame; Both classes are in the same package app, so "import app.*;" and "import app.Window;" are unnecessary. The package java.lang is always imported in all compilation units, so importing that package is unnecessary. "import static app.Window.frame;" is necessary to access the static variable frame in the Window class by its simple name.)*

Module 4: Given the following code: // (1) INSERT ONE IMPORT STATEMENT HERE public class RQ700A20 { public static void main(String[] args) { System.out.println(sqrt(49)); } } Which import statements, when inserted independently at (1), will make the program print 7.0 when the program is compiled and run? Select the two correct answers. import static Math.sqrt; import static java.lang.Math.sqrt; import static Math.*; import static java.lang.Math.sqrt(); import static java.lang.Math.*;

import static java.lang.Math.sqrt; import static java.lang.Math.*; *(The correct answers are: import static java.lang.Math.sqrt; import static java.lang.Math.*; The name of the class must be fully qualified. A parameter list after the method name is not permitted. import static java.lang.Math.sqrt; illustrates single static import and import static java.lang.Math.*; illustrates static import on demand.)*

Module 2: Which integral type in Java has the exact range from -2147483648 (i.e. -231) to 2147483647 (i.e. 231-1), inclusive? Select the one correct answer. char byte short int long

int *(The bit representation of int is 32 bits wide and can hold values in the range -231 through 231-1.)*

Module 3: Which one of the following array declaration statements is not legal? Select the one correct answer. int a[][] = new int[][4]; int a[][] = new int[4][4]; int [][]a = new int[4][4]; int []a[] = new int[4][]; int []a[] = new int [4][4];

int a[][] = new int[][4]; *(int a[][] = new int[][4]; is not a legal declaration. The [] notation can be placed both after the type name and after the variable name in an array declaration. Multidimensional arrays are created by constructing arrays that contain references to other arrays. The expression new int[4][] will create an array of length 4, which can contain references to arrays of int values. The expression new int[4][4] will also create a two-dimensional array, but will in addition create four more one-dimensional arrays, each of length 4 and of the type int[]. References to each of these arrays are stored in the two-dimensional array. The expression int[][4] will not work because the arrays for the dimensions must be created from left to right.)*

Module 5: Given the following declaration: char c = 'A'; What is the simplest way to convert the character value in c to an int? Select the one correct answer. int i = (int) c; int i = Character.getNumericValue(c); int i = c;

int i = c; *(int i = c; is correct. A value of type char can be assigned to a variable of type int. A widening conversion will convert the value to an int.)*

Module 3: Which of these array declaration statements are not legal? Select the two correct answers. int i[][] = { {1, 2}, new int[2] }; int i[] = new int[2] {1, 2}; int[] i[] = { {1, 2}, {1}, {}, {1, 2, 3} }; int i[][] = new int[][] { {1, 2, 3}, {4, 5, 6} }; int i[4] = {1, 2, 3, 4};

int i[] = new int[2] {1, 2}; int i[4] = {1, 2, 3, 4}; *(int i[] = new int[2] {1, 2}; and int i[4] = {1, 2, 3, 4}; are not legal. Notice that array sizes are specified in addition to initialization code. The size of an array is determined implicitly by the initialization code, it is never specified in the declaration of an array reference. The size of an array is always associated with the array instance (on the right-hand side), not the array reference (on the left-hand side).*

Module 1: Which command from the JDK should be used to execute the main() method of a class name SmallProg? Select the one correct answer. java SmallProg.class java SmallProg.main() javac SmallProg java SmallProg java SmallProg.java

java SmallProg *(Java programs are executed by the Java Virtual Machine (JVM). In the JDK, the command java is used to start the execution by the JVM. The java command requires the name of a class that has a valid main() method. The JVM starts the program execution by calling the main() method of the given class. The exact name of the class should be specified, rather than the name of the class file; that is, the .class extension in the class file name should not be specified.)*

Module 1: Which command from the JDK should be used to compile the following source code contained in a file named SmallProg.java? Select the one correct answer. public class SmallProg { public static void main(String[] args) { System.out.println("Good luck!"); } } javac SmallProg.java java SmallProg java SmallProg main java SmallProg.java javac SmallProg

javac SmallProg.java *(The compiler supplied with the JDK is named javac. The names of the sources files to be compiled are listed on the command line after the command javac.)*

Module 3: Given the following code: public class RQ810A40 { static void print(Object... obj) { System.out.println("Object...: " + obj[0]); } public static void main(String[] args) { // (1) INSERT METHOD CALL HERE. } } Which method call, when inserted at (1), will not result in the following output from the program: Object...: 9 Select the one correct answer. print(new Object[] {"9", "1", "1"}); None of these answers are correct. print(new String[] {"9", "1", "1"}); print(new Integer[] {9, 1, 1}); print(new int[] {9, 1, 1}); print(9, 1, 1); print("9", "1", "1");

print(new int[] {9, 1, 1}); *(The correct answer is print(new int[] {9, 1, 1}); In print("9", "1", "1"); and print(9, 1, 1); the arguments are encapsulated as elements in the implicitly created array that is passed to the method, whereas in the correct answer the int array itself is encapsulated as an element n the implicitly created array that is passed to the method. print("9", "1", "1"); print("9", "1", "1"); print(new int[] {9, 1, 1}); are all fixed arity calls. Note that int[] is not a subtype of Object[], and the argument itself is passed without the need of an implicitly created array; that is, these are fixed arity method calls. However, in print(new Integer[] {9, 1, 1}); and print(new String[] {"9", "1", "1"}); the compiler issues a warning that both fixed arity and variable arity method calls are feasible, but chooses fixed arity method calls.)*

Module 9: Given the following class, which of these static initializer blocks can be independently inserted at (1)? public class MyClass { private static int count = 5; static final int STEP = 10; boolean alive; // (1) INSERT STATIC INITIALIZER BLOCK HERE } Select the three correct answers. static { ; } static { STEP = count; } static ; static { alive = true; count = 0; } static { count += STEP; } static { count = 1; }

static { ; } static { count += STEP; } static { count = 1; } *(The correct answers are static { count += STEP; } static { ; } static { count = 1; } The static initializer blocks static { alive = true; count = 0; } and static { STEP = count; } are not legal, since the fields alive and STEP are non-static and final, respectively. static ; is not a syntactically legal static initializer block. The static block in static { ; } is legal but will have no effect, as it executes the empty statement. The static block in static { count = 1; } will change the value of the static field count from 5 to 1.)*

Module 3: Which of the following method declarations are valid declarations? Select the three correct answers. void compute(String... ss, int len) { } void compute(char[] ca, int... is) { } void compute(String... ds) { } void compute(int... is, int i, String... ss) { } void compute(int is...) { } void compute(int... is) { }

void compute(char[] ca, int... is) { } void compute(String... ds) { } void compute(int... is) { } *(The correct answers are: void compute(int... is) { } void compute(String... ds) { } void compute(char[] ca, int... is) { } The ellipses (...) must be specified before the parameter name. Only one variable arity parameter is permitted, and it must be the last parameter in the formal parameter list.)*

Module 3: Which one of these declarations is a valid method declaration? Select the one correct answer. method5(void) { /* ... */ } void method2() { /* ... */ } void method3(void) { /* ... */ } method4() { /* ... */ } void method1 { /* ... */ }

void method2() { /* ... */ } *(void method2() { /* ... */ } is a valid method declaration. Methods must specify a return type or must be declared as void. This makes method4() { /* ... */ } and method5(void) { /* ... */ } invalid. Methods ust specify a list of zero or more comma-separated parameters enclosed by parentheses (). The keyword void cannot be used to specify an empty parameter list. This makes void method1 { /* ... */ } and void method3(void) { /* ... */ } invalid.)*

Module 9: Given the following class, which instance initializer block inserted independently at (1) will allow the class to be compiled? public class FirstClass { static int gap = 10; double length; final boolean active; // (1) INSERT CODE HERE } Select the one correct answer. FirstClass { gap += 5; } { active = (gap > 5); length = 5.5 + gap;} { ; } { gap = 5; length = (active ? 100 : 200) + gap; } instance { active = true; } { length = 4.2; }

{ active = (gap > 5); length = 5.5 + gap;} *(The correct answer is { active = (gap > 5); length = 5.5 + gap;} This class has a blank final boolean instance variable active. This variable must be initialized when an instance is constructed, or else the code will not compile. This also applies to blank final static variables. The keyword static is used to signify that a block is a static initializer block. No keyword is used to signify that a block is an instance initializer block. instance { active = true; } and FirstClass { gap += 5; } are not instance initializer blocks, and the remaining choices fail to initialize the blank final variable active.)*


Kaugnay na mga set ng pag-aaral

19: Essentials of Maternity, Newborn, and Women's Health Nursing 5th Edition Chapter 19

View Set

Alternatives Search, Humane Standards, Housing, Source, and Acclimation and Quarantine

View Set

Medical Terminology: The Nine Regions

View Set

MTA 98-367 Security Fundamentals

View Set

WHH Student Activity Page 117-118

View Set