Jul 5, 2008

CORE JAVA FAQ-2

JAVA EXCEPTION HANDLING INTERVIEW QUESTIONS AND ANSWERS

1) Which package contains exception handling related classes?
java.lang

2) What are the two types of Exceptions?
Checked Exceptions and Unchecked Exceptions.

3) What is the base class of all exceptions?
java.lang.Throwable

4) What is the difference between Exception and Error in java?
Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow.

5) What is the difference between throw and throws?
throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{}

6) Differentiate between Checked Exceptions and Unchecked Exceptions?
Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error.

Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it's subclasses, Error and it's subclasses fall under unchecked exceptions.

7) What are User defined Exceptions?
Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.

8) What is the importance of finally block in exception handling?
Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc.

9) Can a catch block exist without a try block?
No. A catch block should always go with a try block.

10) Can a finally block exist with a try block but without a catch?
Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

11) What will happen to the Exception object after exception handling?
Exception object will be garbage collected.

12) The subclass exception should precede the base class exception when used within the catch clause. True/False?
True.

13) Exceptions can be caught or rethrown to a calling method. True/False?
True.

14) The statements following the throw keyword in a program are not executed. True/False?
True.

15) How does finally block differ from finalize() method?
Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected.

16) What are the constraints imposed by overriding on exception handling?
An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class.

JAVA THREADS INTERVIEW QUESTIONS AND ANSWERS

1) What are the two types of multitasking?
a. Process-based.
b. Thread-based.

2) What is a Thread ?
A thread is a single sequential flow of control within a program.

3) What are the two ways to create a new thread?
a.Extend the Thread class and override the run() method.
b.Implement the Runnable interface and implement the run() method.

4) If you have ABC class that must subclass XYZ class, which option will you use to create a thread?
I will make ABC implement the Runnable interface to create a new thread, because ABC class will not be able to extend both XYZ class and Thread class.

5) Which package contains Thread class and Runnable Interface?
java.lang package

6) What is the signature of the run() mehod in the Thread class?
public void run()

7) Which methods calls the run() method?
start() method.

8) Which interface does the Thread class implement?
Runnable interface

9) What are the states of a Thread ?
Ready,Running, Waiting and Dead.

10) Where does the support for threading lie?
The thread support lies in java.lang.Thread, java.lang.Object and JVM.

11) In which class would you find the methods sleep() and yield()?
Thread class

12) In which class would you find the methods notify(),notifyAll() and wait()?
Object class

13) What will notify() method do?
notify() method moves a thread out of the waiting pool to ready state, but there is no guaranty which thread will be moved out of the pool.

14) Can you notify a particular thread?
No.

15) What is the difference between sleep() and yield()?
When a Thread calls the sleep() method, it will return to its waiting state. When a Thread calls the yield() method, it returns to the ready state.

16) What is a Daemon Thread?
Daemon is a low priority thread which runs in the backgrouund.

17) How to make a normal thread as daemon thread?
We should call setDaemon(true) method on the thread object to make a thread as daemon thread.

18) What is the difference between normal thread and daemon thread?
Normal threads do mainstream activity, whereas daemon threads are used low priority work. Hence daemon threads are also stopped when there are no normal threads.

19) Give one good example of a daemon thread?
Garbage Collector is a low priority daemon thread.

20) What does the start() method of Thread do?
The thread's start() method puts the thread in ready state and makes the thread eligible to run. start() method automatically calls the run () method.

21) What are the two ways that a code can be synchronised?
a. Method can be declared as synchronised.
b. A block of code be sychronised.

22) Can you declare a static method as synchronized?
Yes, we can declare static method as synchronized. But the calling thread should acquire lock on the class that owns the method.

23) Can a thread execute another objects run() method?
A thread can execute it's own run() method or another objects run() method.

24) What is the default priority of a Thread?
NORM_PRIORITY

25) What is a deadlock?
A condition that occurs when two processes are waiting for each other to complete before proceeding. The result is that both processes wait endlessly.

26) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?
a. wait(),notify() & notifyall()
b. Object class

27) What is the mechanisam defind in java for a code segment be used by only one Thread at a time?
Synchronisation

28) What is the procedure to own the moniter by many threads?
Its not possible. A monitor can be held by only one thread at a time.

29) What is the unit for 500 in the statement, obj.sleep(500);?
500 is the no of milliseconds and the data type is long.

30) What are the values of the following thread priority constants?
MAX_PRIORITY,MIN_PRIORITY and NORMAL_PRIORITY
10,1,5

31) What is the default thread at the time of starting a java application?
main thread

32) The word synchronized can be used with only a method. True/ False?
False. A block of code can also be synchronised.

33) What is a Monitor?
A monitor is an object which contains some synchronized code in it.

34) What are all the methods defined in the Runnable Interface?
only run() method is defined the Runnable interface.

35) How can i start a dead thread?
A dead Thread cannot be started again.

36) When does a Thread die?
A Thread dies after completion of run() method.

37) What does the yield() method do?
The yield() method puts currently running thread in to ready state.

38) What exception does the wait() method throw?
The java.lang.Object class wait() method throws "InterruptedException".

39) What does notifyAll() method do?
notifyAll() method moves all waiting threads from the waiting pool to ready state.

40) What does wait() method do?
wait() method releases CPU, releases objects lock, the thread enters into pool of waiting threads.

JAVA COLLECTIONS INTERVIEW QUESTIONS AND ANSWERS

1) Explain Java Collections Framework?
Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects.

2) Explain Iterator Interface.
An Iterator is similar to the Enumeration interface.With the Iterator interface methods, you can traverse a collection from start to end and safely remove elements from the underlying Collection. The iterator() method generally used in query operations.
Basic methods:
iterator.remove();
iterator.hasNext();
iterator.next();

3) Explain Enumeration Interface.
The Enumeration interface allows you to iterate through all the elements of a collection. Iterating through an Enumeration is similar to iterating through an Iterator. However, there is no removal support with Enumeration.
Basic methods:
boolean hasMoreElements();
Object nextElement();

4) What is the difference between Enumeration and Iterator interface?
The Enumeration interface allows you to iterate through all the elements of a collection. Iterating through an Enumeration is similar to iterating through an Iterator. However, there is no removal support with Enumeration.

5) Explain Set Interface.
In mathematical concept, a set is just a group of unique items, in the sense that the group contains no duplicates. The Set interface extends the Collection interface. Set does not allow duplicates in the collection. In Set implementations null is valid entry, but allowed only once.

6) What are the two types of Set implementations available in the Collections Framework?
HashSet and TreeSet are the two Set implementations available in the Collections Framework.

7) What is the difference between HashSet and TreeSet?
HashSet Class implements java.util.Set interface to eliminate the duplicate entries and uses hashing for storage. Hashing is nothing but mapping between a key value and a data item, this provides efficient searching.

The TreeSet Class implements java.util.Set interface provides an ordered set, eliminates duplicate entries and uses tree for storage.

8) What is a List?
List is a ordered and non duplicated collection of objects. The List interface extends the Collection interface.

9) What are the two types of List implementations available in the Collections Framework?
ArrayList and LinkedList are the two List implementations available in the Collections Framework.

10) What is the difference between ArrayList and LinkedList?
The ArrayList Class implements java.util.List interface and uses array for storage. An array storage's are generally faster but we cannot insert and delete entries in middle of the list.To achieve this kind of addition and deletion requires a new array constructed. You can access any element at randomly.

The LinkedList Class implements java.util.List interface and uses linked list for storage.A linked list allow elements to be added, removed from the collection at any location in the container by ordering the elements.With this implementation you can only access the elements in sequentially.

11) What collection will you use to implement a queue?
LinkedList

12) What collection will you use to implement a queue?
LinkedList

13) Explain Map Interface.
A map is a special kind of set with no duplicates.The key values are used to lookup, or index the stored data. The Map interface is not an extension of Collection interface, it has it's own hierarchy. Map does not allow duplicates in the collection. In Map implementations null is valid entry, but allowed only once.

14) What are the two types of Map implementations available in the Collections Framework?
HashMap and TreeMap are two types of Map implementations available in the Collections Framework.

15) What is the difference between HashMap and TreeMap?
The HashMap Class implements java.util.Map interface and uses hashing for storage. Indirectly Map uses Set functionality so, it does not permit duplicates. The TreeMap Class implements java.util.Map interface and uses tree for storage. It provides the ordered map.

16) Explain the functionality of Vector Class?
Once array size is set you cannot change size of the array. To deal with this kind of situations in Java uses Vector, it grows and shrink it's size automatically. Vector allows to store only objects not primitives. To store primitives, convert primitives in to objects using wrapper classes before adding them into Vector.The Vector reallocates and resizes itself automatically.

17) What does the following statement convey?
Vector vt = new Vector(3, 10);

vt is an instance of Vector class with an initial capacity of 3 and grows in increment of 10 in each relocation

18) How do you store a primitive data type within a Vector or other collections class?
You need to wrap the primitive data type into one of the wrapper classes found in the java.lang package, like Integer, Float, or Double, as in:
Integer in = new Integer(5);

19) What is the difference between Vector and ArrayList?
Vector and ArrayList are very similar. Both of them represent a growable array. The main difference is that Vector is synchronized while ArrayList is not.

20) What is the between Hashtable and HashMap?
Both provide key-value access to data. The key differences are :
a. Hashtable is synchronised but HasMap is not synchronised.
b. HashMap permits null values but Hashtable doent allow null values.
c. iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not fail safe.

21) How do I make an array larger?
You cannot directly make an array larger. You must make a new (larger) array and copy the original elements into it, usually with System.arraycopy(). If you find yourself frequently doing this, the Vector class does this automatically for you, as long as your arrays are not of primitive data types.

22) Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access?
Because a synchronized HashMap requires an extra method call, a Hashtable is faster for synchronized access.

23) In which package would you find the interfaces amd claases defined in the Java Collection Framework?
java.util

24) What method in the System class allows you to copy eleemnts from one array to another?
System. arraycopy()

25) When using the System.arraycopy() method,What exception is thrown if the destination array is smaller than the souce array?
ArrayIndexOutofBoundsException

26) What is the use of Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region

27) What is the use of GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars

28) What is the use of SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar

29) What is the use of ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

JAVA GARBAGE COLLECTION INTERVIEW QUESTIONS AND ANSWERS
1) Explain Garbage collection in Java?
In Java, Garbage Collection is automatic. Garbage Collector Thread runs as a low priority daemon thread freeing memory.

2) When does the Garbage Collection happen?
When there is not enough memory. Or when the daemon GC thread gets a chance to run.

3) When is an Object eligible for Garbage collection?
An Object is eligble for GC, when there are no references to the object.

4) What are two steps in Garbage Collection?
1. Detection of garbage collectible objects and marking them for garbage collection.
2. Freeing the memory of objects marked for GC.

5) What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

6) Can GC be forced in Java?
No. GC can't be forced.

7) What does System.gc() and Runtime.gc() methods do?
These methods inform the JVM to run GC but this is only a request to the JVM but it is up to the JVM to run GC immediately or run it when it gets time.

8) When is the finalize() called?
finalize() method is called by the GC just before releasing the object's memory. It is normally advised to release resources held by the object in finalize() method.

9) Can an object be resurrected after it is marked for garbage collection?
Yes. It can be done in finalize() method of the object but it is not advisable to do so.

10) Will the finalize() method run on the resurrected object?
No. finalize() method will run only once for an object. The resurrected object's will not be cleared till the JVM cease to exist.

11) GC is single threaded or multi threaded?
Garbage Collection is multi threaded from JDK1.3 onwards.

12) What are the good programming practices for better memory management?
a. We shouldn't declare unwanted variables and objects.
b. We should avoid declaring variables or instantiating objects inside loops.
c. When an object is not required, its reference should be nullified.
d. We should minimize the usage of String object and SOP's.

13) When is the Exception object in the Exception block eligible for GC?
Immediately after Exception block is executed.

14) When are the local variables eligible for GC?
Immediately after method's execution is completed.

15) If an object reference is set to null, Will GC immediately free the memory held by that object?
No. It will be garbage collected only in the next GC cycle.

JAVA LANG PACKAGE INTERVIEW QUESTIONS AND ANSWERS
1) What is the base class of all classes?
java.lang.Object

2) What do you think is the logic behind having a single base class for all classes?
1. casting
2. Hierarchial and object oriented structure.

3) Why most of the Thread functionality is specified in Object Class?
Basically for interthread communication.

4) What is the importance of == and equals() method with respect to String object?
== is used to check whether the references are of the same object.
.equals() is used to check whether the contents of the objects are the same.
But with respect to strings, object refernce with same content
will refer to the same object.

String str1="Hello";
String str2="Hello";

(str1==str2) and str1.equals(str2) both will be true.

If you take the same example with Stringbuffer, the results would be different.
Stringbuffer str1="Hello";
Stringbuffer str2="Hello";

str1.equals(str2) will be true.
str1==str2 will be false.


5) Is String a Wrapper Class or not?
No. String is not a Wrapper class.

6) How will you find length of a String object?
Using length() method of String class.

7) How many objects are in the memory after the exection of following code segment?
String str1 = "ABC";
String str2 = "XYZ";
String str1 = str1 + str2;
There are 3 Objects.

8) What is the difference between an object and object reference?
An object is an instance of a class. Object reference is a pointer to the object. There can be many refernces to the same object.

9) What will trim() method of String class do?
trim() eliminate spaces from both the ends of a string.***

10) What is the use of java.lang.Class class?
The java.lang.Class class is used to represent the classes and interfaces that are loaded by a java program.
11) What is the possible runtime exception thrown by substring() method?
ArrayIndexOutOfBoundsException.

12) What is the difference between String and Stringbuffer?
Object's of String class is immutable and object's of Stringbuffer class is mutable moreover stringbuffer is faster in concatenation.

13) What is the use of Math class?
Math class provide methods for mathametical functions.

14) Can you instantiate Math class?
No. It cannot be instantited. The class is final and its constructor is private. But all the methods are static, so we can use them without instantiating the Math class.

15) What will Math.abs() do?
It simply returns the absolute value of the value supplied to the method, i.e. gives you the same value. If you supply negative value it simply removes the sign.

16) What will Math.ceil() do?
This method returns always double, which is not less than the supplied value. It returns next available whole number

17) What will Math.floor() do?
This method returns always double, which is not greater than the supplied value.

18) What will Math.max() do?
The max() method returns greater value out of the supplied values.

19) What will Math.min() do?
The min() method returns smaller value out of the supplied values.

20) What will Math.random() do?
The random() method returns random number between 0.0 and 1.0. It always returns double.


JDBC INTERVIEW QUESTIONS AND ANSWERS
1) What is JDBC?
JDBC is a layer of abstraction that allows users to choose between databases. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database.

2) How many types of JDBC Drivers are present and what are they?
There are 4 types of JDBC Drivers Type 1: JDBC-ODBC Bridge Driver Type 2: Native API Partly Java Driver Type 3: Network protocol Driver Type 4: JDBC Net pure Java Driver

3) Explain the role of Driver in JDBC?
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendors driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

4) Is java.sql.Driver a class or an Interface ?
It's an interface.

5) Is java.sql.DriverManager a class or an Interface ?
It's a class. This class provides the static getConnection method, through which the database connection is obtained.

6) Is java.sql.Connection a class or an Interface ?
java.sql.Connection is an interface. The implmentation is provided by the vendor specific Driver.

7) Is java.sql.Statement a class or an Interface ?
java.sql.Statement,java.sql.PreparedStatement and java.sql.CallableStatement are interfaces.

8) Which interface do PreparedStatement extend?
java.sql.Statement

9) Which interface do CallableStatement extend?
CallableStatement extends PreparedStatement.

10) What is the purpose Class.forName("") method?
The Class.forName("") method is used to load the driver.
11) Do you mean that Class.forName("") method can only be used to load a driver?
The Class.forName("") method can be used to load any class, not just the database vendor driver class.

12) Which statement throws ClassNotFoundException in SQL code block? and why?
Class.forName("") method throws ClassNotFoundException. This exception is thrown when the JVM is not able to find the class in the classpath.

13) What exception does Class.forName() throw?
ClassNotFoundException.

14) What is the return type of Class.forName() method ?
java.lang.Class

15) Can an Interface be instantiated? If not, justify and explain the following line of code:
Connection con = DriverManager.getConnection("dsd","sds","adsd");
An interface cannot be instantiated. But reference can be made to a interface. When a reference is made to interface, the refered object should have implemented all the abstract methods of the interface. In the above mentioned line, DriverManager.getConnection method returns Connection Object with implementation for all abstract methods.

16) What type of a method is getConnection()?
static method.

17) What is the return type for getConnection() method?
Connection object.

18) What is the return type for executeQuery() method?
ResultSet

19) What is the return type for executeUpdate() method and what does the return type indicate?
int. It indicates the no of records affected by the query.

20) What is the return type for execute() method and what does the return type indicate?
boolean. It indicates whether the query executed sucessfully or not.
21) is Resultset a Classor an interface?
Resultset is an interface.

22) What is the advantage of PrepareStatement over Statement?
PreparedStatements are precompiled and so performance is better. PreparedStatement objects can be reused with passing different values to the queries.

23) What is the use of CallableStatement?
CallableStatement is used to execute Stored Procedures.

24) Name the method, which is used to prepare CallableStatement?
CallableStament.prepareCall().

25) What do mean by Connection pooling?
Opening and closing of database connections is a costly excercise. So a pool of database connections is obtained at start up by the application server and maintained in a pool. When there is a request for a connection from the application, the application server gives the connection from the pool and when closed by the application is returned back to the pool. Min and max size of the connection pool is configurable. This technique provides better handling of database connectivity.

No comments: