MOCK PAPER

Mock Exam -1 
Question 1 :Let's have a look at the typeless baskets and the ones where the type is an unbounded wildcards.

// Source A
Basket<?> b5 = new Basket<Apple>();
b5.setElement(new Apple());
Apple apple = (Apple) b5.getElement();
// Source B          

Basket b = new Basket();
b.setElement(new Apple());           
Apple apple = (Apple) b.getElement();
// Source C          

Basket b1 = new Basket<Orange>();
b1.setElement(new Apple());
Apple apple = (Apple) b1.getElement();

Which of the following statements are true?
a)Source A cannot be compiled
b)Source B will be compiled with warning(s).
c)No exception will be thrown during the runtime.
d)Source C will be compiled with warning(s). A ClassCastException exception will be thrown during the runtime

Answer:
Answer 1 : a,b
a) The compiler does not know the type of the element stored in b5. That is why it cannot guarantee an apple can be inserted into the basket b5. So the statement s5.setElement(new Apple()) ist not allowed. The methode b5.setElement(..) cannot be used at all.
b) The compiler does not know the type of the element stored in b. That is why it cannot guarantee apples can be inserted into the basket b. But since we did not specify the type of the element of b at all, the compiler will accept the source code and compile it as if it was a pre 1.5 source code. Since the compiler cannot assure the type safety of the compiled code, it will issue a warning.

Question 2: What will be the output of the following program?
package chapters.chap02;
public class Chap02 {
 public static void main(String[] args) {
  
  for (int i=0; i<5; i++){
   
   switch (i){
    case 0:
     System.out.println("0");
     ++i;
     break;
    case -1:
     System.out.println("-1");
     break;
    case 2:
     System.out.println("2");
     i++;
    case 4:
     System.out.println("4");
     break;     
   }
  }
 }
}

a.The program will not stop and it will run recursively upon execution
b.The program will output '0 2 5 5'.
c.The program will output '0 2 4 4'.
d.The program will output '02 4 5'.

Answer:
Answer 2: c
Answer c is correct. Upon execution the variable 'i' will have a value of 0 which matches the first case, 0 is printed and the value of 'i' is incremented to 1. Because of the break statement, the control comes out of the switch block, and now the value of 'i' is increased to 2 in the for loop. After printing 2, the value of 'i' is incremented to 3, and in the for loop, the value of 'i' happens to be 4 and subsequently the values 4 and 4 gets printed.
                                                                                                                                                                   MORE