Tuesday, November 26, 2013

Question: Variable Decleration and Scope

Given:

public static void main(String[] args) {
   for (int i = 0; i <= 10; i++) {
      if (i > 6) 

           break;
   }
    System.out.println(i);
 }


What is the result?

A. 6
B. 7
C. 10
D. 11
E. Compilation fails.
F. An exception is thrown at runtime

Execution:
The variable i have scope within for loop only and it is printed out of scope will give Compile Time Exception. So it says can't find symbol 'i'

Answer:
E. Compilation fails.


Question: Hashmap & HashSet

Given:

public class Person {

   private name;
   public Person(String name) {
     this.name = name;
   }
   

   public int hashCode() {
    return 420;
   }
}

Which statement is true?

A. The time to find the value from HashMap with a Person key depends on the size of the map.
B. Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
C. Inserting a second Person object into a HashSet will cause the first Person object to be
removed as a duplicate.
D. The time to determine whether a Person object is contained in a HashSet is constant and does
NOT depend on the size of the map.


Execution:

A: The more the size Hashmap will have it will take time  to execute which is correct
B. If we will delete a person key then it will not delete all keys of person type. It is just like deleting String key and all String keys got removed.
C. The previous object will get over write not removed
D. To determine size of collection time is always be taken with respect to size.

Answer:
A. The time to find the value from HashMap with a Person key depends on the size of the map.

Question: Typecasting and Array

Given:

public static void main(String[] args) {
  Object obj = new int[] { 1, 2, 3 };
  int[] someArray = (int[])obj;

  for (int i : someArray) System.out.print(i + " ");
}


What is the result?
A. 1 2 3
B. Compilation fails because of an error in line Object obj .
C. Compilation fails because of an error in line int[] someArray.
D. Compilation fails because of an error in line for (int i.
E. A ClassCastException is thrown at runtime.




































Execution:
Correct declaration and casting
and correct fetching of data
 
Answer: A

Question: Interfaces, abstract class, inheritence and function decleration

Given:

interface Data { public void load(); }
abstract class Info { public abstract void load(); }

Which class correctly uses the Data interface and Info class?

A.
public class Employee extends Info implements Data {
        public void load() { /*do something*/ }
}

B.
public class Employee implements Info extends Data {
public void load() { /*do something*/ }
}

C.
public class Employee extends Info implements Data {
public void load(){ /*do something*/ }
public void Info.load(){ /*do something*/ }
}


D.
public class Employee implements Info extends Data {
public void Data.load(){ /*do something*/ }
public void load(){ /*do something*/ }
}

E. public class Employee implements Info extends Data {
public void load(){ /*do something*/ }
public void Info.load(){ /*do something*/ }
}

F.
public class Employee extends Info implements Data{
public void Data.load() { /*do something*/ }
public void Info.load() { /*do something*/ }
}

Execution:
In option B, Interface only can implement and Class can only extends.
In option C Info.load() is invalid method declaration
D & E are wrong use of inheritance i.e always to implement interface and to extend classes
 F is invalid method declaration.
Answer: A
public class Employee extends Info implements Data {
        public void load() { /*do something*/ }
}

Question: Override, extends and implements

Given:

interface A { public void aMethod(); }

interface B { public void bMethod(); }
 

& interface C extends A,B { public void cMethod(); }
 

class D implements B {
@  public void bMethod(){}
}
 

$ class E extends D implements C {
  public void aMethod(){}
#  public void bMethod(){}
  public void cMethod(){}
}

What is the result?

A. Compilation fails because of an error in line &.
B. Compilation fails because of an error in line $.
C. Compilation fails because of an error in line #.
D. If you define D e = new E(), then e.bMethod() invokes the version of bMethod() defined in Line
@.
E. If you define D e = (D)(new E()), then e.bMethod() invokes the version of bMethod() defined in
Line @.
F. If you define D e = (D)(new E()), then e.bMethod() invokes the version of bMethod() defined in
Line #.

Execution:
There will be no compilation error in any line.
If we create object of some class and reference of it's base class then call some overrided method then it will only execute method of class object(new E()) rather then reference (D e).

Answer:
F. If you define D e = (D)(new E()), then e.bMethod() invokes the version of bMethod() defined in
Line 9.

Monday, November 25, 2013

Question: Iterator, For Each and Lists

Given:

public static Iterator reverse(List list) {
     Collections.reverse(list); 
     return list.iterator();
}

public static void main(String[] args) {
   List list = new ArrayList();
   list.add("1");
   list.add("2");
   list.add("3");
   for (Object obj: reverse(list))
           System.out.print(obj + ", ");
}

What is the result?

A. 3, 2, 1,
B. 1, 2, 3,
C. Compilation fails.
D. The code runs with no output.
E. An exception is thrown at runtime.

Execution:
For Each is not applicable to expression type. You require an Array or Iterable
but not Iterator. Here the reverse method is returning an iterator  
to correct it should be used as
for (Object obj: list)

Answer:
C. Compilation fails.

Question: Switch / enum

Given:

public class Test {
    public enum Dogs {collie, harrier};
    

    public static void main(String [] args) {
    Dogs myDog = Dogs.collie;
    switch (myDog) {
       case collie:
          System.out.print("collie ");
       case harrier:
          System.out.print("harrier ");
     }
   }

}
What is the result?
A. collie
B. harrier
C. Compilation fails.
D. collie harrier
E. An exception is thrown at runtime.

Execution:
It will first print coolie but as BREAK is not there in case so it will execute next statement too and will print harrier.
so answer will be coolie harrier

Answer:
D. collie harrier

Question: Objects and Accessing values

Given:

 class Inner{
    private int x;
    public void setX(int x){this.x=x;}
  
    public int getX(){return x;}
}

class Outer{
    private Inner y;
    public void setY(Inner y){this.y=y;}
    public Inner getY(){return y;}
}

public class Threado {
    public static void main(String[] args) {
           Outer o = new Outer();
           Inner i = new Inner();
           int n = 10;
           i.setX(n);
           o.setY(i);
           //insert code here
           System.out.println(o.getY().getX());
    }
 }





Which three code fragments, added individually at line  //insert code here, produce the output 100?

A. n = 100;
B. i.setX( 100 );
C. o.getY().setX( 100 );
D. i = new Inner(); i.setX( 100 );
E. o.setY( i ); i = new Inner(); i.setX( 100 );
F. i = new Inner(); i.setX( 100 ); o.setY( i );

Execution:
If put option A in place of //insert code here, we will only get 10 as output
If put option B in place of //insert code here, then we will get 100 as output, as "i" object is set with 100 value and o.getY().getX() is accessing that value.
If put option C in place of //insert code here, then we will get 100 as output, as o.getY() is returning object of Inner class and  setX is setting value into same object.
If put option E in place of //insert code here, then we will get 10 as output, as we are declaring a new object of Inner and setting 100 value in it, but printing object which contain value of previous Inner object.
If put option F in place of //insert code here, then we will get 100 as output as it is updating "o" object(Outer class) and printing value for it

Answer:
B. i.setX( 100 );
F. i = new Inner(); i.setX( 100 ); o.setY( i );
C. o.getY().setX( 100 )

Question: Access Specifier and Static Variables

Given:

package com.sun.ocjp;

public class Geodetics {
   public static final double DIAMETER = 12756.32; // kilometers
}

Which two correctly access the DIAMETER member of the Geodetics class?

A. import com.sun.ocjp.Geodetics;
public class TerraCarta {
public double halfway(){ return Geodetics.DIAMETER/2.0; }

B. import static com.sun.ocjp.Geodetics;
public class TerraCarta{
public double halfway() { return DIAMETER/2.0; } }

C. import static com.sun.ocjp.Geodetics.*;
public class TerraCarta {
public double halfway() { return DIAMETER/2.0; } }

D. package com.sun.ocjp;
public class TerraCarta {
public double halfway() { return DIAMETER/2.0; } }





Execution:
The option C will import all Static data and members, so it can be access variable directly.
The option A will access static variable using class name
The option B/D does not have access to static variable as Static import in B will not able to access class internal statics and D does not use object or class name for accessing.

Answer: A,C
A. import com.sun.ocjp.Geodetics;
public class TerraCarta {
public double halfway()
{ return Geodetics.DIAMETER/2.0; }

C. import static com.sun.ocjp.Geodetics.*;
public class TerraCarta {
public double halfway() { return DIAMETER/2.0; } }

Question - Thread Locking and Synchronization

Given:
void waitForSignal() {
    Object obj = new Object();
    synchronized (Thread.currentThread()) {
    obj.wait();
    obj.notify();
   }
 }

Which statement is true?

A. This code can throw an InterruptedException.
B. This code can throw an IllegalMonitorStateException.
C. This code can throw a TimeoutException after ten minutes.
D. Reversing the order of obj.wait() and obj.notify() might cause this method to complete normally.
E. A call to notify() or notifyAll() from another thread might cause this method to complete
normally.
F. This code does NOT compile unless "obj.wait()" is replaced with "((Thread)
obj).wait()".





 Execution:
wait() It will throw InterruptedException if not handled 

but the snippet is acquiring lock on current thread and invoking wait for object i.e ob. This lead to Illegal Monitor of State. So Answer will be IllegalMonitoryStateException

Result:
B. This code can throw an IllegalMonitorStateException.
 

Question: Generics

Given:

// insert code here
private N min, max;
public N getMin() { return min; } 
public N getMax() { return max; }
public void add(N added) {
 if (min == null || added.doubleValue() < min.doubleValue())
 min = added;
 if (max == null || added.doubleValue() > max.doubleValue())
 max = added;
 }
}


Which two, inserted at line 11, will allow the code to compile? (Choose two.)
A. public class MinMax<?> {
B. public class MinMax<? extends Number> {
C. public class MinMax<N extends Object> {
D. public class MinMax<N extends Number> {
E. public class MinMax<? extends Object> {
F. public class MinMax<N extends Integer> {

Execution:
 Yet to study...

Answer:
D. public class MinMax<N extends Number> {
F. public class MinMax<N extends Integer> {
 

Question: Ternary Operator and Array

Given:

String[] elements = { "for", "tea", "too" };
String first = (elements.length > 0) ? elements[0] : null;
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The variable first is set to null.
D. The variable first is set to elements[0].

Execution:
Look carefully to syntax.
It is correct.
So element at Zero location i.e "for" will be assigned to first.
So answer will be D

Answer:
D. The variable first is set to elements[0].

Sunday, November 24, 2013

Question - Static Imports

Given a class Repetition:

package utils;
public class Repetition {
   public static String twice(String s) { return s + s; }
}

and given another class Demo.java:

// insert code here 
public class Demo {   public static void main(String[] args) {
     System.out.println(twice("pizza"));
  }
}
Which code should be inserted at // insert code here  of Demo.java to compile and run Demo to print
"pizzapizza"?

A. import utils.*;
B. static import utils.*;
C. import utils.Repetition.*;
D. static import utils.Repetition.*;
E. import utils.Repetition.twice();
F. import static utils.Repetition.twice;
G. static import utils.Repetition.twice;













Execution:
Static import is a feature introduced in the Java programming language that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined. This feature was introduced into the language in version 5.0.






import static keyword is used


Result:
F. import static utils.Repetition.twice;

Question - Looping and Increment/Decrement Operators

Given:

int a = 0;
int b = 10;
do {
   a--;
   ++b;
} while (a < 5);
System.out.print(a + "," + b);

What is the result?
A. 5,6
B. 5,5
C. 6,5
D. 6,6


Execution:

If we put SOUT in following code:
   ++a;
   System.out.println("A="+a+" B="+b);

} while (a < 5);

On Each loop following will be result:
A=1 B=9
A=2 B=8
A=3 B=7
A=4 B=6
A=5 B=5

Result:
B. 5,5

Question - File Handling - File/Folder creation

Given that the current directory is empty, and that the user has read and write permissions, and
the following:

import java.io.*;
public class DOS { 
public static void main(String[] args) {
File dir = new File("c:\\dir");
dir.mkdir();
File f1 = new File(dir, "f1.txt");
try {
f1.createNewFile();
} catch (IOException e) { ; }
File newDir = new File("newDir");
dir.renameTo(newDir);
}
}

Which statement is true?
A. Compilation fails.
B. The file system has a new empty directory named dir.
C. The file system has a new empty directory named newDir.
D. The file system has a directory named dir, containing a file f1.txt.
E. The file system has a directory named newDir, containing a file f1.txt.

Execution:
On execution of program, this will creates folder in C Drive and also creates an empty text file in that folder.

Result:
E. The file system has a directory named newDir, containing a file f1.txt.

Question - Access Specifiers

Given:
 package test;
 

class Target {
    public String name = "hello";
 }

What can directly access and change the value of the variable name?
A. any class
B. only the Target class
C. any class in the test package
D. any class that extends Target

Execution:
Class is not public but default.
Variable is public
So class is accessible within package which makes it's answer C, whether it extends or not.

Result:
C. any class in the test package

Question - Return Type Compatibility/Overiding

Which statement is true about the classes and interfaces?

    public interface A{
        public void doSomething(String thing);
    }


    public class AImpl implements A{
        public void doSomething(String msg){}
    }
   
    public class B{
        public A doiit() {
        }
        public String execute(){  
        }
    }
   
    public class C extends B{
        public AImpl doiit(){
        }
      
        public Object execute(){
        }
    }


A. Compilation will succeed for all classes and interfaces.
B. Compilation of class C will fail because of an error in line public AImpl doiit() - line 2.
C. Compilation of class C will fail because of an error in line  public Object execute() - line 6.
D. Compilation of class AImpl will fail because of an error in line public void doSomething(String msg) - line 2.

Execution:
Compatibility between types refers to the similarity of two types to each other. Here return types are not compatible between String execute() and Object execute()

In Class C, execute method is overrided with return type Object, as "Return Type Object is not Compatible with String" so it will unable to compile.

If we change execute return type to String, the compile time issue will be resolve
or if we set return type of execute() method to Object in Class B and String in Class C then also the issue will resolve as Object is base class

Output: C
C. Compilation of class C will fail because of an error in line  public Object execute() - line 6.

Question - Multithreading - Thread Execution

Given:
 public class Threads2 implements Runnable {
public void run() {
System.out.println("run.");
throw new RuntimeException("Problem");
}
public static void main(String[] args) {
Thread t = new Thread(new Threads2());
t.start();
System.out.println("End of method.");
}
}

Which of the following two can be results of above question

A. java.lang.RuntimeException: Problem
B. run. java.lang.RuntimeException: Problem
C. End of method. java.lang.RuntimeException: Problem
D. End of method. run. java.lang.RuntimeException: Problem
E. run. java.lang.RuntimeException: Problem End of method.

Execution Result:
Execution of thread is unpredictable and is dependent on JVM
so sometimes main thread will run and it will print End of Method and then other thread will print run and Exception
and other time main thread will run later on to execution of other thread.

So answer will be :
D,E
D. End of method. run. java.lang.RuntimeException: Problem
E. run. java.lang.RuntimeException: Problem End of method.