8.2. Answers to mock exam questions

This section contains answers to all the mock exam questions in section 8.1. Also, each question is preceded by the exam objectives that the question is based on.

[7.2] Develop code that demonstrates the use of polymorphism; including overriding and object type versus reference type

[7.3] Determine when casting is necessary

[8.5] “Recognize common exception classes (such as NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, ClassCastException)”

ME-Q1)

Given the following definition of the classes Animal, Lion, and Jumpable, select the correct combinations of assignments of a variable that don’t result in compilation errors or runtime exceptions (select 2 options).

interface Jumpable {}
class Animal {}
class Lion extends Animal implements Jumpable {}

  1. Jumpable var1 = new Jumpable();
  2. Animal var2 = new Animal();
  3. Lion var3 = new Animal();
  4. Jumpable var4 = new Animal();
  5. Jumpable var5 = new Lion();
  6. Jumpable var6 = (Jumpable)(new Animal());

Answer: b, e

Explanation: Option (a) is incorrect. An interface can’t be instantiated.

Option (c) is incorrect. A reference variable of a derived class can’t be used to refer to an object of its base class.

Option (d) is incorrect. A reference variable of type Jumpable can’t be used to refer to an object of the class Animal because Animal doesn’t implement the interface Jumpable.

Option (f) is incorrect. Although this line of code will compile successfully, it will throw a ClassCastException at runtime. You can explicitly cast any object to an interface, even if it doesn’t implement it to make the code compile. But if the object’s class doesn’t implement the interface, the code will throw a ClassCastException at runtime.

[8.2] Create a try-catch block and determine how exceptions alter normal program flow

ME-Q2)

Given the following code, which option, if used to replace /*INSERT CODE HERE*/, will make the code print 1? (Select 1 option.)

try {
    String[][] names = {{"Andre", "Mike"}, null, {"Pedro"}};
    System.out.println (names[2][1].substring(0, 2));
} catch (/*INSERT CODE HERE*/) {
    System.out.println(1);
}

  1. IndexPositionException e
  2. NullPointerException e
  3. ArrayIndexOutOfBoundsException e
  4. ArrayOutOfBoundsException e

Answer: c

Explanation: Options (a) and (d) are incorrect because the Java API doesn’t define any exception classes with these names.

Here’s a list of the array values that are initialized by the code in this question:

names[0][0] = "Andre"
names[0][1] = "Mike"
names[1] = null
names[2][0] = "Pedro"

Because the array position [2][1] isn’t defined, any attempt to access it will throw an ArrayIndexOutOfBoundsException.

An attempt to access any position of the second array—that is, names[1][0]—will throw a NullPointerException because names[1] is set to null.

[8.2] Create a try-catch block and determine how exceptions alter normal program flow

ME-Q3)

What is the output of the following code? (Select 1 option.)

public static void main(String[] args) {
    int a = 10; String name = null;
    try {
        a = name.length();                   //line1
        a++;                                 //line2
    } catch (NullPointerException e){
        ++a;
        return;
    } catch (RuntimeException e){
        a--;
        return;
    } finally {
        System.out.println(a);
    }
}

  1. 5
  2. 6
  3. 10
  4. 11
  5. 12
  6. Compilation error
  7. No output
  8. Runtime exception

Answer: d

Explanation: Because the variable name isn’t assigned a value, you can’t call an instance method (length()) using it. The following line of code will throw a NullPointerException:

name.length();

When an exception is thrown, the control is transferred to the exception handler, skipping the execution of the remaining lines of code in the try block. So the code (a++) doesn’t execute at the comment marked with line2.

The code defines an exception handler for both NullPointerException and Runtime-Exception. When an exception is thrown, more than one exception handler won’t execute. In this case, the exception handler for NullPointerException will execute because it’s more specific and it’s defined earlier than RuntimeException. The exception handler for NullPointerException includes the following code:

++a;
return;

The preceding code increments the value of the variable a by 1; and before it exits the method main, due to the call to the statement return, it executes the finally block, outputting the value 11. A finally block executes even if the catch block includes a return statement.

[3.4] Use a switch statement

ME-Q4)

Given the following class definition,

class Student { int marks = 10; }

what is the output of the following code? (Select 1 option.)

class Result {
    public static void main(String... args) {
        Student s = new Student();
        switch (s.marks) {
            default: System.out.println("100");
            case 10: System.out.println("10");
            case 98: System.out.println("98");
        }
    }
}


  1. 100
    10
    98

  2. 10
    98

  3. 100

  4. 10

Answer: b

Explanation: The default case executes only if no matching values are found. In this case, a matching value of 10 is found and the case label prints 10. Because a break statement doesn’t terminate this case label, the code execution continues and executes the remaining statements within the switch block, until a break statement terminates it or it ends.

[7.4] Use super and this to access objects and constructors

ME-Q5)

Given the following code, which code can be used to create and initialize an object of the class ColorPencil? (Select 2 options.)

class Pencil {}
class ColorPencil extends Pencil {
    String color;
    ColorPencil(String color) {this.color = color;}
}

  1. ColorPencil var1 = new ColorPencil();
  2. ColorPencil var2 = new ColorPencil(RED);
  3. ColorPencil var3 = new ColorPencil("RED");
  4. Pencil var4 = new ColorPencil("BLUE");

Answer: c, d

Explanation: Option (a) is incorrect because new ColorPencil() tries to invoke the no-argument constructor of the class ColorPencil, which isn’t defined in the class ColorPencil.

Option (b) is incorrect because new ColorPencil(RED) tries to pass a variable RED, which isn’t defined in the code.

[2.3] Know how to read or write to object fields

ME-Q6)

What is the output of the following code? (Select 1 option.)

class Doctor {
    protected int age;
    protected void setAge(int val) { age = val; }
    protected int getAge() { return age; }
}
class Surgeon extends Doctor {
    Surgeon(String val) {
        specialization = val;
    }
    String specialization;
    String getSpecialization() { return specialization; }
}
class Hospital {
    public static void main(String args[]) {
        Surgeon s1 = new Surgeon("Liver");

        Surgeon s2 = new Surgeon("Heart");
        s1.age = 45;
        System.out.println(s1.age + s2.getSpecialization());
        System.out.println(s2.age + s1.getSpecialization());
    }
}


  1. 45Heart
    0Liver

  2. 45Liver
    0Heart

  3. 45Liver
    45Heart

  4. 45Heart
    45Heart
  5. Class fails to compile.

Answer: a

Explanation: The constructor of the class Surgeon assigns the values "Liver" and "Heart" to the variable specialization of objects s1 and s2. The variable age is protected- in the class Doctor. Also, the class Surgeon extends the class Doctor. Hence, the variable age is accessible to reference variables s1 and s2. The code assigns a value of 45 to the member variable age of reference variable s1. The variable age of reference variable s2 is initialized to the default value of an int, which is 0. Hence, the code prints the values mentioned in option (a).

[3.1] Use Java operators; including parentheses to override operator precedence

ME-Q7)

What is the output of the following code? (Select 1 option.)

class RocketScience {
    public static void main(String args[]) {
        int a = 0;
        while (a == a++) {
            a++;
            System.out.println(a);
        }
    }
}

  1. The while loop won’t execute; nothing will be printed.
  2. The while loop will execute indefinitely, printing all numbers, starting from 1.
  3. The while loop will execute indefinitely, printing all even numbers, starting from 0.
  4. The while loop will execute indefinitely, printing all even numbers, starting from 2.
  5. The while loop will execute indefinitely, printing all odd numbers, starting from 1.
  6. The while loop will execute indefinitely, printing all odd numbers, starting from 3.

Answer: d

Explanation: The while loop will execute indefinitely because the condition a == a++ will always evaluate to true. The postfix unary operator will increment the value of the variable a after it’s used in the comparison expression. a++ within the loop body will increment the value of a by 1. Hence, the value of a increments by 2 in a single loop.

[1.4] Import other Java packages to make them accessible in your code

ME-Q8)

Given the following statements,

  • com.ejava is a package
  • class Person is defined in package com.ejava
  • class Course is defined in package com.ejava

which of the following options correctly import the classes Person and Course in the class MyEJava? (Select 3 options.)


  1. import com.ejava.*;
    class MyEJava {}

  2. import com.ejava;
    class MyEJava {}

  3. import com.ejava.Person;
    import com.ejava.Course;
    class MyEJava {}

  4. import com.ejava.Person;
    import com.ejava.*;
    class MyEJava {}

Answer: a, c, d

Explanation: Option (a) is correct. The statement import com.ejava.*; imports all the public members of the package com.ejava in the class MyEJava.

Option (b) is incorrect. Because com.ejava is a package, to import all the classes defined in this package, the package name should be followed by .*:

import com.ejava.*;

Option (c) is correct. It uses two separate import statements to import each of the classes Person and Course individually, which is correct.

Option (d) is also correct. The first import statement imports only the class Person in MyClass. But the second import statement imports both the Person and Course classes from the package com.ejava. You can import the same class more than once in a Java class with no issues. This code is correct.

In Java, the import statement makes the imported class visible to the Java compiler, allowing it to be referred to by the class that’s importing it. In Java, the import statement doesn’t embed the imported class in the target class.

[6.4] Apply access modifiers

ME-Q9)

Given that the following classes Animal and Forest are defined in the same package, examine the code and select the correct statements (select 2 options).

line1>    class Animal {
line2>        public void printKing() {
line3>            System.out.println("Lion");
line4>        }
line5>    }

line6>    class Forest {
line7>        public static void main(String... args) {
line8>            Animal anAnimal = new Animal();
line9>            anAnimal.printKing();
line10>        }
line11>    }

  1. The class Forest prints Lion.
  2. If the code on line 2 is changed as follows, the class Forest will print Lion:

    private void printKing() {
  3. If the code on line 2 is changed as follows, the class Forest will print Lion:

    void printKing() {
  4. If the code on line 2 is changed as follows, the class Forest will print Lion:

    default void printKing() {

Answer: a, c

Explanation: Option (a) is correct. The code will compile successfully and print Lion.

Option (b) is incorrect. The code won’t compile if the access modifier of the method printKing is changed to private. private members of a class can’t be accessed outside the class.

Option (c) is correct. The classes Animal and Forest are defined in the same package, so changing the access modifier of the method printKing to default access will still make it accessible in the class Forest. The class will compile successfully and print Lion.

Option (d) is incorrect. “default” isn’t a valid access modifier or keyword in Java. In Java, the default accessibility is marked by the absence of any explicit access modifier. This code will fail to compile.

[1.3] Create executable Java applications with a main method; run a Java program from the command line; including console output.

ME-Q10)

Given the following code,

class MainMethod {
    public static void main(String... args) {
        System.out.println(args[0]+":"+ args[2]);
    }
}

what’s its output if it’s executed using the following command? (Select 1 option.)

java MainMethod 1+2 2*3 4-3 5+1

  1. java:1+2
  2. java:3
  3. MainMethod:2*3
  4. MainMethod:6
  5. 1+2:2*3
  6. 3:3
  7. 6
  8. 1+2:4-3
  9. 31
  10. 4

Answer: h

Explanation: This question tests you on multiple points.

  1. The arguments that are passed on to the main method—The keyword java and the name of the class (MainMethod) aren’t passed as arguments to the main method. The arguments following the class name are passed to the main method. In this case, four method arguments are passed to the main method, as follows:

    args[0]: 1+2
    args[1]: 2*3
    args[2]: 4-3
    args[3]: 5+1
  2. The type of the arguments that are passed to the main method—The main method accepts arguments of type String. All the numeric expressions—1+2, 2*3, 5+1, and 4-3—are passed as literal String values. These won’t be evaluated when you try to print their values. Hence, args[0] won’t be printed as 3. It will be printed as 1+2.
  3. + operations with String array elements—Because the array passed to the main method contains all the String values, using the + operand with its individual values will concatenate its values. It won’t add the values, if they are numeric expressions. Hence, "1+2"+"4-3" won’t evaluate to 31 or 4.

[2.2] Differentiate between object reference variables and primitive variables

[9.5] Write a simple Lambda expression that consumes a Lambda Predicate expression

ME-Q11)

What is the output of the following code? (Select 1 option.)

interface Moveable {
    int move(int distance);
}
class Person {
    static int MIN_DISTANCE = 5;
    int age;
    float height;
    boolean result;
    String name;
}
public class EJava {
    public static void main(String arguments[]) {
        Person person = new Person();
        Moveable moveable = (x) -> Person.MIN_DISTANCE + x;
        System.out.println(person.name + person.height + person.result
                                       + person.age + moveable.move(20));
    }
}

  1. null0.0false025
  2. null0false025
  3. null0.0ffalse025
  4. 0.0false025
  5. 0false025
  6. 0.0ffalse025
  7. null0.0true025
  8. 0true025
  9. 0.0ftrue025
  10. Compilation error
  11. Runtime exception

Answer: a

Explanation: The instance variables of a class are all assigned default values if no explicit value is assigned to them. Here are the default values of the primitive data types and the objects:

  • char -> u0000
  • byte, short, int -> 0
  • long -> 0L
  • float-> 0.0f
  • double -> 0.0d
  • boolean -> false
  • objects -> null

Moveable is a functional interface. The example code defines the code to execute for its functional method move by using the Lambda expression (x) -> Person.MIN _DISTANCE + x.

Calling moveable.move(20) passes 20 as an argument to the method move. It returns 25 (the sum of Person.MIN_DISTANCE, which is 5, and the method argument 20).

[7.3] Determine when casting is necessary

ME-Q12)

Given the following code, which option, if used to replace /* INSERT CODE HERE */, will make the code print the value of the variable pagesPerMin? (Select 1 option.)

class Printer {
    int inkLevel;
}
class LaserPrinter extends Printer {
    int pagesPerMin;
    public static void main(String args[]) {
        Printer myPrinter = new LaserPrinter();
        System.out.println(/* INSERT CODE HERE */);
    }
}

  1. (LaserPrinter)myPrinter.pagesPerMin
  2. myPrinter.pagesPerMin
  3. LaserPrinter.myPrinter.pagesPerMin
  4. ((LaserPrinter)myPrinter).pagesPerMin

Answer: d

Explanation: Option (a) is incorrect because (LaserPrinter) tries to cast myPrinter.pagesPerMin (variable of primitive type int) to LaserPrinter, which is incorrect. This code won’t compile.

Option (b) is incorrect. The type of reference variable myPrinter is Printer. myPrinter refers to an object of the class LaserPrinter, which extends the class Printer. A reference variable of the base class can’t access the variables and methods defined in its subclass without an explicit cast.

Option (c) is incorrect. LaserPrinter.myPrinter treats LaserPrinter as a variable, although no variable with this name exists in the question’s code. This code fails to compile.

[2.1] Declare and initialize variables (including casting of primitive data types)

[9.5] Write a simple Lambda expression that consumes a Lambda Predicate expression

ME-Q13)

What is the output of the following code? (Select 1 option.)

interface Keys {
    String keypad(String region, int keys);
}
public class Handset {
    public static void main(String... args) {
        double price;
        String model;
        Keys varKeys = (region, keys) ->
                       {if (keys >= 32)
                        return region; else return "default";};
        System.out.println(model + price + varKeys.keypad("AB", 32));
    }
}

  1. null0AB
  2. null0.0AB
  3. null0default
  4. null0.0default
  5. 0
  6. 0.0
  7. Compilation error

Answer: g

Explanation: The local variables (variables that are declared within a method) aren’t initialized with their default values. If you try to print the value of a local variable before initializing it, the code won’t compile.

The Lambda expression used in the code is correct.

[3.1] Use Java operators; including parentheses to override operator precedence

ME-Q14)

What is the output of the following code? (Select 1 option.)

public class Sales {
    public static void main(String args[]) {
        int salesPhone = 1;
        System.out.println(salesPhone++ + ++salesPhone +
                                                       ++salesPhone);
    }
}

  1. 5
  2. 6
  3. 8
  4. 9

Answer: c

Explanation: Understanding the following rules will enable you to answer this question correctly:

  • An arithmetic expression is evaluated from left to right.
  • When an expression uses the unary increment operator (++) in postfix notation, its value increments just after its original value is used in an expression.
  • When an expression uses the unary increment operator (++) in prefix notation, its value increments just before its value is used in an expression.

The initial value of the variable salesPhone is 1. Let’s evaluate the result of the arithmetic expression salesPhone++ + ++salesPhone + ++salesPhone step by step:

  1. The first occurrence of salesPhone uses ++ in postfix notation, so its value is used in the expression before it’s incremented by 1. This means that the expression evaluates to

    1 + ++salesPhone + ++salesPhone
  2. Note that the previous usage of ++ in postfix increments has already incremented the value of salesPhone to 2. The second occurrence of salesPhone uses ++ in prefix notation, so its value is used in the expression after it’s incremented by 1, to 3. This means that the expression evaluates to

    1 + 3 + ++salesPhone
  3. The third occurrence of salesPhone again uses ++ in prefix notation, so its value is used in the expression after it’s incremented by 1, to 4. This means that the expression evaluates to

    1 + 3 + 4
    The preceding expression evaluates to 8.

[1.2] Define the structure of a Java class

[1.4] Import other Java packages to make them accessible in your code

ME-Q15)

Which of the following options defines the correct structure of a Java class that compiles successfully? (Select 1 option.)


  1. package com.ejava.guru;
    package com.ejava.oracle;
    class MyClass {
        int age = /* 25 */ 74;
    }

  2. import com.ejava.guru.*;
    import com.ejava.oracle.*;
    package com.ejava;
    class MyClass {
        String name = "e" + "Ja /*va*/ v";
    }

  3. class MyClass {
        import com.ejava.guru.*;
    }

  4. class MyClass {
        int abc;
        String course = //this is a comment
                     "eJava";
    }
  5. None of the above

Answer: d

Explanation: This question requires you to know

  • Correct syntax and usage of comments
  • Usage of import and package statements

None of the code fails to compile due to the end-of-line or multiline comments. All the following lines of code are valid:

int age = /* 25 */ 74;
String name = "e" + "Ja /*va*/ v";
String course = //this is a comment
                 "eJava";

In the preceding code, the variable age is assigned an integer value 74, the variable name is assigned a string value "eJa /*va*/ v", and course is assigned a string value "eJava". A multiline comment delimiter is ignored if put inside a string definition. Let’s see how all the options perform on the usage of package and import statements:

Option (a) is incorrect. A class can’t define more than one package statement.

Option (b) is incorrect. Although a class can import multiple packages in a class, the package statement must be placed before the import statement.

Option (c) is incorrect. A class can’t define an import statement within its class body. The import statement appears before the class body.

Option (d) is correct. In the absence of any package information, this class becomes part of the default package.

[3.1] Use Java operators; including parentheses to override operator precedence

ME-Q16)

What is the output of the following code? (Select 1 option.)

class OpPre {
    public static void main(String... args) {
        int x = 10;
        int y = 20;
        int z = 30;
        if (x+y%z > (x+(-y)*(-z))) {
            System.out.println(x + y + z);
        }
    }
}

  1. 60
  2. 59
  3. 61
  4. No output.
  5. The code fails to compile.

Answer: d

Explanation: x+y%z evaluates to 30; (x+(y%z))and (x+(-y)*(-z)) evaluate to 610. The if condition returns false and the line of code that prints the sum of x, y, and z doesn’t execute. Hence, the code doesn’t provide any output.

[1.1] Define the scope of variables

[6.2] Apply the static keyword to methods and fields

ME-Q17)

Select the most appropriate definition of the variable name and the line number on which it should be declared so that the following code compiles successfully (choose 1 option).

class EJava {
    // LINE 1
    public EJava() {
        System.out.println(name);
    }
    void calc() {
        // LINE 2
        if (8 > 2) {
            System.out.println(name);
        }
    }
    public static void main(String... args) {
        // LINE 3
        System.out.println(name);
    }
}

  1. Define static String name; on line 1.
  2. Define String name; on line 1.
  3. Define String name; on line 2.
  4. Define String name; on line 3.

Answer: a

Explanation: The variable name must be accessible in the instance method calc, the class constructor, and the static method main. A non-static variable can’t be accessed by a static method. Hence, the only appropriate option is to define a static variable name that can be accessed by all: the constructor of the class EJava and the methods calc and main.

[2.4] Explain an Object’s Lifecycle (creation, “dereference by reassignment” and garbage collection)

ME-Q18)

Examine the following code and select the correct statement (choose 1 option).

line1>    class Emp {
line2>        Emp mgr = new Emp();
line3>    }

line4>    class Office {
line5>        public static void main(String args[]) {
line6>            Emp e = null;
line7>            e = new Emp();
line8>            e = null;
line9>        }
line10>    }

  1. The object referred to by object e is eligible for garbage collection on line 8.
  2. The object referred to by object e is eligible for garbage collection on line 9.
  3. The object referred to by object e isn’t eligible for garbage collection because its member variable mgr isn’t set to null.
  4. The code throws a runtime exception and the code execution never reaches line 8 or line 9.

Answer: d

Explanation: The code throws java.lang.StackOverflowError at runtime. Line 7 creates an instance of class Emp. Creation of an object of the class Emp requires the creation of an instance variable mgr and its initialization with an object of the same class. As you can see, the Emp object creation calls itself recursively (without an exit condition), resulting in a java.lang.StackOverflowError.

[2.5] Develop code that uses wrapper classes such as Boolean, Double, and Integer.

[6.1] Create methods with arguments and return values; including overloaded methods

ME-Q19)

Given the following,

long result;

which options are correct declarations of methods that accept two String arguments and an int argument and whose return value can be assigned to the variable result? (Select 3 options.)

  1. Short myMethod1(String str1, int str2, String str3)
  2. Int myMethod2(String val1, int val2, String val3)
  3. Byte myMethod3(String str1, str2, int a)
  4. Float myMethod4(String val1, val2, int val3)
  5. Long myMethod5(int str2, String str3, String str1)
  6. Long myMethod6(String... val1, int val2)
  7. Short myMethod7(int val1, String... val2)

Answer: a, e, g

Explanation: The placement of the type of method parameters and the name of the method parameters doesn’t matter. You can accept two String variables and then an int variable or a String variable followed by int and again a String. The name of an int variable can be str2. As long as the names are valid identifiers, any name is acceptable. The return type of the method must be assignable to a variable of type long.

Option (a) is correct. The value of a Short instance can be assigned to a variable of the primitive type long.

Option (b) is incorrect. It won’t compile because Int is not defined in the Java API. The correct wrapper class name for the int data type is Integer.

Options (c) and (d) are incorrect. Unlike the declaration of multiple variables, which can be preceded by a single occurrence of their data type, each and every method argument must be preceded by its type. The declaration of the following variables is valid:

int aa, bb;

But the declaration of the method parameters in the following declaration isn’t:

Byte myMethod3(String str1, str2, int a) { /*code*/ }

Option (e) is correct. The value of a Long instance can be assigned to a variable of primitive type long.

Option (f) won’t compile. If varargs is used to define method parameters, it must be the last one.

Option (g) is correct. The method parameter val2, a variable argument, can accept two String arguments. Also, the return value of method7(), a Short, can be assigned to a variable of type long.

[4.1] Declare, instantiate, initialize, and use a one-dimensional array

ME-Q20)

Which of the following will compile successfully? (Select 3 options.)

  1. int eArr1[] = {10, 23, 10, 2};
  2. int[] eArr2 = new int[10];
  3. int[] eArr3 = new int[] {};
  4. int[] eArr4 = new int[10] {};
  5. int eArr5[] = new int[2] {10, 20};

Answer: a, b, c

Explanation: Option (d) is incorrect because it defines the size of the array while using {}, which isn’t allowed. Both of the following lines of code are correct:

int[] eArr4 = new int[10];
int[] eArr4 = new int[]{};

Option (e) is incorrect because it’s invalid to specify the size of the array within the square brackets when you’re declaring, instantiating, and initializing an array in a single line of code.

[6.1] Create methods with arguments and return values; including overloaded methods

[9.2] Create and manipulate strings

ME-Q21)

Assume that Oracle has asked you to create a method that returns the concatenated value of two String objects. Which of the following methods can accomplish this job? (Select 2 options.)


  1. public String add(String 1, String 2) {
        return str1 + str2;
    }

  2. private String add(String s1, String s2) {
        return s1.concat(s2);
    }

  3. protected String add(String value1, String value2) {
        return value2.append(value2);
    }

  4. String subtract(String first, String second) {
        return first.concat(second.substring(0));
    }

Answer: b, d

Explanation: Option (a) is incorrect. This method defines method parameters with invalid identifier names. Identifiers can’t start with a digit.

Option (b) is correct. The method requirements don’t talk about the access modifier of the required method. It can have any accessibility.

Option (c) is incorrect because the class String doesn’t define any append method.

Option (d) is correct. Even though the name of the method—subtract—isn’t an appropriate name for a method that tries to concatenate two values, it does accomplish the required job.

[3.3] Create if and if/else and ternary constructs

[5.2] Create and use for loops including the enhanced for loop

[5.5] Use break and continue

ME-Q22)

Given the following,

int ctr = 10;
char[] arrC1 = new char[]{'P','a','u','l'};
char[] arrC2 = {'H','a','r','r','y'};
//INSERT CODE HERE
System.out.println(ctr);

which options, when inserted at //INSERT CODE HERE, will output 14? (Choose 2 options.)


  1. for (char c1 : arrC1) {
        for (char c2 : arrC2) {
            if (c2 == 'a') break;
            ++ctr;
        }
    }

  2. for (char c1 : arrC1)
        for (char c2 : arrC2) {
            if (c2 == 'a') break;
            ++ctr;
        }

  3. for (char c1 : arrC1)
        for (char c2 : arrC2)
            if (c2 == 'a') break;
            ++ctr;

  4. for (char c1 : arrC1) {
        for (char c2 : arrC2) {
            if (c2 == 'a') continue;
            ++ctr;
        }
    }

Answer: a, b

Explanation: Options (a) and (b) differ only in the usage of {} for the outer for construct. You can use {} to group the statements to execute for iteration constructs like do, do-while, and for. {} are also used with conditional constructs like switch and if-else.

The initial value of the variable ctr is 10. The size of array arrC1 is 4 and the size of array arrC2 is 5 with 'a' at the second position. The outer loop executes four times. Because the second character referred to by arrC2 is 'a', the inner loop will increment the value of variable ctr for its first element. The inner loop won’t execute ++ctr for its second element because c2=='a' returns true and the break statement, and exits the inner loop. The inner loop increments the value ctr four times, incrementing its value to 14.

Option (c) is incorrect. Because the inner for loop doesn’t use {} to group the lines of code that must execute for it, the code ++ctr isn’t a part of the inner for loop.

Option (d) is incorrect. The code ++ctr just executes once, after the completion of the outer and inner for loops, because it isn’t a part of the looping constructs.

[6.1] Create methods with arguments and return values; including overloaded methods

ME-Q23)

Given the following definitions of the class ChemistryBook, select the statements that are correct individually (choose 2 options):

import java.util.ArrayList;
class ChemistryBook {
    public void read() {}                //METHOD1
    public String read() { return null; }     //METHOD2
    ArrayList read(int a) { return null; }     //METHOD3
}

  1. Methods marked with //METHOD1 and //METHOD2 are correctly overloaded methods.
  2. Methods marked with //METHOD2 and //METHOD3 are correctly overloaded methods.
  3. Methods marked with //METHOD1 and //METHOD3 are correctly overloaded methods.
  4. All the methods—methods marked with //METHOD1, //METHOD2, and //METHOD3—are correctly overloaded methods.

Answer: b, c

Explanation: Options (a) and (d) are incorrect because the methods read marked with //METHOD1 and //METHOD2 differ only in their return types, void and String. Overloaded methods can’t be defined with only a change in their return types; hence, these methods don’t qualify as correctly overloaded methods.

Note that the presence of methods marked with //METHOD1 and //METHOD2 together will cause a compilation error.

[6.2] Apply the static keyword to methods and fields

[6.3] Create and overload constructors; including impact on default constructors

[6.4] Apply access modifiers

ME-Q24)

Given the following,

final class Home {
    String name;
    int rooms;
    //INSERT CONSTRUCTOR HERE
}

which options, when inserted at //INSERT CONSTRUCTOR HERE, will define valid overloaded constructors for the class Home? (Choose 3 options.)

  1. Home() {}
  2. Float Home() {}
  3. protected Home(int rooms) {}
  4. final Home() {}
  5. private Home(long name) {}
  6. float Home(int rooms, String name) {}
  7. static Home() {}

Answer: a, c, e

Explanation: A constructor must not define an explicit return type. It you use it to do so, it’s no longer a constructor. A constructor can be defined using any access level—private, default, protected, and public—irrespective of the access level that’s used to declare the class.

Options (b) and (f) are incorrect because they define explicit return types: Float or float. The code in these options defines a method with the name Home, not constructors.

Options (d) and (g) are incorrect. The code won’t compile because a constructor can’t be defined using non-access modifiers static, abstract, or final.

[3.3] Create if and if/else and ternary constructs

[5.2] Create and use for loops including the enhanced for loop

[5.5] Use break and continue

ME-Q25)

Given the following code, which option, if used to replace //INSERT CODE HERE, will make the code print numbers that are completely divisible by 14? (Select 1 option.)

for (int ctr = 2; ctr <= 30; ++ctr) {
    if (ctr % 7 != 0)
        //INSERT CODE HERE
    if (ctr % 14 == 0)
        System.out.println(ctr);
}

  1. continue;
  2. exit;
  3. break;
  4. end;

Answer: a

Explanation: Options (b) and (d) are incorrect because exit and end aren’t valid statements in Java.

Option (c) is incorrect. Using break will terminate the for loop for the first iteration of the for loop so that no output is printed.

[2.1] Declare and initialize variables (including casting of primitive data types)

[9.5] Write a simple Lambda expression that consumes a Lambda Predicate expression

ME-Q26)

What is the output of the following code? (Select 1 option.)

import java.util.function.Predicate;
public class MyCalendar {
    public static void main(String arguments[]) {
        Season season1 = new Season();
        season1.name = "Spring";

        Season season2 = new Season();
        season2.name = "Autumn";

        Predicate<String> aSeason = (s) -> s == "Summer" ?
                                season1.name : season2.name;

        season1 = season2;
        System.out.println(season1.name);
        System.out.println(season2.name);
        System.out.println(aSeason.test(new String("Summer")));
    }
}
class Season {
    String name;
}


  1. String
    Autumn
    false

  2. Spring
    String
    false

  3. Autumn
    Autumn
    false

  4. Autumn
    String
    true
  5. Compilation error
  6. Runtime exception

Answer: e

Explanation: The return type of the functional method test in the functional interface Predicate is boolean. The following Lambda expression is trying to return a String value and so the code fails compilation:

Predicate<String> aSeason = (s) -> s == "Summer" ?
                           season1.name : season2.name;

This question also covers another important topic: multiple variable references can refer to the same instances. Let’s assume that you modify the preceding Lambda expression as follows:

Predicate<String> aSeason = (s) -> s == "Summer";

In this case, the code will output the following:

Autumn
Autumn
false

This is because multiple variable references can point to the same object. The following lines of code define a reference variable season1, which refers to an object that has the value of its instance variable (name) set to Spring:

Season season1 = new Season();
season1.name = "Spring";

The following lines of code define a reference variable season2, which refers to an object that has the value of its instance variable (name) set to Autumn:

Season season2 = new Season();
season2.name = "Autumn";

The following line of code reinitializes the reference variable season1 and assigns it to the object referred to by the variable season2:

season1 = season2;

Now the variable season1 refers to the object that’s also referred to by the variable season2. Both of these variables refer to the same object—the one that has the value of the instance variable set to Autumn. Hence, the output of the modified code is as follows:

Autumn
Autumn
false

A quick reminder for the reason for the preceding output: a String object with the value "Summer", created with the new operator, is never pooled by the JVM. Here, such an instance is compared to the pooled "Summer" instance through the == operator.

[6.3] Create and overload constructors; including impact on default constructors

ME-Q27)

What is true about the following code? (Select 1 option.)

class Shoe {}
class Boot extends Shoe {}
class ShoeFactory {
    ShoeFactory(Boot val) {
        System.out.println("boot");
    }
    ShoeFactory(Shoe val) {
        System.out.println("shoe");
    }
}

  1. The class ShoeFactory has a total of two overloaded constructors.
  2. The class ShoeFactory has three overloaded constructors, two user-defined constructors, and one default constructor.
  3. The class ShoeFactory will fail to compile.
  4. The addition of the following constructor will increment the number of constructors of the class ShoeFactory to 3:

    private ShoeFactory (Shoe arg) {}

Answer: a

Explanation: Java accepts changes in the objects of base-derived classes as a sole criterion to define overloaded constructors and methods.

Option (b) is incorrect because Java doesn’t generate a default constructor for a class that has already defined a constructor.

Option (c) is incorrect. All classes defined for this example compile successfully.

Option (d) is incorrect. The class ShoeFactory already defines a constructor that accepts a method argument of type Shoe. You can’t overload a constructor with a mere change in its access modifier.

[7.4] Use super and this to access objects and constructors

ME-Q28)

Given the following definitions of the classes ColorPencil and TestColor, which option, if used to replace //INSERT CODE HERE, will initialize the instance variable color of the reference variable myPencil with the String literal value "RED"? (Select 1 option.)

class ColorPencil {
    String color;
    ColorPencil(String color) {
        //INSERT CODE HERE
    }
}
class TestColor {
    ColorPencil myPencil = new ColorPencil("RED");
}

  1. this.color = color;
  2. color = color;
  3. color = RED;
  4. this.color = RED;

Answer: a

Explanation: Option (b) is incorrect. This line of code will assign the value of the method parameter to itself. The constructor of the class ColorPencil defines a method parameter with the same name as its instance variable, color. To access an instance variable in the constructor, it must be prefixed with the keyword this, or it will refer to the method parameter color.

Options (c) and (d) are incorrect. They try to access the value of the variable RED, which isn’t defined in the code.

[2.3] Know how to read or write to object fields

ME-Q29)

What is the output of the following code? (Select 1 option.)

class EJavaCourse {
    String courseName = "Java";
}
class University {
    public static void main(String args[]) {
        EJavaCourse courses[] = { new EJavaCourse(), new EJavaCourse() };
        courses[0].courseName = "OCA";
        for (EJavaCourse c : courses) c = new EJavaCourse();
        for (EJavaCourse c : courses) System.out.println(c.courseName);
    }
}


  1. Java
    Java

  2. OCA
    Java

  3. OCA
    OCA
  4. None of the above

Answer: b

Explanation: This question tests you on multiple concepts: how to read from and write to object fields, how to use arrays, the enhanced for loop, and assigning a value to a loop variable.

The code defines an array of the class EJavaCourse with two elements. The default value of the variable courseNameJava—is assigned to each of these two elements. courses[0].courseName = "OCA" changes the value courseName for the object stored at array position 0. c = new EJavaCourse() assigns a new object to the loop variable c. This assignment doesn’t reassign new objects to the array reference variables. System-.out.println(c.courseName) prints the name of the courseName of the objects initially stored by the array, using the loop variable c.

The loop variable in the enhanced for loop refers to a copy of the array or list element. If you modify the state of the loop variable, the modified object state will be reflected in the array. But if you assign a new object to the loop variable, it won’t be reflected in the list or the array that’s being iterated. You can compare this behavior of the enhanced for loop variable with the behavior of object references passed as arguments to a method.

[6.2] Apply the static keyword to methods and fields

[7.2] Develop code that demonstrates the use of polymorphism; including overriding and object type versus reference type

ME-Q30)

What is the output of the following code? (Select 1 option.)

class Phone {
    static void call() {
        System.out.println("Call-Phone");
    }
}
class SmartPhone extends Phone{
    static void call() {
        System.out.println("Call-SmartPhone");
    }
}
class TestPhones {
    public static void main(String... args) {
        Phone phone = new Phone();
        Phone smartPhone = new SmartPhone();
        phone.call();
        smartPhone.call();
    }
}


  1. Call-Phone
    Call-Phone

  2. Call-Phone
    Call-SmartPhone

  3. Call-Phone
    null

  4. null
    Call-SmartPhone

Answer: a

Explanation: Invocation of a static method is tied to the type of the reference variable and doesn’t depend on the type of the object that’s assigned to the reference variable. The static method belongs to a class, not to its objects. Reexamine the following code:

Phone smartPhone = new SmartPhone();
smartPhone.call();

In the preceding code, the type of the reference variable smartPhone is Phone. Because call is a static method, smartPhone.call() calls the method call defined in the class Phone.

[8.1] Differentiate among checked exceptions, unchecked exceptions, and Errors

ME-Q31)

Given the following code, which of the following statements are true? (Select 3 options.)

class MyExam {
    void question() {
        try {
            question();
        } catch (StackOverflowError e) {
            System.out.println("caught");
        }
    }
    public static void main(String args[]) {
        new MyExam().question();
    }
}

  1. The code will print caught.
  2. The code won’t print caught.
  3. The code would print caught if StackOverflowError were a runtime exception.
  4. The code would print caught if StackOverflowError were a checked exception.
  5. The code would print caught if question() throws the exception NullPointer-Exception.

Answer: a, c, d

Explanation: Option (a) is correct. The control will be transferred to the exception handler for StackOverflowError when it’s encountered. Hence it will print caught.

Options (c) and (d) are correct. Exception handlers execute when the corresponding checked or runtime exceptions are thrown.

Option (e) is incorrect. An exception handler for the class StackOverflow can’t handle exceptions of the class NullPointerException because NullPointerException is not a superclass of StackOverflowError.

[6.5] Apply encapsulation principles to a class

ME-Q32)

A class Student is defined as follows:

public class Student {
    private String fName;
    private String lName;

    public Student(String first, String last) {
        fName = first; lName = last;
    }
    public String getName() { return fName + lName; }
}

The creator of the class later changes the method getName as follows:

public String getName() {
    return fName + " " + lName;
}

What are the implications of this change? (Select 2 options.)

  1. The classes that were using the class Student will fail to compile.
  2. The classes that were using the class Student will work without any compilation issues.
  3. The class Student is an example of a well-encapsulated class.
  4. The class Student exposes its instance variable outside the class.

Answer: b, c

Explanation: This is an example of a well-encapsulated class. There’s no change in the signature of the method getName after it’s modified. Hence, none of the code that uses this class and method will face any compilation issues. Its instance variables (fName and lName) aren’t exposed outside the class. They’re available only via a public method: getName.

[6.2] Apply the static keyword to methods and fields

ME-Q33)

What is the output of the following code? (Select 1 option.)

class ColorPack {
    int shadeCount = 12;
    static int getShadeCount() {
        return shadeCount;
    }
}
class Artist {
    public static void main(String args[]) {
        ColorPack pack1 = new ColorPack();
        System.out.println(pack1.getShadeCount());
    }
}

  1. 10
  2. 12
  3. No output
  4. Compilation error

Answer: d

Explanation: A static method can’t access non-static instance variables of a class. Hence, the class ColorPack fails to compile.

[6.6] Determine the effect upon object references and primitive values when they are passed into methods that change the values

ME-Q34)

Paul defined his Laptop and Workshop classes to upgrade his laptop’s memory. Do you think he succeeded? What is the output of this code? (Select 1 option.)

class Laptop {
    String memory = "1 GB";
}
class Workshop {
    public static void main(String args[]) {
        Laptop life = new Laptop();
        repair(life);
        System.out.println(life.memory);
    }
    public static void repair(Laptop laptop) {
        laptop.memory = "2 GB";
    }
}

  1. 1 GB
  2. 2 GB
  3. Compilation error
  4. Runtime exception

Answer: b

Explanation: The method repair defined in this example modifies the state of the method parameter laptop that’s passed to it. It does so by modifying the value of the instance variable memory.

When a method modifies the state of an object reference variable that’s passed to it, the changes made are visible in the calling method. The method repair makes changes to the state of the method parameter laptop; these changes are visible in the method main. Hence, the method main prints the value of life.memory as 2 GB.

[2.1] Declare and initialize variables (including casting of primitive data types)

ME-Q35)

What is the output of the following code? (Select 1 option.)

public class Application {
    public static void main(String... args) {
        double price = 10;

        String model;
        if (price > 10)
            model = "Smartphone";
        else if (price <= 10)
            model = "landline";
        System.out.println(model);
    }
}

  1. landline
  2. Smartphone
  3. No output
  4. Compilation error

Answer: d

Explanation: The local variables aren’t initialized with default values. Code that tries to print the value of an uninitialized local variable fails to compile.

In this code, the local variable model is only declared, not initialized. The initialization of the variable model is placed within the if and else-if constructs. If you initialize a variable within an if or else-if construct, the compiler can’t be sure whether these conditions will evaluate to true, resulting in no initialization of the local variable. Because there’s no else at the bottom and the compiler can’t tell whether the if and else-if are mutually exclusive, the code won’t compile.

If you remove the condition if (price <= 10) from the previous code, the code will compile successfully:

public class Application {
    public static void main(String... args) {
        double price = 10;
        String model;
        if (price > 10)
            model = "Smartphone";
        else
            model = "landline";
        System.out.println(model);
    }
}

In this code, the compiler can be sure about the initialization of the local variable model.

[9.2] Create and manipulate strings

ME-Q36)

What is the output of the following code? (Select 1 option.)

class EString {
    public static void main(String args[]) {
        String eVal = "123456789";

        System.out.println(eVal.substring(eVal.indexOf("2"),
 eVal.indexOf("0")).concat("0"));
    }
}

  1. 234567890
  2. 34567890
  3. 234456789
  4. 3456789
  5. Compilation error
  6. Runtime exception

Answer: f

Explanation: When multiple methods are chained on a single code statement, the methods execute from left to right, not from right to left. eVal.indexOf("0") returns a negative value because, as you can see, the String eVal doesn’t contain the digit 0. Hence, eVal.substring is passed a negative end value, which results in a runtime exception.

[2.4] Explain an Object’s Lifecycle (creation, “dereference by reassignment” and garbage collection)

ME-Q37)

Examine the following code and select the correct statements (choose 2 options).

class Artist {
    Artist assistant;
}
class Studio {
    public static void main(String... args) {
        Artist a1 = new Artist();
        Artist a2 = new Artist();
        a2.assistant = a1;
        a2 = null;        // Line 1
    }
     // Line 2
}

  1. At least two objects are garbage collected on line 1.
  2. At least one object is garbage collected on line 1.
  3. No objects are garbage collected on line 1
  4. The number of objects that are garbage collected on line 1 is unknown.
  5. At least two objects are eligible for garbage collection on line 2.

Answer: d, e

Explanation: Options (a), (b), and (c) are incorrect.

When an object reference is marked as null, the object is marked for garbage collection. But you can’t be sure exactly when a garbage collector will kick in to garbage collect the objects. A garbage collector is a low-priority thread, and its exact execution time will depend on the OS. The OS will start this thread if it needs to claim unused space. You can be sure only about the number of objects that are eligible for garbage collection. You can never be sure about which objects have been garbage collected, so any statement that asserts that a particular number of objects have been garbage collected is incorrect.

Option (d) is correct. As mentioned previously, the exact number of objects garbage collected at any point in time can’t be determined.

Option (e) is correct. If you marked this option incorrect, think again. The question wants you to select the correct statements, and this is a correct statement. You may argue that at least two objects were already made eligible for garbage collection at line 1, and you’re correct. But because nothing changes on line 2, at least two objects are still eligible for garbage collection.

[3.2] Test equality between Strings and other objects using == and equals()

ME-Q38)

What is the output of the following code? (Select 1 option.)

class Book {
    String ISBN;
    Book(String val) {
        ISBN = val;
    }
}
class TestEquals {
    public static void main(String... args) {
        Book b1 = new Book("1234-4657");
        Book b2 = new Book("1234-4657");
        System.out.print(b1.equals(b2) +":");
        System.out.print(b1 == b2);
    }
}

  1. true:false
  2. true:true
  3. false:true
  4. false:false
  5. Compilation error—there is no equals method in the class Book.
  6. Runtime exception

Answer: d

Explanation: The comparison operator determines whether the reference variables refer to the same object. Because the reference variables b1 and b2 refer to different objects, b1==b2 prints false.

The method equals is a public method defined in the class java.lang.Object. Because the class Object is the superclass for all the classes in Java, the method equals is inherited by all classes. Hence, the code compiles successfully. The default implementation of the method equals in the base class compares the object references and returns true if both reference variables refer to the same object, and false otherwise.

Because the class Book doesn’t override this method, the method equals in the base class Object is called for b1.equals(b2), which returns false. Hence, the code prints

false:false

[9.1] Manipulate data using the StringBuilder class and its methods

ME-Q39)

Which of the following statements are correct? (Select 2 options.)

  1. StringBuilder sb1 = new StringBuilder() will create a StringBuilder object with no characters but with an initial capacity to store 16 characters.
  2. StringBuilder sb1 = new StringBuilder(5*10) will create a StringBuilder object with a value of 50.
  3. Unlike the class String, the concat method in StringBuilder modifies the value of a StringBuilder object.
  4. The insert method can be used to insert a character, number, or String at the start or end or a specified position of a StringBuilder.

Answer: a, d

Explanation: There is no concat method in the StringBuilder class. It defines a whole army of append methods (overloaded methods) to add data at the end of a String-Builder object.

new StringBuilder(50) creates a StringBuilder object with no characters but with an initial capacity to store 50 characters.

[4.1] Declare, instantiate, initialize, and use a one-dimensional array

ME-Q40)

Given the following definition of the class Animal and the interface Jump, select the correct array declarations and initialization (choose 3 options).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.147