50 Java Interveiw Questions

Typical HR Questions

1. What are the thread states in java ?

State Description
NEW A thread that has not yet started is in this state.
RUNNABLE A thread executing in the Java virtual machine is in this state.
BLOCKED A thread that is blocked waiting for a monitor lock is in this state.
WAITING A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED A thread that has exited is in this state.

2. List all the inner classes ?

Class Type Description
static inner class the static inner class can only access the static fields of the enclosing class and define its own static fields.
non static inner class the inner class can access all the fields of the enclosing class, they can define there own fields but these can not be static.
local class This is a class inside a method, the local inner class can access all the fields from the enclosing class and all final parameters from the enclosing method, they can define there own fields but these can not be static.
anonymous class

3. How to increase the heap memory of the JVM ?

-Xmx (maximum heap size)

4. Name three JVMs ?

HotSpot
JRockit
Windows JVM


5. What is the quickest type of HashMap ?

IdentityHashMap()

6. How do you redirect the System.out ( "standard" output stream ) to a file ?

System.setOut(...)

7. A class that supports serializarion must implement serializable, if its base class is not serizable then what must it have. ?

A default constructor


8. Which method should you override when writing a Customer Class Loader ?

you should override the findClass() method, see example below :

class CustomClassLoader extends ClassLoader {
         String host;
         int port;
 
         public Class findClass(String name) {
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         }
 
         private byte[] loadClassData(String name) {
             // load the class data from the connection
         }
    }
 
  // then to load your class
  Class r = new CustomClassLoader().findClass("com.x.MyClass");
 
 or 
 
 Class.forName("com.x.MyClass",true,new CustomClassLoader());

9. Name the standard class loaders ?

cl_hierarchy.gif

10. What is the signature of readResolve() and what is it used for ?

The read resolve method will be called ( if exists ) to create the object. Note : the constructor of the object does not get called is read resolve is called ( so this is one way to create an object without calling its constructor )

ANY-ACCESS-MODIFIER Object readResolve()
            throws ObjectStreamException;

11. Other than using externizable, how can you handle custom sterilization?

Just provide the following methods in your class being serialized. note: the private access modifiers.

private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;

12. In java 6, how can you see the assembly code that the JIT is creating ?

-XX:+PrintOptoAssembly

more details


13. Name 10 Ways to Reduce Lock Contention in Threaded Programs ?

1.Protect data, not code.
2.Get rid of expensive calculations while in locks.
3.Use lock striping.
4.Employ interlocked / atomic operations.
5.Use synchronized data structures.
6.Use Reader-Writer Locks where applicable.
7.Use Read-Only data whenever possible.
8.Avoid Object Pooling.
9.Use local variables or thread-local storage.
10. Avoid hotspots.

more details


14. List 4 Collection Classes and 4 Collection Interfaces ?

(some of them are listed below )

Classes
ArrayList
HashSet
HashMap
LinkedList
LinkedHashSet
LinkedHashMap
ConcurrentHashMap
ArrayDeque
Stack
TreeSet
ConcurrentSkipListMap

Interfaces
Iterable
Collection
List
Set
Map
NavitableSet
NavitableMap
Deque
Queue
SortedSet


15. How do you create an array using reflection

use Array.newInstance(String.class, 10);

import java.lang.reflect.*;
 
public class array1 {
      public static void main(String args[])
      {
         try {
            Class cls = Class.forName(
              "java.lang.String");
            Object arr = Array.newInstance(cls, 10);
            Array.set(arr, 5, "this is a test");
            String s = (String)Array.get(arr, 5);
            System.out.println(s);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
}

15. Describethe following exceptions : CloneNotSupportedException, ClassNotFoundException, ArrayStoreException, ClassCastException, ConcurrentModificationException, IllegalMonitorStateException, UnsupportedOperationException.

Checked Exceptions
CloneNotSupportedException Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.
ClassNotFoundException Thrown when an application tries to load in a class through its string name, and this fails.

Runtime Exceptions
ArrayStoreException Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
ClassCastException Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
ConcurrentModificationException
IllegalMonitorStateException Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.
UnsupportedOperationException Thrown to indicate that the requested operation is not supported.


16 With java collections, whats the difference between Offer(E e) and Add(E e).

generally the following is true :

Throws exception Special value
add offer
remove poll
get peek

Add(E e) Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an Exception if no space is currently available.

Offer() Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally preferable to add(E), which can fail to insert an element only by throwing an exception. It is implemented in Queue and Deque.


17 Can a top level class be have a protected class modifier

No, only inner class can have protected class modifier access.

more coming soon….

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License