OCA Java 8 Certification 1Z0-808 Sample Questions



The following are not 1z0-808 dumps but are sample questions extracted from Enthuware OCAJP 8 Exam Simulator, which contains more than 600 practice questions with detailed explanations. Stay away from sites offering Java certification dumps because they are highly unreliable.
CLICK HERE TO PURCHASE
Question 1.     Topic: Constructors     Toughness: Very Tough

Given the following code, which of these constructors can be added to class B without causing a compile time error?


class A{
   int i;
   public A(int x) { this.i = x; }
}
class B extends A{
   int j;
   public B(int x, int y) { super(x);  this.j = y; }
}

Select 2 options:

  1. B( ) { }
  2. B(int y ) { j = y; }
  3. B(int y ) { super(y*2 ); j = y; }
  4. B(int y ) { i = y; j = y*2; }
  5. B(int z ) { this(z, z); }
   Click to see discussion about this Question!
Correct options are: 3, 5
1. To construct an instance of a sub class, its super class needs need to be constructed first. Since an instance can only be created via a constructor, some constructor of the super class has to be invoked.
Either you explicitly call it or the compiler will add super() (i.e. no args constructor) as the first line of the sub class constructor.

Now, if the super class ( here, A ) does not have a no args constructor, the call super() will fail. Hence, choices B( ) { }, B(int y ) { j = y; } and B(int y ) { i = y; j = y*2; } are not valid and choice B(int y ) { super(y*2 ); j = y; } is valid because it explicitly calls super( int ) which is available in A.

2. Instead of calling super(...) you can also call another constructor of the base class in the first line (as given in choice B(int z ) { this(z, z); } ). Here, this(int, int) is called in the first line which in turn calls super(int). So the super class A is correctly instantiated.

Question 2.     Topic: Using Operators and Decision Constructs     Toughness: Very Tough

What will the following code print?
        int x = 1;
        int y = 2;
        int z = x++;
        int a = --y;
        int b = z--;
        b += ++z;

        int answ = x>a?y>b?y:b:x>z?x:z;
        System.out.println(answ);

Select 1 best option:

  1. 0
  2. 1
  3. 2
  4. -1
  5. -2
  6. 3
   Click to see discussion about this Question!
Correct option is: 3
This is a simple but frustratingly time consuming question. Expect such questions in the exam.
For such questions, it is best to keep track of each variable on the notepad after executing each line of code.

The final values of the variables are as follows -
x=2 y=1 z=1 a=1 b=2

The expression x>a?y>b?y:b:x>z?x:z; should be grouped as -
x > a  ? (y>b ? y : b)  :  (x>z ? x : z);

It will, therefore, assign 2 to answ.

Question 3.     Topic: Working with Inheritance     Toughness: Real Brainer

Which statements about the following code are correct?

interface House{
  public default String getAddress(){
     return "101 Main Str";
  }
}

interface Bungalow extends House{
  public default String getAddress(){
     return "101 Smart Str";
  }
}

class MyHouse implements Bungalow, House{

}

public class TestClass {

  public static void main(String[] args) {
    House ci = new MyHouse();  //1
    System.out.println(ci.getAddress()); //2
  }
}

Select 1 best option:

  1. Code for interface House will cause compilation to fail.
  2. Code for interface Bungalow will cause compilation to fail.
  3. Code for class MyHouse will cause compilation to fail.
  4. Line at //1 will cause compilation to fail.
  5. Line at //2 will cause compilation to fail.
  6. The code will compile successfully.
   Click to see discussion about this Question!
Correct option is: 6
There is no problem with the code. It is perfectly valid for a sub-interface to override a default method of the base interface. A class that implements an interface can also override a default method.
It is valid for MyHouse to say that it implements Bungalow as well as House even though House is redundant because Bungalow is a House anyway.

It will actually print 101 Smart str.

Question 4.     Topic: Using Operators and Decision Constructs     Toughness: Easy

Consider the following code:

class Test{
  public static void main(String[] args){
    for (int i = 0; i < args.length; i++)   System.out.print(i == 0 ? args[i] : " " + args[i]);
  }
}


What will be the output when it is run using the following command:

java Test good bye friend!

Select 1 best option:

  1. good bye friend!
  2. good good good
  3. goodgoodgood
  4. good bye
  5. None of the above.
   Click to see discussion about this Question!
Correct option is: 1
The arguments passed on the command line can be accessed using the args array. The first argument (i.e. good) is stored in args[0], second argument (i.e. bye) is stored in args[1] and so on.

Here, we are passing 3 arguments. Therefore, args.length is 3 and the for loop will run 3 times. For the first iteration, i is 0 and so the first operand of the ternary operator (?) will be returned, which is args[i]. For the next two iterations, " "+args[i] will be returned. Hence, the program will print three strings: "good", " bye", and " friend" on the same line.

Note that unlike in C++, program name is not the first parameter in the argument list. Java does not need to know the program name because the .class file name and the java class name are always same (for a public class). So the java code always knows the program name it is running in. So there is no need to pass the program name as the first parameter of the argument list. In C/C++, the binary file name may be anything so the code does not know what binary file it is going to end up in. That's why the program name is also sent (automatically) in parameter list.

Question 5.     Topic: Working with Java Data Types     Toughness: Tough

Which of the following statements will print true when executed?

Select 3 options:

  1. System.out.println(Boolean.parseBoolean("true"));
  2. System.out.println(new Boolean(null)));
    This will print false.
  3. System.out.println(new Boolean()));
    This will not compile because Boolean class does not have a no-args constructor. Remember that no other wrapper class has a no-args constructor either. So new Integer(), or new Long() will also not compile.
  4. System.out.println(new Boolean("true"));
    Case of the String parameter does not matter. As long as the String equals "true" after ignoring the case, it will be parsed as true.  However, if you have extra spaces, for example, " true" or "true ", it will be parsed as false.
  5. System.out.println(new Boolean("trUE"));
    Case of the String parameter does not matter. As long as the String equals "true" after ignoring the case, it will be parsed as true.  However, if you have extra spaces, for example, " true" or "true ", it will be parsed as false.
   Click to see discussion about this Question!
Correct options are: 1, 4, 5
You need to remember the following points about Boolean:

1. Boolean class has two constructors - Boolean(String) and Boolean(boolean)
The String constructor allocates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string "true". Otherwise, allocate a Boolean object representing the value false. Examples: new Boolean("True") produces a Boolean object that represents true. new Boolean("yes") produces a Boolean object that represents false.

The boolean constructor is self explanatory.

2. Boolean class has two static helper methods for creating booleans - parseBoolean and valueOf.
Boolean.parseBoolean(String ) method returns a primitive boolean and not a Boolean object (Note - Same is with the case with other parseXXX methods such as Integer.parseInt - they return primitives and not objects). The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Boolean.valueOf(String ) and its overloaded Boolean.valueOf(boolean ) version, on the other hand, work similarly but return a reference to either Boolean.TRUE or Boolean.FALSE wrapper objects. Observe that they dont create a new Boolean object but just return the static constants TRUE or FALSE defined in Boolean class.

3. When you use the equality operator ( == ) with booleans, if exactly one of the operands is a Boolean wrapper, it is first unboxed into a boolean primitive and then the two are compared (JLS 15.21.2). If both are Boolean wrappers, then their references are compared just like in the case of other objects. Thus, new Boolean(true) == new Boolean(true) is false, but new Boolean(true) == Boolean.parseBoolean("true") is true.

Question 6.     Topic: Java Basics     Toughness: Easy

You have written some Java code in MyFirstClass.java file. Which of the following commands will you use to compile and run it.
(Assume that the code has no package declaration.)

Select 1 best option:

  1. javac MyFirstClass.java
    javar MyFirstClass
  2. javap MyFirstClass.java
    javar MyFirstClass.java
  3. java MyFirstClass.java
    java MyFirstClass.class
  4. javac MyFirstClass.java
    javar MyFirstClass.java
  5. javac MyFirstClass.java
    java MyFirstClass
   Click to see discussion about this Question!
Correct option is: 5
Remember that java code must be written in a file with .java extension. If you have a public class in the code, the name of the file must be same as the name of that public class.

Compilation and execution of a Java program is two step process. You first need to compile a java file using a Java compiler. Oracle's JDK comes with a compiler. It is contained in the executable file named javac. You will find it in <jdk installation folder>/bin.

javac compiles the source code and generates bytecode in a new file with the same name as the source file but with extension .class. By default, the class file in generated in the same folder but javac is capable of placing it in a different folder if you use the -d flag. [This is just FYI and not required for the exam. -d is a very important and useful flag and we recommend that you read about it even if it is not required for the exam.]

In second step, the Java virtual machine (JVM), aka Java interpreter is invoked to execute the .class file. Oracle's JVM is contained in the executable file named java. It is also present in the same bin folder of JDK installation. It takes the fully qualified name (i.e. name including package) of the class file without extension as a argument.

Question 7.     Topic: Java Basics     Toughness: Very Tough

What will the following code print when run?

public class TestClass{
  public static long main(String[] args){
     System.out.println("Hello");
     return 10L;
  }
}

Select 1 best option:

  1. Hello
  2. It will not print anything.
  3. It will not compile
  4. It will throw an Error at runtime.
  5. None of the above.
   Click to see discussion about this Question!
Correct option is: 4
When the program is run, the JVM looks for a method named main() which takes an array of Strings as input and returns nothing (i.e. the return type is void).
But in this case, it doesn't find such a method ( the given main() method is returning long!) so it throws a java.lang.NoSuchMethodError.
Note that java.lang.Error does not extend Exception class. It  extends java.lang.Throwable and so it can be "thrown".

Question 8.     Topic: Working with Inheritance     Toughness: Very Tough

Consider the following code:


interface Flyer{ String getName(); }

class Bird implements Flyer{
    public String name;
    public Bird(String name){
        this.name = name;
    }
    public String getName(){ return name; }
}

class Eagle extends Bird {
    public Eagle(String name){
        super(name);
    }
}

public class TestClass {
    public static void main(String[] args) throws Exception {
        Flyer f = new Eagle("American Bald Eagle");
        //PRINT NAME HERE
   }
}

Which of the following lines of code will print the name of the Eagle object?

Select 3 options:

  1. System.out.println(f.name);
  2. System.out.println(f.getName());
  3. System.out.println(((Eagle)f).name);
  4. System.out.println(((Bird)f).getName());
  5. System.out.println(Eagle.name);
    name is not a static field in class Eagle.
  6. System.out.println(Eagle.getName(f));
    This option doesn't make any sense.
   Click to see discussion about this Question!
Correct options are: 2, 3, 4
While accessing a method or variable, the compiler will only allow you to access a method or variable that is visible through the class of the reference.

When you try to use f.name, the class of the reference f is Flyer and Flyer has no field named "name", thus, it will not compile. But when you cast f to Bird (or Eagle), the compiler sees that the class Bird (or Eagle, because Eagle inherits from Bird) does have a field named "name" so ((Eagle)f).name or ((Bird)f).name will work fine.

f.getName() will work because Flyer does have a getName() method.

Question 9.     Topic: Working with Methods     Toughness: Easy

What will the following program print when run?

public class ChangeTest {

    private int myValue = 0;
    
    public void showOne(int myValue){
        myValue = myValue;
    }
    
    public void showTwo(int myValue){
        this.myValue = myValue;
    }    
    public static void main(String[] args) {
        ChangeTest ct = new ChangeTest();
        ct.showTwo(200);
        System.out.println(ct.myValue);
        ct.showOne(100);
        System.out.println(ct.myValue);
    }
}

Select 1 best option:

  1. 0 followed by 100.
  2. 100 followed by 100.
  3. 0 followed by 200.
  4. 100 followed by 200.
  5. 200 followed by 200.
  6. 200 followed by 100
   Click to see discussion about this Question!
Correct option is: 5
There are a couple of important concepts in this question:

1. Within an instance method, you can access the current object of the same class using 'this'. Therefore, when you access this.myValue, you are accessing the instance member myValue of the ChangeTest instance.

2. If you declare a local variable (or a method parameter) with the same name as the instance field name, the local variable "shadows" the member field. Ideally, you should be able to access the member field in the method directly by using the name of the member (in this example, myValue). However, because of shadowing, when you use myValue, it refers to the local variable instead of the instance field.

In showTwo method, there are two variables accessible with the same name myValue. One is the method parameter and another is the member field of ChangeTest object. Ideally, you should be able to access the member field in the method directly by using the name myValue but in this case, the method parameter shadows the member field because it has the same name.  So by doing this.myValue, you are changing the instance variable myValue by assigning it the value contained in local variable myValue, which is 200. So in the next line when you print ct.myValue, it prints 200.

Now, in the showOne method also, there are two variables accessible with the same name myValue. One is the method parameter and another is the member field of ChangeTest object. So when you use myValue, you are actually using the method parameter instead of the member field.

Therefore, when you do : myValue = myValue; you are actually assigning the value contained in method parameter myValue to itself. You are not changing the member field myValue. Hence, when you do System.out.println(ct.myValue); in the next line, it still prints 200.


Question 10.     Topic: Working with Java Data Types     Toughness: Real Brainer

What will the following program print?

public class TestClass{
  static boolean b;
  static int[] ia = new int[1];
  static char ch;
  static boolean[] ba = new boolean[1];
  public static void main(String args[]) throws Exception{
    boolean x = false;
    if( b ){
      x = ( ch == ia[ch]);
    }
    else x = ( ba[ch] = b );
    System.out.println(x+" "+ba[ch]);
  }
}

Select 1 best option:

  1. true true
  2. true false
  3. false true
  4. false false
  5. It will not compile.
   Click to see discussion about this Question!
Correct option is: 4
This question tests your knowledge on the default values of uninitialized primitives and object references. booleans are initialized to false, numeric types to 0 and object references to null. Elements of arrays are initialized to the default values of their types. So, elements of a boolean array are initialized to false. int, char, float to 0 and Objects to null.

In this case, b is false. So the else part of if(b) is executed.
ch is a numeric type to its value is 0. ba[0] = false assigns false to ba[0] and returns false which is assigned to x.
Finally, x and ba[0] are printed as false false.

Question 11.     Topic: Working with Inheritance     Toughness: Real Brainer

Consider the following code:


class A{
 public XXX m1(int a){
   return a*10/4-30;
 }
}
class A2 extends A{
 public YYY m1(int a){
   return a*10/4.0;
 }
}
What can be substituted for XXX and YYY so that it can compile without any problems?

Select 1 best option:

  1. int, int
    a*10/4.0; generates a double so, A2's m1() cannot return an int. (It will need a cast otherwise: return (int) (a*10/4.0);)
  2. int, double
    The return type should be same for overridden and overriding method.
  3. double, double
    a*10/4-30; generates an int which can be returned as a double without any cast.
  4. double, int
    The return type should be same for overridden and overriding method.
  5. Nothing, they are simply not compatible.
   Click to see discussion about this Question!
Correct option is: 3
Note that when a method returns objects (as opposed to primitives, like in this question), the principle of covariant returns applies. Meaning, the overriding method is allowed to return a subclass of the return type defined in the overridden method. Thus, if a base class's method is: public A m(); then a subclass is free to override it with: public A1 m(); if A1 extends A.

Question 12.     Topic: Lambda Expressions     Toughness: Very Tough

What can be inserted in the code below so that it will print true when run?

public class TestClass{

   public static boolean checkList(List list, Predicate<List> p){
      return p.test(list);
   }
  
   public static void main(String[] args) {
      boolean b = //WRITE CODE HERE
      System.out.println(b);
   }
}

Select 2 options:

  1. checkList(new ArrayList(), al -> al.isEmpty());
    The test method of Predicate returns a boolean. So all you need for your  body part in your lambda expression is an expression that returns a boolean.
    isEmpty() is a valid method of ArrayList, which returns true if there are no elements in the list. Therefore, al.isEmpty() constitutes a valid body for the lambda expression in this case.
  2. checkList(new ArrayList(), ArrayList al -> al.isEmpty());
    You need to put the parameter list of the lambda expression in brackets if you want to use the parameter type. For example,
    checkList(new ArrayList(), (ArrayList al) -> al.isEmpty());
    Remember that specifying the parameter type is optional ( as shown in option 1) because the compiler can figure out the parameter types by looking at the signature of the abstract method of any functional interface (here, Predicate's test method).
  3. checkList(new ArrayList(), al -> return al.size() == 0);
    You need to put the body withing curly braces if you want to use the return keyword. For example,
    checkList(new ArrayList(), al -> { return al.size() == 0; });
  4. checkList(new ArrayList(), al -> al.add("hello"));
    The add method of ArrayList returns a boolean. Further, it returns true if the list is altered because of the call to add. In this case, al.add("hello") indeed alters the list because a new element is added to the list.
   Click to see discussion about this Question!
Correct options are: 1, 4

Question 13.     Topic: Using Operators and Decision Constructs     Toughness: Easy

Given:
public class LoopTest {
    int k = 5;
    public boolean checkIt(int k){
        return k-->0?true:false;
    }
    public void printThem(){
        while(checkIt(k)){
            System.out.print(k);
        }
    }
    public static void main(String[] args) {
        new LoopTest().printThem();
    }
}

What changes should be made so that the program will print 54321?

Select 1 best option:

  1. No change is necessary.
    It will go in an infinite loop.
  2. Replace System.out.print(k); with System.out.print(k--);
  3. Replace System.out.print(k); with System.out.print(--k);
    It will print 43210.
  4. Replace while(checkIt(k)) with while(checkIt(--k)).
    It will print 4321.
  5. Replace return k-->0?true:false; with return this.k-->0?true:false;
    This will print 43210.
   Click to see discussion about this Question!
Correct option is: 2
Observe that the method parameter k in checkIt shadows the instance variable k. Therefore, any changes made to k in checkIt will not affect the instance variable k. For checkIt method to access the instance variable k, you need to do this.k.

k-->0 means, first compare the value of k with 0, and then reduce it by 1. (As opposed to --k>0, which means, first reduce the value of k by 1 and then compare with 0).

In the printThem method, k refers to the instance variable. You need to reduce it by 1 after each iteration. Therefore, System.out.print(k--); will do.

Question 14.     Topic: Working with Java Data Types     Toughness: Tough

What will the following code print when compiled and run?


public class Discounter {
    static double percent; //1
    int offset = 10, base= 50; //2
    public static double calc(double value) {
        int coupon, offset, base; //3
        if(percent <10){ //4
            coupon = 15;
            offset = 20;
            base = 10;
        }
        return coupon*offset*base*value/100; //5
    }
    public static void main(String[] args) {
        System.out.println(calc(100));
    }
}

Select 1 best option:

  1. 3000
  2. 3000.0
  3. compilation error at //3
  4. compilation error at //4
  5. compilation error at //5
  6. Exception at run time.
   Click to see discussion about this Question!
Correct option is: 5
Remember that static and instance variables are automatically assigned a value even if you don't initialize them explicitly but local variables must be initialized explicitly before they are used.

Now, observe that the calc method declares local variables coupon, offset, and base but does not assign them a value. Even though at run time, we know that since percent is 0 and is thus < 10, a value will be assigned to these variables, the compiler doesn't know this because the compiler doesn't take values of "variables" into consideration while determining the flow of control. It only considers the values of compile time constants. Therefore, as far as the compiler is concerned, coupon, offset, and base may remain uninitialized before they are used.

Having uninitialized variables itself is not a problem. So there is no compilation error at //3. However, using them before they are initialized is a problem and therefore the compiler flags an error at //5.

Had percent been defined as final ( static final double percent = 0; ), the code would work and print 3000.0.


Question 15.     Topic: Using Loop Constructs     Toughness: Very Tough

Consider the following code for the main() method:


public static void main(String[] args) throws Exception{
   int i = 1, j = 10;
   do {
      if (i++ > --j) continue;
   } while (i < 5);
   System.out.println("i=" + i + " j=" + j);
}
What will be the output when the above code is executed?

Select 1 best option:

  1. i=6 j=6
  2. i=5 j=6
  3. i=5 j=5
  4. i=6 j=5
  5. None of these.
   Click to see discussion about this Question!
Correct option is: 2
To understand the flow, let us put a print statement in the code:

  int i = 1, j = 10;
   int k =1;
   do {
      System.out.println("Iteration "+k+": i=" + i + " j=" + j);
      k++;
      if (i++ > --j) continue;
   } while (i < 5);
   System.out.println("i=" + i + " j=" + j);


It generates the following output:

Iteration 1: i=1 j=10
Iteration 2: i=2 j=9
Iteration 3: i=3 j=8
Iteration 4: i=4 j=7
i=5 j=6


In the iteration 1, the if comparison goes like this:
if (1++ > --10 ) continue; => if( 1 > 9 ) . The values of i and j after the if statement are 2 and 9
In the iteration 2, the if comparison goes like this:
if (2++ > --9 ) continue; => if( 2 > 8 ) . The values of i and j after the if statement are 3 and 8
In the iteration 3, the if comparison goes like this:
if (3++ > --8 ) continue; => if( 3 > 7 ) . The values of i and j after the if statement are 4 and 7
In the iteration 4, the if comparison goes like this:
if (4++ > --7 ) continue; => if( 4 > 6 ) . The values of i and j after the if statement are 5 and 6

Now, i is not < 5 so the while(i<5) check fails and the loop terminates. So the final values are 5 and 6.

Question 16.     Topic: Handling Exceptions     Toughness: Very Tough

Consider the following code:


class A {
    public void doA(int k) throws Exception {  // 0
        for(int i=0; i< 10; i++) {
            if(i == k) throw new Exception("Index of k is "+i); // 1
        }
    }
    public void doB(boolean f) { // 2
        if(f) {
            doA(15); // 3
        }
        else return;
    }
    public static void main(String[] args) { // 4
        A a = new A();
        a.doB(args.length>0); // 5
    }
 }
Which of the following statements are correct?

Select 1 best option:

  1. This will compile and run without any errors or exception.
  2. This will compile if throws Exception is added at line //2
  3. This will compile if throws Exception is added at line //4
  4. This will compile if throws Exception is added at line //2 as well as //4
  5. This will compile if  line marked // 1 is enclosed in a try - catch block.
    Even if // 1 is enclosed in a try block, the method still has throws Exception in its declaration, which will force the caller of this method to either declare Exception in its throws clause or put the call within a try block.
   Click to see discussion about this Question!
Correct option is: 4
Any checked exceptions must either be handled using a try block or the method that generates the exception must declare that it throws that exception.
In this case, doA() declares that it throws Exception. doB() is calling doA but it is not handling the exception generated by doA(). So, it must declare that it throws Exception. Now, the main() method is calling doB(), which generates an exception (due to a call to doA()). Therefore, main() must also either wrap the call to doB() in a try block or declare it in its throws clause.

The main(String[] args) method is the last point in your program where any unhandled checked exception can bubble up to. After that the exception is thrown to the JVM and the JVM kills the thread.

Question 17.     Topic: Working with Java API - String, StringBuilder     Toughness: Very Tough

What will the following code print when compiled and run?

public class TestClass{
    
    public static void main(String[] args) {

        System.out.println(getMsg((char)10));

    }

    public static String getMsg(char x){
        String msg = "Input value must be ";
        msg = msg.concat("smaller than X");
        msg.replace('X', x);
        String rest = " and larger than 0";
        msg.concat(rest);
        return msg;
    }
}

Select 1 best option:

  1. Input value must be smaller than X and larger than 0
  2. Input value must be smaller than 10 and larger than 0
  3. Input value must be smaller than X
  4. Input value must be smaller than 10
   Click to see discussion about this Question!
Correct option is: 3
Remember that a String once created cannot be changed. Therefore, when you call replace or concat methods on a String, a new String object is created. The old String remains as it is.
Here, the first call to concat returns a new String object containing "Input value must be smaller than X" and it is assigned back to msg. The original String referred to by msg is now lost (i.e. there is no reference to it anymore).
The first call to replace also creates a new String object but it is not assigned to any reference and is therefore lost and msg keeps pointing to the same String object. The same thing happens to the second call to concat. It create a new String object but it is not assigned back to msg, therefore, msg keeps pointing to the same object i.e. "Input value must be smaller than X"

Question 18.     Topic: Using Operators and Decision Constructs     Toughness: Easy

What will the following code print when run?

public class TestClass {
    public static void main(String[] args) throws Exception {
        
         boolean flag  = true;
         switch (flag){
             case true : System.out.println("true");
                 default: System.out.println("false");
         }
              
    }
}

Select 1 best option:

  1. It will not compile.
    A boolean cannot be used for a switch statement. It needs an integral type, an enum, or a String.
  2. false
  3. true
    false
  4. Exception at run time.
   Click to see discussion about this Question!
Correct option is: 1
Here are the rules for a switch statement:
1. Only String, byte, char, short, int, (and their wrapper classes Byte, Character, Short, and Integer), and enums can be used as types of a switch variable. (String is allowed only since Java 7).
2. The case constants must be assignable to the switch variable. For example, if your switch variable is of class String, your case labels must use Strings as well.
3. The switch variable must be big enough to hold all the case constants. For example, if the switch variable is of type char, then none of the case constants can be greater than 65535 because a char's range is from 0 to 65535.
4.  All case labels should be COMPILE TIME CONSTANTS. You cannot have variables as case labels.
5. No two of the case constant expressions associated with a switch statement may have the same value.
6. At most one default label may be associated with the same switch statement.

Question 19.     Topic: Working with Java Data Types     Toughness: Tough

How many objects have been created by the time the main method reaches its end in the following code?
public class Noobs {
    public Noobs(){
        try{
            throw new MyException();
        }catch(Exception e){
        }
    }
    public static void main(String[] args) {
        Noobs a = new Noobs();
        Noobs b = new Noobs();
        Noobs c = a;
    }
}
class MyException extends Exception{
    
}

Select 1 best option:

  1. 2
  2. 3
  3. 4
  4. 5
  5. 6
   Click to see discussion about this Question!
Correct option is: 3
When a Noobs object is created, a MyException object is also created. Therefore a total of 4 objects are created. The line Noobs c = a; just assigns an existing Noobs object to c. No new object is created.

Note: Some candidates have reported getting a similar question.
The question is ambiguous because two Class objects (one for Noobs and one for MyException) are also created. If you consider those, then the answer would be 6. Further, several Thread objects are also created (although not directly by this code.) Since this is out of scope for the exam, it is best to ignore these kind of objects and consider only the objects created directly by the code.

Question 20.     Topic: Working with Java API - Time and Date     Toughness: Tough

Which of the following are valid ways to create a LocalDateTime?

Select 1 best option:

  1. java.time.LocalDate.parse("2015-01-02");
    To create an instance of LocalDateTime, you need to use the methods in LocalDateTime class. Methods in LocalDate class create LocalDate instances. Similarly, methods in LocalTime class create LocalTime instances.
  2. java.time.LocalDateTime.parse("2015-01-02");
    LocalDateTime requires date as well as time. Here, you just have a date in the input so it will throw a java.time.format.DateTimeParseException.
    java.time.LocalDateTime.parse("2015-01-02T17:13:50"); would be valid.
  3. java.time.LocalDateTime.of(2015, 10, 1, 10, 10);
  4. java.time.LocalDateTime.of(2015, "January", 1, 10, 10);
    All parameters should be ints. For the month argument, you can either pass the numbers 1 to 12  (and not 0 to 11) or use constants such as java.time.Month.JANUARY.
   Click to see discussion about this Question!
Correct option is: 3

Question 21.     Topic: Working with Java Data Types     Toughness: Real Brainer

What will the following code print?

public class Test{
    public static void testInts(Integer obj, int var){
        obj = var++;
        obj++;
    }
    public static void main(String[] args) {
        Integer val1 = new Integer(5);
        int val2 = 9;
        testInts(val1++, ++val2);
        System.out.println(val1+" "+val2);
    }
}           

Select 1 best option:

  1. 10 9
  2. 10 10
  3. 6 9
  4. 6 10
  5. 5 11
   Click to see discussion about this Question!
Correct option is: 4
There are multiple concepts at play here:
1. All the wrapper objects are immutable. So when you do obj++, what actually happens is something like this:
obj = new Integer( obj.intValue()  + 1);  

2.val1++ uses post-increment operator, which implies that you note down the current value of val1, increment it, and then pass the original noted down value to the method testInts. Thus, the reference value of Integer 5 is passed to testInts. But val1 is set to point to a new Integer object containing 6.
++val2 uses pre-increment operator, which implies that you first increment val2 and then pass the incremented value. Therefore, val2 is incremented to 10 and then 10 is passed to the method testInts.

3. Java uses pass by value semantics in method calls. In case of primitive variables, their values are passed, while in case of Objects, their reference values are passed.  Thus, when you assign a different object to reference variable in a method, the original reference variable that was passed from the calling method still points to the same object that it pointed to before the call.
In this question, therefore, val1 in main still points to 6 after the call to testInts returns.

Question 22.     Topic: Working with Methods - Overloading     Toughness: Very Tough

Consider the following class...


class TestClass{
    void probe(Object x) { System.out.println("In Object"); } //3 

    void probe(Number x) { System.out.println("In Number"); } //2

    void probe(Integer x) { System.out.println("In Integer"); } //2
    
    void probe(Long x) { System.out.println("In Long"); } //4
    
    public static void main(String[] args){
        double a = 10; 
        new TestClass().probe(a); 
    }
}
What will be printed?

Select 1 best option:

  1. In Number
  2. In Object
  3. In Long
  4. In Integer
  5. It will not compile.
   Click to see discussion about this Question!
Correct option is: 1
Here, we have four overloaded probe methods but there is no probe method that takes a double parameter. However, a double will be boxed into a Double and class Double extends Number. Therefore, a Double can be passed to the method that takes Number. A Double can also be passed to a method that takes Object, but Number is more specific than Object therefore probe(Number ) will be called.

We advise you to run this program and try out various combinations. The exam has questions on this pattern.

Question 23.     Topic: Working with Inheritance     Toughness: Real Brainer

What will the following code print when compiled and run?
class Baap{
    public int h = 4;
    public int getH(){
        System.out.println("Baap "+h); return h;
    }
}


public class Beta extends Baap{
    public int h = 44;
    public int getH(){
        System.out.println("Beta "+h); return h;
    }    
    public static void main(String[] args) {
        Baap b = new Beta();
        System.out.println(b.h+" "+b.getH());
        Beta bb = (Beta) b;
        System.out.println(bb.h+" "+bb.getH());
    }
}

Select 1 best option:

  1. Baap 44
    4 44
    Beta 44
    44 44
  2. Beta 44
    4 44
    Baap 44
    44 44
  3. Beta 44
    4 44
    Beta 44
    44 44
  4. 4 44
    Beta 44
    44 44
    Beta 44
  5. 44 44
    Beta 44
    4 44
    Beta 44
  6. 4 44
    Beta 44
    4 44
    Beta 44

   Click to see discussion about this Question!
Correct option is: 3
Always remember: Instance methods are overridden and variables are hidden. Which method is invoked depends on the class of the actual object, while which field is accessed depends on the class of the variable.
Here, b refers to an object of class Beta so b.getH() will always call the overridden (subclass's method). However, the type of reference of b is Baap. so b.h will always refer to Baap's h. Further, inside Beta's getH(), Beta's h will be accessed instead of Baap's h because you are accessing this.h ('this' is implicit) and the type of this is Beta.

The class of bb, on the other hand, is Beta. Thus, bb.h will always refer to Beta's h.

Question 24.     Topic: Creating and Using Arrays     Toughness: Tough

Consider the following array definitions:
int[] array1, array2[];
int[][] array3;
int[] array4[], array5[];

Which of the following are valid statements?

Select 3 options:

  1. array2 = array3;
  2. array2 = array4;
  3. array1 = array2;
  4. array4 = array1;
  5. array5 = array3;
   Click to see discussion about this Question!
Correct options are: 1, 2, 5
There is a subtle difference between: int[] i; and int i[]; although in both the cases, i is an array of integers.
The difference is if you declare multiple variables in the same statement such as: int[] i, j; and int i[], j;, j is not of the same type in the two cases.
In the first case, j is an array of integers while in the second case, j is just an integer.
Therefore, in this question:
array1 is an array of int
array2, array3, array4, and array5  are arrays of int arrays
Therefore, option 1, 2 and 5 are valid.

Question 25.     Topic: Working with Java API - ArrayList     Toughness: Very Tough

What will the following code print?
List s1 = new ArrayList( );
s1.add("a");
s1.add("b");
s1.add("c");
s1.add("a");
System.out.println(s1.remove("a")+" "+s1.remove("x"));

Select 1 best option:

  1. 1 0
  2. 2 -1
  3. 2 0
  4. 1 -1
  5. true false
   Click to see discussion about this Question!
Correct option is: 5
ArrayList's remove(Object ) method returns a boolean. It returns true if the element is found in the list and false otherwise. The JavaDoc API description of this method is important for the exam -

public boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

Observe that it does not remove all occurences of the element. It removes just the first one. In this case, only the first "a" will be removed.

Question 26.     Topic: Using Loop Constructs     Toughness: Easy

What will the following code print?


void crazyLoop(){
  int c = 0;
  JACK: while (c < 8){
    JILL: System.out.println(c);
    if (c > 3) break JACK; else c++;
  }
}

Select 1 best option:

  1. It will not compile.
  2. It will throw an exception at runtime.
  3. It will print numbers from 0 to 8
  4. It will print numbers from 0 to 3
  5. It will print numbers from 0 to 4
   Click to see discussion about this Question!
Correct option is: 5
This is a straight forward loop that contains a labelled break statement. A labelled break breaks out of the loop that is marked with the given label. Therefore, a labelled break is used to break out from deeply nested loops to the outer loops. Here, there is only one nested loop so the break; and break JACK; are same, but consider the following code:
    public static void crazyLoop(){
      int c = 0;
      JACK: while (c < 8){
        JILL: System.out.println("c = "+c);
        for(int k = 0; k<c; k++){
            System.out.println(" k = "+k+" c = "+c);
            if (c > 3) break JACK; 
        }
        c++;
      }
    }
This code prints:
c = 0
c = 1
  k = 0 c = 1
c = 2
  k = 0 c = 2
  k = 1 c = 2
c = 3
  k = 0 c = 3
  k = 1 c = 3
  k = 2 c = 3
c = 4
  k = 0 c = 4
As you can see, in this case, break JACK; will break out from the outer most loop (the while loop). If break JACK; is replaced by break; it will print:
c = 0
c = 1
  k = 0 c = 1
c = 2
  k = 0 c = 2
  k = 1 c = 2
c = 3
  k = 0 c = 3
  k = 1 c = 3
  k = 2 c = 3
c = 4
  k = 0 c = 4
c = 5
  k = 0 c = 5
c = 6
  k = 0 c = 6
c = 7
  k = 0 c = 7
This shows that a break without a label only breaks out of the current loop.

Question 27.     Topic: Java Basics - OO Concepts     Toughness: Tough

Given:

public class Triangle{
    public int base;
    public int height;
    public double area;
    
    public Triangle(int base, int height){
        this.base = base; this.height = height;
        updateArea();
    }

    void updateArea(){
        area = base*height/2;
    }
    public void setBase(int b){ base  = b; updateArea(); }
    public void setHeight(int h){ height  = h; updateArea(); }
}
The above class needs to protect an invariant on the "area" field. Which three members must have the public access modifiers removed to ensure that the invariant is maintained?

Select 3 options:

  1. the base field
  2. the height field
  3. the area field
  4. the Triangle constructor
  5. the setBase method
  6. the setHeight method
   Click to see discussion about this Question!
Correct options are: 1, 2, 3
An invariant means a certain condition that constrains the state stored in the object. For example, in this case the value of the area field of the Triangle must always be consistent with its base and height fields. Thus, it should never have a value that is different from base*height/2.

If you allow other classes to directly change the value of base, height, or area, using direct field access, the area field may not contain the correct area thereby breaking the invariant.

To prevent this inconsistency from happening, you need to prohibit changing the instance fields directly and instead permit the changes only through the setter method because these methods call the updateArea method and keep the area and base and height consistent.