Google

May 6, 2014

Java Generics written test questions and answers



Q1. Which of the following are legal in the underline specified?

     ______________ = new ArrayList<Integer>();  // line 1

     numbers.add(5);    //line 2                               

a) List<? super Integer> numbers
b) List<? super Number> numbers
c) List<Object> numbers
d) List<? extends Integer> numbers
e) List<?> numbers
f) List<Integer> numbers


A1. a and f.

a) is legal because the rule for

<? super T> is

for List<T> to write (i.e. add) to the destination, and does not care if the destination also contain subclasses of T. In the above example T happens to be an Integer.

b) Line 1 is illegal because T is an Integer and not a Number as per the above rule.

c) Line 1 is illegal because the super class of List<T> is List<?> and not List<Object>. List<?> means the collection of the unknown.

d) Line 2 is illegal because  the rule for

<? extends T>  is

for List<? extends T> is for read only and you can't add to it. It does not care if the actual object retrieved is a sub type of T. In the above example, T happens to be an Integer.

e) Line 1 is illegal because you can't add anything to a list of unknown (i.e. List<?>)

f) is legal as T is Integer.


Note: Illegal means you get compile-time error. Java generics check happens only at compile-time.


Q2. Which of the following are legal in the underline specified?

    List<Integer> numbers = ______________________; //Line1
    numbers.add(5); 


a) new ArrayList<Integer>();
b) new ArrayList<?>();
c) new ArrayList<? super Integer>();
d) new ArrayList<? extends Integer>();
e) new ArrayList<>();
f) new ArrayList<Number>();
g) new ArrayList<Object>();


A2. a and e (only from Java 8, the empty diamond is allowed on instantiation.

b, c, and d are illegal on Line 1 because ? (i.e. the wild card) types cannot be instantiated.

f and g are illegal on Line 1 because T is an Integer, and List<Number> and List<Object> cannot be converted to List<Integer>



Q3. Can you use generics with Java arrays?
A3.  No. One of the reasons to favor a List over an Array is because  a List supports generics to provide compile time type-safety check.

Q4. What do you understand by the term type erasure?
A4:  Generics in Java is implemented using type erasure that happens at compile time. This means a List&ltNumber&gt becomes just a List at run-time. This was done to preserve backward compatibility.

Q5. Given the following Pair class that takes Generic data types

public class Pair<T, S> {
 
 public T first;
 public S second;

 public Pair(T a, S b) { 
  first = a;
  second = b;
 }
 
}


Which of the following statements compile without errors?

a) Pair<String,Color> colorName = new Pair<String,Color>("Red", Color.RED);
b) Pair<Double,Double> coordinates = new Pair<Double,Double>(17.3,42.8);
c) Pair<String,Double> keyValue = new Pair<String,Double>("PI", "22/7");
d) Pair<String,Double> lookUp = new Pair<>("right-angle", 90.0);
e) Pair<String,String, String> lookUp = new Pair<>("a", "b", "c");


A5.  a, b, and d (empty-diamond compiles from Java 8 on wards).

c) won't compile as "22/7" should be of type Double and not String. The constructor expects an object of type Double.  Actual error: The constructor Pair<String,Double>(String, String) is undefined

e) won't compile as it expects only two arguments and not three. Actual error: Incorrect number of arguments for type Pair<T,S>; it cannot be parameterized with arguments <String, String, String>


Q6. Given the following implementation to count the number of occurrences of a given item. The example below counts the occurrences of number 6, and returns 3 as the count.

public class OccrrencesTest {

 public static  int countOccurrences(Integer[] list, Integer itemToCount) {
  int count = 0;
  if (itemToCount == null) {
   for (Integer listItem : list)
    if (listItem == null)
     count++;
  } else {
   for (Integer listItem : list)
    if (itemToCount.equals(listItem))
     count++;
  }
  return count;
 }
 
 public static void main(String[] args) {
  Integer[] numbers = {5,6,6,5,7,8,6};
  System.out.println(countOccurrences(numbers, 6));
 }
}


How will you ensure that the  implementation works with other types like String, Color, Double, etc ?


A6. If you want to use the static method approach, you method needs to use the generic method type, for example <T> as shown below. Note that the generic type is also used in the static method signature before the return type int.

public class OccrrencesTest {

 public static <T>  int countOccurrences(T[] list, T itemToCount) {
  int count = 0;
  if (itemToCount == null) {
   for (T listItem : list)
    if (listItem == null)
     count++;
  } else {
   for (T listItem : list)
    if (itemToCount.equals(listItem))
     count++;
  }
  return count;
 }
 
 public static void main(String[] args) {
  Integer[] numbers = {5,6,6,5,7,8,6};
  System.out.println(countOccurrences(numbers, 6));
 }
}




if you want to use instance method approach

public class OccrrencesTest<T> {

 public int countOccurrences(T[] list, T itemToCount) {
  int count = 0;
  if (itemToCount == null) {
   for (T listItem : list)
    if (listItem == null)
     count++;
  } else {
   for (T listItem : list)
    if (itemToCount.equals(listItem))
     count++;
  }
  return count;
 }
 
 public static void main(String[] args) {
  Integer[] numbers = {5,6,6,5,7,8,6};
  System.out.println(new OccrrencesTest<Integer>().countOccurrences(numbers, 6));
 }
}


In both examples, the type of T is inferred at compile-time. Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable.

You can now use other types like Color as shown below

Color[] numbers = {Color.RED, Color.blue};
System.out.println(new OccrrencesTest<Color>().countOccurrences(numbers, Color.RED));


Labels: ,

Apr 2, 2014

Java Web Service Pre Interview written test Questions and Answers

Q1. A web service protocol stack from bottom to top consists of

a) HTTP, SOAP, description language, UDDI
b) SMTP, XML messaging, WSDL, Service discovery
c) HTTP, XML messaging, WSDL, UDDI
d) HTTP, XML-RPC, WSDL, UDDI
e) HTTP, WSDL, SOAP, UDDI


A1. The answer is a,b,c, and d. The e is not right beacuse of the order.

This is an evolving standard, but the basic Web service protocol stack is (aka web service components)comprised of
  • Service transport is the lowest layer in the stack, and is responsible for transporting messages between applications. Currently, this layer includes hypertext transfer protocol (HTTP), Simple Mail Transfer Protocol (SMTP), file transfer protocol (FTP), and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP).
  • XML messaging layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this layer includes XML-RPC and SOAP.
  • Service description layer responsible for describing the public interface to a specific web service. Currently, service description is handled via the Web Service Description Language (WSDL or WADL[for RESTful]).
  • Service discovery layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via Universal Description, Discovery, and Integration (UDDI).

Q2. What are the key roles played in a Web service

a) Service provider, Service requestor, Service registry
b) producer, consumer, Service registry
c) producer, consumer
d) publish, bind, find

A2. The answer is a,b,c, and d.

Q3. Which of the following are in the WSDL document structure?

a) types, message, port type, binding
b) input, output, binding, exception
c) types, input, output, exception
d) input, output, operations, binding

A3. The anser is a.

types: The data types used by the web service.

message: The input and output messages used by the web service.

port type: The operations performed by the web service. This is analogous to a class in Java programming. This also defines the input/output via messages. This is the most important part of the wsdl.

binding: The communication protocol used by the web service.


Q4. What are the different types of operations available in a WSDL?

a) One-way
b) Request-Response
c) Solicit-Response
d) Notification or fire and forget

A4. The anser is a, b, c, and d. Supports all 4 types of operations.

One-way: The operation (or endpoint) recieves a message, but will not return a response.
Request-Response: The most common one. The operation (or endpoint) recieves a request message and responds with a response message.
Solicit-Response: The operation (or endpoint) sends a request message and recieves a correlated response message.
Notification or fire and forget: The operation (or endpoint) sends a request message, but will not wait for a response.


Q. What is the difference between Request-Response and Solicit-Response?
A. Solicit-Response is a push operation like Notification, but waits for a response. Request-Response is a pull operation.

The only way to tell the difference between a request-response operation and a solicit-response operation is the ordering of the input and output elements. In request-response, the input child element comes first. In solicit-response, the output child element comes first.


Q5. Which of the following are true?

a) SOAP is a protocol and REST is a concept without any defined spec at all
b) SOAP is a XML-based message protocol, while REST is an architectural style
c) You can send SOAP envelopes in a REST application.
d) The REST verbs are "get", "put", "post" and "delete" and the nouns are identified by URLs.
e) SOAP allows many different verbs to be applied to many different nouns.

A5: The answer is a,b,c,d, and e. All are true.

a, b, and c are true because they state the fact that SOAP is an XML based message protocol and REST is a concept or architectural style.

d is true because RESTful url define the noun via the urls like

http://localhost:8080/accounting-services/1.0/forecasting/account/123/transaction/567
http://localhost:8080/accounting-services/1.0/forecasting/account/123/transactions/search?txn-date=20120201
http://localhost:8080/accounting-services/1.0/forecasting/account/123/transaction

e is true because you use different functions in SOAP port-type definition

Q6. Though both RESTful web series and SOAP web service can operate cross platform, they are architecturally different to each other. Which of the following statements are correct?

a) REST is more simple and easy to use than SOAP, hence currently more popular.
b) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.
c) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA's.
d) REST supports different format like text, JSON and XML while SOAP only support XML.
e) REST web services call can be cached to improve performance.
f) SOAP provides more comprehensive security and transaction management.

A6: all are correct. SOAP Vs RESTful web service comparison


Q7. Which of the following statements are correct?

a) JAX-WS is an API for SOAP based web service.
b) JAX-RS is an API for RESTFul web service.
c) SOAP invokes services by calling RPC method, REST just simply calls services via URL path.
d) Apache CXF framework only supports JAX-WS
e) Jersey and RESTEasy are reference implementations of JAX-RS.

A7. a, b, c, and e are correct. d is incorrect because Apache CXF supports both JAX-WS and JAX-RS.




You may also like:  Java Web Services Interview Questions and Answers

Labels: ,

Mar 27, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 5

Q14: What will be the output for the following code snippet?

package com.writtentest8;

public class PersonMain {

 public static void main(String[] args) {
   Person p1 = new  Person("John");
   changReference(p1);
   System.out.println("After changing reference:"  + p1.getName());
   changName(p1);
   System.out.println("After changing name:"  + p1.getName());
 }

 static void changReference(Person person) {
   Person p2 = new Person("Peter");
   person = p2;
 }

 static void changName(Person person) {
   person.setName("Sam");
 }

 //inner class
 static class Person {
   private String name;

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

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  } 
 }
}



a) After changing reference:Peter
After changing name:Sam

b) After changing reference:John
After changing name:Sam

c) After changing reference:John
After changing name:John

d) After changing reference:Peter
After changing name:Peter

A14: The answer is b. Java uses pass by vlaue. When a reference is passed to a method, its reference is copied, but the original reference and the copied refrence will be pointing to the same object. When a primitive value is passed, its value is copied.

In the above example,

Step 1: reference p1 in the stack points to a new Person object created in the heap. When changReference(p1) is invoked, a copy of reference p1 is passed to the method changReference(Person person). Both references p1 and person will be pointing to the same "John" person object.

Step 2: Reference p2 will be referencing a new Person object named "Peter".

Step 3: When person = p2;, the person will be referencing "Peter", but reference p1 is still pointing to "John".

Step 4: When method changName(Person person) is invoked, p1 reference is again copied and reference person will be pointing to "John". Inside the method, the name is changed to "Sam" via the person refrence. Remmeber that p1 is also pointing to the same object, but its value has now changed to "Sam" via the copied reference person.

Step 5: So, p1 is pointing to "Sam" now.

Similar  Java coding written test question and answer with diagram 


Q15: What is the output of the following code snippet?

package com.writtentest9;

public class Xyz {

 public static void main(String[] args) {
   String s1 = "Hello";
   String s2 = new String(s1);
   String s3 = "Hello";
  
   System.out.println("s1 equals() s2 "   + s1.equals(s2)); 

   System.out.println("s1 == s2 "  + (s1 == s2)); 
   System.out.println("s1  == s3 " + (s1 == s3)); 
 }
}


a) s1 equals() s2 true
s1 == s2 false
s1 == s3 true

b) s1 equals() s2 true
s1 == s2 true
s1 == s3 true

c) s1 equals() s2 true
s1 == s2 false
s1 == s3 false

d) s1 equals() s2 false
s1 == s2 true
s1 == s3 false

A15: The answer is a. s1 and s2 are 2 different objects, but have the same value "Hello". So s1.equals(s2) is always true. But s1 == s2 is not true because those references are not pointing to the same "Hello" object, but 2 different objects happen to have same value.

Why is then s1 == s3 is true? 

This is the tricky bit. This is a special condition for String objects only. Not for any other objects. You know that String objects are immutable, and for performance reason Java stores Strings created without the new operator in a String pool. So, String s1 = "Hello"; will be stored in the String pool. When you create String s3 = "Hello";, the JVM first checks the String pool to see if the value "Hello" exists in the String pool. If it does, it will not create a new String object but, s3 will be pointing to the same object in the pool. This means, s1 and s3 will be pointing to the same String object. In other words, reference s1 == s3 is true.

You may also like


Labels: ,

Mar 20, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 4

Q10: When is an object needs to implement the Comparable interface?

a) When adding it to a HashSet.
b) When adding it to a TreeSet.
c) When adding it to a LinkedHashSet.
d) When adding it to any Java Collection class

A10: The answer is b.

1. HashSet is implemented using a HashMap, hence the elements are not ordered.

2. TreeSet is implemented using a tree structure(red-black tree algorithm). The elements in a set are sorted. It offers several methods to deal with the ordered set like first( ), last( ), headSet( ), tailSet( ), etc. Any object you add to it must implement the Comparable interface, otherwise it throws a runtime exception

Exception in thread "main" java.lang.ClassCastException: com.writtentest6.Employee cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1188)
at java.util.TreeMap.put(TreeMap.java:531)
at java.util.TreeSet.add(TreeSet.java:255)


TreeSet maintains the elements in the order in which the public int compareTo(String o) method is implemented. Any object that implements the Comparable interface must provide the public int compareTo(String o) method implementation.


3. LinkedHashSet is between a HashSet and TreeSet. It is implemented as a HashMap with a linked list running through it. So, it maintains the elements in the order in which they are added.


Q11: Given the following code

List plainList = new ArrayList();
List<String> specList = new ArrayList<String> ();


a) adding a non String object to specList will throw a compile-time error
b) adding a non String object to specList will throw a runtime error
c) adding a non String object to specList will be slower than adding it to a plainList
d) adding a non String object to specList will throw a checked exception
e) you can add any objects to a plainList


A11: Answer is a & e.

Java generics check happens at compile-time. Learn more at Java Interview Questions & Answers: Compile-time versus runtime. Generics is a bit tricky subject to master, and a must know topic to do well in coding and written tests, hence I have dedicated a whole chapter in my book "Core Java Career Essentials"


Q12: Which of the following are right way to run a thread in the JVM?

a) A class MyThreadClass that extends the Thread class, and

MyThreadClass myT = new MyThreadClass();
myT.start();


b) A class MyThreadClass that extends the Thread class, and

MyThreadClass myT = new MyThreadClass();
myT.run();




c) A class MyThreadClass that implements the Runnable interface, and

MyThreadClass myT = new MyThreadClass();
Thread t = new Thread(myT);
myT.start();


d) A class MyThreadClass that implements the Runnable interface, and

MyThreadClass myT = new MyThreadClass();
Thread t = new Thread(myT);
myT.run();



A12: Answer is a and c.

You need to invoke the start( ) method and not the run( ) method. Invoking the start( ) method will invoke the run( ) method indirectly.

Q. Why can't you invoke the run( ) method directly?
A. The start method makes sure the code runs in a new thread context. If you called run directly, then it would be like an ordinary method call and it would run in the context of the current thread instead of the new one. Invoking the start( ) method will invoke the run( ) method indirectly with its special code.


Q13: What value will the following method return?

public static int getSomeNumber( ){ 
 try{ 
  return 2; 
 } finally { 
  return 1; 
 } 
} 



a) 1 is returned
b) 2 is returned
c) Compile error "unreachable code is returned"
d) Runtime error "ambiguous return statement"

A13: The answer is a. 1 is returned because 'finally' has the right to override any exception/returned value by the try..catch block. It is a bad practice to return from a finally block as it can suppress any exceptions thrown from a try..catch block.

You may also like


Labels: ,

Mar 19, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 3



Q8: What will be the statement you add so that you invoke Abc's process( ) method?


package com.writtentest5;

public class Abc {

 public void process(){
    System.out.println("Processing Abc");
 }

}



package com.writtentest5;

public class Def extends Abc {
 
 public void process(){
    System.out.println("Processing Def");
    ___________________________________ //how will you invoke Abc's process method here?
 }
 

 public static void main(String[] args) {
    Abc myApp = new Def();
    myApp.process();
 }

}




A8: super.process( ) will invoke parent class's process( ) method.


Q9: Which of the following interfaces will you be concerned about when adding an object to a HashSet?


a) Collection
b) Set
c) SortedSet
d) List
e) All the above

A9: Answer is a and b.

The Set interface extends the Collection interface, and HashSet implements the  Set  interface. Hence a and b are correct. You can write either

Collection<String> col = new HashSet<String>();
col.add("a");

or

Set<String> col = new HashSet<String>();
col.add("a");


Coding to an interface is a best practice.

c) is wrong because the SortedSet is implemented by ConcurrentSkipListSet and TreeSet. if you write

SortedSet<String> col = new HashSet<String>();
col.add("a");


you will get a compile time error "Type mismatch"

If you write as

SortedSet<String> col = (SortedSet)new HashSet<String>();
col.add("a");


you will get a Runtime exception

Exception in thread "main" java.lang.ClassCastException: java.util.HashSet cannot be cast to java.util.SortedSet
at com.writtentest5.Def.main(Def.java:19)


Note: There are a number of Set implementations listed below, but their behaviors are quite different.

  • java.util.EnumSet
  • java.util.HashSet
  • java.util.LinkedHashSet
  • java.util.TreeSet


You may also like





Labels: ,

Mar 11, 2014

Top 15 Core Java pre-interview technical written test questions and answers -- part 2

Extends Java written test pre-interview Questions and Answers 1-3.

Q4: Given the following class with an equals(...) method


package com.writtentest4;

public class Xyz {
 
 int a, b;

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  
  if (obj == null)
   return false;
  
  if (getClass() != obj.getClass())
   return false;
  
  Xyz other = (Xyz) obj;
  
  if (b != other.b)
   return false;
  
  return true;
 }
 
}


Which of the following hashCode( ) method implementation is correct.

a) public int hashCode() { return a;}
b) public int hashCode() { return a+b;}
c) public int hashCode() { return a*b;}
d) public int hashCode() { return b;}


A4: The answer is d. As per the equals(..) and hashCode( ) contract, whatever fields used in equals(..) must be used in hashCode( ); Since only field "b" is used in equals(...), the hashCode( ) should also use only "b". Can't use "a" because it will break the contract. Refer to the Object class api methods hashCode( ) & equals(..) for the contract.


Q5. An IllegalArgumentException is thrown from

a) JVM when wrong method arguments are passed.
b) pre-condition check on a public method.
c) pre-condition check from a private method.
d) pre-condition check from a public or private method.

A5. The answer is b. You need to understand 2 things here.

1. Firstly, common exceptions classes in Java are:

Runtime exceptions thrown by JVM 



  • ArrayIndexOutOfBoundsException: when your code uses an array index, which is outside the array's bounds.
  • NullPointerException: when your code attempts to use a null reference where an object reference is required.
  • ClassCastException: when an attempt is made to cast an object reference fails.
  • NoClassDefFoundError: thrown by the JVM or class loader when the definition of a class cannot be found. In JDK 1.7 the error message is simplified to "Error: Could not find or load main class xxx" instead of a detailed stack trace.

Runtime exceptions  thrown programmatically

  • NumberFormatException: when an attempt is made to convert a string to a numeric type, but the string does not have the appropriate format. 
  • IllegalArgumentException: to indicate that a method has been passed an illegal or inappropriate argument. For example, a null object or a percentage  value less than 0 or greater than 100. This extends "IllegalStateException".
  • IllegalStateException: when a method is invoked and the program is not in an appropriate state for that method to perform its task. This typically happens when a method is invoked out of sequence, or perhaps a method is only allowed to be invoked once and an attempt is made to invoke it again.


All the above exceptions thrown by either JVM or programmatically indicate a bug in your application and need to be fixed.

2. Design by contract allows you to write fail-fast programs at runtime. The fail-fast programs need to check the validity of the arguments (pre-condition) passed into "public" method.  The public methods exposed and anyone could call the "public" methods with invalid arguments. On the other hand, private methods are under your sole control and it is appropriate to assert the pre-conditions as opposed to throwing an IllegalArgumentException.


Q6. What method do you invoke on the thread class to pause until a signal is received from the other threads?
A6. wait( ) or wait(2000). 

The wait( ), notify (), and notifyAll( ) methods are used to provide an efficient way for threads to communicate with each other. This communication solves the ‘consumer-producer problem’. This problem occurs when the producer thread is completing work that the other thread (consumer thread) will use. Refer Java Multithreading Interview Questions and Answers


Q7. What do you do when an ArrayIndexOutOfBoundsException is thrown?

a) Catch it and do nothing.
b) Catch it and log the full stack trace.
c) Don't do anything as it is a Runtime exception it will bubble all the way up.
d) All of the above.

A7. The answer is c.

The a) is an anti-pattern to to hide exceptions.
The b) is not a best practice to unnecessarily catch and then log. The ArrayIndexOutOfBoundsException indicates a bug in the application, hence it must be fixed and not logged. It will hide the bug unless someone is monitoring the logs or you have Nagios based alert setup to raise alerts and help desk tickets.

You may also like


Labels: ,

Mar 7, 2014

Top 15 Core Java pre-interview technical written test questions and answers

Written tests can help short-list candidates and often used by recruitment agencies  and prospective employers. Here are some popular written test questions and answers.

Note: Multiple choice questions may have more than one right answers.

Q1. What will be the output of the following code snippet?


package com.writtentest1;

public class Base {
 int i;

 public Base() {
   add(1);
 }

 public void add(int j) {
   i += j;
 }

}


package com.writtentest1;

public class Extension extends Base {

 public Extension() {
   add(2);
 }

 public void add(int j) {
   i += j*2;
 }
}


package com.writtentest1;

public class Main {

 public static void main(String[] args) {
   exec(new Extension());
 }

 private static void exec(Base base) {
   base.add(8);
   System.out.println(base.i);
 }

}


a) 21
b) 22
c) 20
d) 16
e) 17


A1. The answers is b, i.e 22.

Step 1: When new Extension( ) is invoked it invokes the constructor Extension( ).
Step 2: The trick here is that default constructors implicitly call super( ), so Base( ) constructor will be invoked next.
Step 3: Base( ) --> add(1) method on Extension class as the stored object is of type Extension and polymorphic will kick in. The value of i becomes 0 + 1*2 = 2.
Step 4: add(2) is invoked from Extension constructor. The i becomes 2 + 2*2 = 6;
Step 5: Finally, add(8) is invoked from Main --> exec, and i becomes 6 + 2*8 = 22.

Q2. What will be happen when you run the following code?

package com.writtentest2;

public class ThreadMain {

 public static void main(String[] args) {
  
  Runnable runnable = new Runnable() {
   
   @Override
   public void run() {
     try {
       System.out.print("Going to sleep. "); 
       Thread.sleep(5000);
     } catch (InterruptedException e) {
       e.printStackTrace();
     } 
     System.out.print("Has woken up. "); 
   }
  };
  
  Thread thread = new Thread(runnable);
  thread.start();
  
  
  try {
    thread.join();
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  
   System.out.print("Completed.");
 }

}


a) prints: Going to sleep. Has woken up. Completed.
b) InterruptedException is thrown with a stack trace.
c) prints: Completed. Going to sleep. Has woken up.
d) prints: Completed.

A2. The answer is a.

There are 2 threads involved in this. Main thread and the worker thread "thread". The main thread spawns the new thread and when thread.start( ) is invoked the run( ) method inside the anonymous inner class for Runnable interface is executed and prints "Going to sleep. ". In the mean time the Main thread is blocked due to thread.join( ) statement. The worker thread sleeps for at least 5 seconds, and then prints "Has woken up. " and it completes its execution. Once the worker thread "thread" has finished, the main thread continues and prints "Completed."

Try commenting out thread.join( ); and its try/catch block see what happens to the output.

Q3: Given the following interface,

package com.writtentest3;

public interface Ixy {
    abstract String get();
    abstract void set(String value);
}


Which of the following statements are correct?

a)

package com.writtentest3;

public  abstract class IxyImpl implements Ixy {

   public  void calc(String value){}
}


b)

package com.writtentest3;

public  class IxyImpl implements Ixy {

 @Override
 public String get() {
    return null;
 }

 public  void calc(String value){}

}


c)

package com.writtentest3;

public  class IxyImpl {

 @Override
 public String get() {
    return null;
 }

 public  void calc(String value){}

}


d)

package com.writtentest3;

public  class IxyImpl {

 public String get() {
    return null;
 }

 public  void calc(String value){}

}



A3. Answer is: a and d.

a: No compile error since the class is abstract, even though it does not implement all the methods from the interface.
b: Compile error because it is a concrete class, and does not implement the abstract method void set(String value).
c: Compile error because it does not implement the interface Ixy, but the method public String get( ) is still annotated with @Override
d: No compile error as the @Override annotation is no longer there.


You may also like


Labels: ,