Showing posts with label Java interview questions. Show all posts
Showing posts with label Java interview questions. Show all posts

Thursday, February 20, 2014

Java : Few basic things to know about "finally" block in Exception handling

finally block is used to as cleanup facility in case of program abruptly interrupts due to exception. e.g. Closing I/O resources, closing connection etc.

Lets find out more details about finally block and answers to few basic questions.
Question 1: Can we write try block without catch?
Answer: Yes. we can write try - finally block as shown in below code example.

Question 2 : Whether finally block is executed if exception is thrown from try block?
Answer : Yes. Code in finally block will be executed even if exception is thrown from try block.

Question 3: Exception A is thrown from try block and while executing finally block, exception B is thrown. Which exception will be thrown to calling method?
Answer : Exception B which is thrown from finally block. Exception thrown from try block is discarded

Code to verify above scenarios:


/**
* Program to show how exception in try block is discarded if there is exception in finally block
*/
public class TestException {

public static void main(String[] args) {
try {
testException();
} catch (Exception e) {
System.out.println(e);
}

}

public static void testException(){
Integer j = null;
Integer k;
String [] strArray = new String []{"aa"};
try {
System.out.println("In try");
//ArrayIndexOutOfBoundsException will be thrown from below code
String testStr = strArray[1];
}
finally{
System.out.println("in finally");
//NullPointerException will be thrown from below code as j is null.
k = j *10;
}
}

}

Output after program execution:

In try
in finally
java.lang.NullPointerException


Monday, January 13, 2014

Java: Generics and Inheritance- Important things

Generics helps to write code in easy way.
-Generics makes code robust by adding strong type check at compile time check.
- Casting is not required as you define type while creating objects.


There is very important point to note related to Generics and Inheritance concept of OOPS.

Consider following java class:


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestGenericList {

/**
* @param args
*/
public static void main(String[] args) {
List< String > strList  = new ArrayList < String >();
 strList .add("a");
 strList .add("b");
 strList .add("c");
TestGenericList t = new TestGenericList();
// Can we use below code to call printList?
// t.printList(strList );

}

public void printList(List < Object > list  ){
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println(object);

}
}
}


We know that String extends Object so you assume that you can pass strList object to printList function.
WRONG
You can not pass strList to printList function as function accept list of Object.

Even though String extends Object but List does not extend List< Object >



You can refer java tutorials for more details at:
http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html

Thursday, July 4, 2013

Java: Thread Basics and Questions

Here are few general questions and answers related to Threads in Java

1. What is thread?
--> Thread is lightweight process which has its own stack trace but share resources.

2. Types of Thread:
--> Daemon thread and User thread : JVM exits when all user threads complete. It does not care whether daemon threads are complete or not.

3. How can we create Thread in java
--> a)  By extending Thread class
      b) By Implementing Runnable interface
Implementing Runnable is preferred because extending a Thread is meant to create specialized version of Class Thread where we may need some special behaviour. And We always instantiate thread by creating new instance of Thread class.

4. How to start a new thread?
--> by calling start() method of thread instance.

5. Explain different Thread states:
--> New : When thread instance is created and start method is not yet invoked. Thread t = new Thread(Runnable r);
Runnable: When thread is eligible to run but execution is not started. Threads enters in runnable state for first time when start() method is called. Thread also enters in runnable state after coming back from blocked, waiting, sleeping state.
Running: When scheduler picks thread for execution from runnable pool.
Waiting/Sleeping/Blocking: When thread is still alive but not eligible to run. Thread is not runnable but it might come to runnable when particular event happens.
Dead: Thread is dead when its run method completes. Once thread is dead, it cannot be invoke again by calling start(). It will generate runtime exception. Thread object is still valid object but not valid for separate thread of execution.

6. What is yield() method of Thread:
--> yield() method make currently running thread back to runnable pool to get other threads in runnable pool to get chance. But it is not guaranteed. Same thread can be picked up for execution by thread scheduler. When yield() is called. Thread goes from Running to Runnable state.

7. What is join() method:
--> Let one thread to join at the end of another thread. when t.join() is called. Currently running thread to join at the end of t. It means that currently running thread is blocked till t thread is complete.

8. When Currently running thread leaves running state:
a. When thread is complete. (run method is complete)
b. Thread can not acquire lock on object whose method it is trying to call.
c. When scheduler decides to move thread from running to runnable state.
d. Call to wait() on object

9. How can you prevent more than one threads to access code in Java
--> Using synchronization. We can use either synchronized method or synchronized block so that only one thread can access that method/block of code at a time.

10. How synchronization works
--> Synchronization work with lock on object. Every object in java has built in lock. When non-static method is synchronized, Thread which is running the code acquires lock on object which is calling method. No other thread can call synchronized method for that object unless current thread comes out of sync. method.
When synchronized method completes, thread releases lock so that other threads can call synchronized method on that object. Same applies for Synchronized block.
We declare synchronized block with synchronized(object){ }. We can pass any object as parameter to synchronized block. Thread acquires lock on that object. If we pass "this" as parameter to synchronized block, current instance of that class is locked.
Static methods can be synchronized. There is class instance (only one instance) of every class on which thread acquires lock.

Note: wait() method gives up lock while sleep(), yield(),join(), notify() keeps lock.

11. How thread interact with each other.
--> Using wait(), notify(), notifyAll(). Note that these methods should be called from synchronized block/method.