New Microsoft Office Word Document

Document Sample
New Microsoft Office Word Document Powered By Docstoc
					Java Questions:

  1. On a scale of 5, how do you rate yourself in Java?
  2. What are the four pillars of Object Oriented Programming (OOPS)?
  3. What is Encapsulation?
  4. What is Abstraction?
  5. What is the difference between Encapsulation and Abstraction?
  6. What are access specifiers?
  7. Explain each of the access specifiers: public, default, protected and private.
  8. Is the default access specifier same as protected?
  9. Can I access a default member from inside a Sub class?
  10. Can I access a protected member from a Sub class outside the package of its Base class?
  11. What is an anonymous class? Can you write code to define an anonymous class?
  12. What is the difference between a String and a StringBuffer?
  13. What is the output upon execution of the following code snippet?

       String a = "Hello";
       StringBuffer b = new StringBuffer("Hello");

         System.out.println("Inside A");
         System.out.println("Inside B")

  14. How to use a StringTokenizer?
  15. What are Collections in Java?
  16. What is the difference between a Vector and an ArrayList?
  17. Can you write a program that emulates a Linked List in Java without using the class
  18. What is a thread in Java?
  19. What are the uses of threads?
  20. What is a process in Java?

Java EE Questions:

  1.   Do you know Java EE?
  2.   On a scale of 5, how do you rate yourself in Java EE?
  3.   Do you know EJB?
  4.   What is Life Cycle of a Servlet?
  5.   What are the methods in the Class GenericServlet?
  6.   What is the difference between GenericServlet and HttpServlet?

SQL Questions:

  1. On a scale of 5, how do you rate yourself in SQL?
  2. What is DDL?
    3. What is DML?
    4. What is the difference between DDL and DML?
    5. Assume there is a table by name Employee, that has columns emp_name, emp_id and

         Write a query that prints emp_name of the employee earning the maximum salary.

UNIX Questions:

    1.   On a scale of 5, how do you rate yourself in UNIX?
    2.   Explain the command mv?
    3.   Explain the command cp?
    4.   What is the difference between mv and cp?
    5.   How to use grep command?
    6.   What command do you use to see all the processes that are running in UNIX?
    7.   Do you know shell scripting?

You may want to

    1. where and why do we use the synchronized keyword?
    2. give example of polymorphism with code?
    3. what are the classes and interfaces used in Collection framework, breifly explain them?
    4. what are inner classes and why do we need them?
    5. Do we name the java file using the Outer class’s name?
    6. how to access the inner class?
    7. Why do we need an abstract class from design perspective?
    8. difference between keywords and variables?
    9. what is the deployment process of your application?
    10. explain MVC?
    11. which sre the components in your application that correspond to Model View and Controller
    12. which application server do u use to deploy your app?
    13. what database do u use and how do u connect to the database?
    14. what is JNDI?
    15. what is EJB?
    16. what do u mean by serialization? how do we achieve it in java?

UNIX Questions:
2. mv moves files / folders from one directory to another.
3. cp copies files / folders from one directory to another.
4. After a mv command, the original files / folders are removed from the source location; with cp, the
files / folders are still available
5. grep is used to find strings within files. E.g., grep “a*” somefiles*.txt will find all multiple occurrences
of the letter “a” from all files that start with the name “somefiles” and end with a “txt” extension.
6. ps is the command to view processes. To see all the processes that are running, use ps -a, or ps -e
depending on what flavor of UNIX you#39;re running.

Encapsulation : Using Getter and Setters  Data validation before changing

Instance variable always gets there default value

Instance variable are declared inside the class..but local variables are declared inside the methd.

Local variables must be initialized before they can b used..

13.What is the Collection interface ?
The Collection interface provides support for the implementation of a mathematical bag – an
unordered collection of objects that may contain duplicates.

14.What is the Set interface ?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets
do not allow duplicate elements.

32.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

33.Which is the preferred collection class to use for storing database result sets ?
When retrieving database results, the best collection implementation to use is the LinkedList.
The benefits include:
Retains the original retrieval order
Has quick insertion at the head/tail
Doesn’t have an internal size limitation like a Vector where when the size is exceeded a new
internal structure is created (or you have to find out size beforehand to size properly)
Permits user-controlled synchronization unlike the pre-Collections Vector which is always


ResultSet result = stmt.executeQuery(―…‖);
List list = new LinkedList();
while( {

If there are multiple columns in the result set, you’ll have to combine them into their own data
structure for each row. Arrays work well for that as you know the size, though a custom class
might be best so you can convert the contents to the proper type when extracting from databse,
instead of later.
34.Why doesn’t the Iterator interface extend the Enumeration interface ?
If the Iterator interface extended the Enumeration interface, the Iterator interface would end up
with five methods where two methods just called other methods in the interface. The designers of
the framework wanted to get rid of the cumbersome Enumeration method names so had the
Iterator interface stand on its own with new shorter method names.

35.How do I print a Collection ?
The Collection Framework implementation classes override the toString() method to print out all
the elements of the collection. If you create your own custom implementation, as long as your
class is a subclass of AbstractMap or AbstractCollection you’ll inherit this behavior. (Keep in
mind that AbstractList and AbstractSet subclass AbstractCollection.)

36.How do I synchronize a collection ?
With the Collections Framework, the new implementations are all unsynchronized by default. If
you need synchronized access, you must synchronize things yourself. The Collections class
offers a wrapper method for each of the six core collection interfaces that add synchronization to
an arbitrary collections implementation. To ensure thread-safety, direct access to the original
backing collection must be avoided.
For example, the following will synchronize an arbitrary List and lose the original reference so
you can’t access it directly:

List list = …;
list = Collections.synchronizedList(list);

37.How I do a case-sensitive sort in a language-insensitive manner ?
If you have an array of primitives or an array of equivalent objects that implement the
Comparable interface, all you need to do is call the sort() method of the java.util.Arrays class. If
the class doesn’t implement Comparable, you need to provide your own Comparator
implementation to the sort() method.

38.How do I get the length of an array ?
To avoid getting an ArrayIndexOutOfBoundsException, you can check for the array length from
either the length instance variable or using reflection and calling
java.lang.reflect.Array.getLength(), passing the array as an argument to the method.
int length = args.length;
// or
int length2 = Array.getLength(args);

39.How can I speed up array accesses and turn off array bounds checking ?
You cannot. It is part of the security architecture of the Java runtime to ensure never accessing
invalid memory space.

40.How do I get the list of system properties that tell me things like which version of Java a
user is running and their platform-specific line separator ?
The System.getProperties() method will return the standard property set. However, in untrusted
applets, you can only ask for specific properties, as in System.getProperty(―java.version‖).
41.How do I sort an array ?
The Arrays class in java.util provides a series of sort() methods for sorting arrays. If the array is
an array of primitives or an array of a class that implements Comparable then you can just call
the method directly:


If, however, it is an array of objects that don’t implement the Comparable interface then you
need to provide a custom Comparator to help you sort the elements in the array.

Arrays.sort(theArray, theComparator);

42.How can I implement a List (ordered collection) that keeps an index (i.e. a Map) of its
contents ?
You can’t. Each of the Map and List interfaces define a remove(Object o) method. Each method
returns a different type (Map returns an Object while List returns a boolean). Because the
compiler doesn’t permit overloaded methods that differ by only return type, you cannot create a
class that implements both the List and Map interface.

If you need a Map that maintains insertion order, see the LinkedHashMap added in Java 1.4.

43.Is there a way to create a homogenous collection in Java? How do I make a collection
where all the elements within it are a specific data type ?
You can wait for Generics to be added to Java or…

You’d have to build one yourself. Basically, you’re creating a class that is a Proxy (Gang Of
Four design pattern) around the actual Collection.

This works similarly to the way the (hidden) Synchronized versions in Collections work. They
contain a reference to the original collection object that does the ―real‖ work, but restrict access
to it by synchronizing all the access methods.

What you’d be doing in this case is restricting access by keeping a reference to the Class object
of the class you want to restrict your collection to contain, and throw IllegalArgumentExceptions
whenever there’s an attempt to add an object not of that class.

There’s no way to enforce compile-time type safety in this manner. The API using ―Object‖
references can’t be changed in Collection.

You can also wrap a collection by a Proxy that provides the alternative API that has type-safe
method signatures. This is what’s done by the StringTokenizer API (which implements
Enumeration, and wraps Enumeration with String versions of the same methods).

Otherwise, create your own class with its own signatures, and keep the Collection strictly
private. This is best done if you are designing a class for others to use.
44.How does a Hashtable internally maintain the key-value pairs ?
The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All
entries of the Hashtable are stored in an array of Entry objects with the hash value of the key
serving as the index. If two or more different keys have the same hash value these entries are
stored as a linked list under the same index.

45.How do I look through each element of a HashMap ?
To go through all the elements of a HashMap, or any class that implements the Map interface,
call the entrySet() or keySet() methods than loop through what is returned. The entrySet() returns
a group of Map.Entry elements, whereas the keySet() method just returns a Set of key elements.
If you then want what the key refers to, you’d have to look them up.
Once you have a Set to work with, you would then use an Iterator to go through all its elements.
The following demonstrates:

Map map = some hash map
Set set = map.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {

46.How do I create a read-only collection ?
The Collections class has six methods to help out here:
unmodifiableCollection(Collection c)
unmodifiableList(List list)
unmodifiableMap(Map m)
unmodifiableSet(Set s)
unmodifiableSortedMap(SortedMap m)
unmodifiableSortedSet(SortedSet s)

If you then get an Iterator from one of these unmodifiable collections, when you call remove() it
will throw an UnsupportedOperationException

47.How can I process through the keys of a Hashtable in sorted order ?
In order to get all the keys for a Hashtable, you use the keys() method to get an Enumeration or
the keySet() method to get a Set. If you are using Java 2, and can use the collections framework,
what you should do is get the key set of the Hashtable and create a TreeSet from it. You can then
get an iterator() from the created TreeSet that will have the keys in order. If you can’t use the
collections framework, you’ll have the sort the Enumeration you get back from keys() yourself.

48.Which collections in Java are synchronized and which aren’t ?
The original collection classes in Java are all synchronized: Vector and Hashtable, along with
their subclasses Stack and Properties. Those classes introduced with the Java 2 Collections
Framework are all NOT synchronized by default, the sets, lists, and maps
49.What are the differences between ArrayList and LinkedList ?
An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the
number of elements in the collection increases, the internal array grows to fit them. If there are
lots of growth periods, performance degrades as the old array needs to be copied into the new
array. However, random access is very quick as it uses an array index to access.
With a LinkedList, the List implementation is backed by a doubly linked list data structure,
allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the
access must start at an end to get to the specific position.

Which you use really depends on the type of operations you need to support.

50.How do I read input from a stream “one word at a time” ?               What you need to do is
use the java.util.StringTokenizer or to parse your input into words. Each
has a default set of delimiters like white space that can be changed. The following demonstrates
the using of StringTokenizer to count words in a file.

import java.util.*;

public class Test {
static final Integer ONE = new Integer(1);

public static void main (String args[])
throws IOException {

Map map = new TreeMap();
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
processLine(line, map);
static void processLine(String line, Map map) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
addWord(map, st.nextToken());
static void addWord(Map map, String word) {
Object obj = map.get(word);
if (obj == null) {
map.put(word, ONE);
} else {
int i = ((Integer)obj).intValue() + 1;
map.put(word, new Integer(i));
static void printMap(Map map) {
Set set = map.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry);
System.out.println(entry.getKey() +
―: ‖ + entry.getValue());

51.Do the keys() and elements() methods of a Hashtable enumerate things in the same
order ?
There is no requirement that the elements are returned in the same order, only that all of them are
returned in the Enumeration. Your best bet for getting the element for a key is to loop through
the keys() returned and fetch the element for each. Or, if you can use a HashMap instead of a
Hashtable, work with the Map.Entry that is returned by the keySet(). This includes both the key
and value together, not requiring a separate lookup.

52.How do I treat an object I get out of a Vector (collection) as the type I put into it ?
When you get an object out of a Vector (or any collection), the object is returned as being of type
Object. You need to cast it back into the object type you put into the data structure if you need to
call or treat the object as the original type.
For instance, if you add an array to a vector:

String args[] = {―1″, ―2″, ―3″};
Vector v = new Vector();

Then, when you get the object out of the vector, you need to cast it back to the original type:
String args2[] = (String[])v.firstElement();

53.What is the difference between a singly linked list and doubley linked list ?
A singly linked list is one that has only a pointer/reference to the next element in the list. A
doubley linked list has both a previous and next pointer/reference.

54.What is meant by natural ordering of objects in the context of the collections framework
Java documentation refers to the natural ordering of objects when describing various algorithms
and data structures in the collections framework. Object ordering is obviously needed by the
sorting algorithms. It is also needed by the specifications of the interfaces such as SortedSet,
SortedMap, etc., and the data structures used for container classes such as TreeSet, TreeMap, etc.
Unless instructed otherwise via a Comparator object supplied as an argument to the constructor,
the default behavior of a class such as TreeSet is to store its objects in an ascending natural
The objects of a class exhibit natural ordering if the class has implemented the
java.lang.Comparable interface. Such a class must provide an implementation for the compareTo
method — referred to as the class’s natural comparison method — that can then be used by the
algorithms and the data structures for comparing data objects. The compareTo method must
return a negative integer, a zero, or a positive integer if the object on which it is invoked is less
than, equal to, or greater than the argument object.

It is strongly recommended that a class’s natural ordering as dictated by the implementation of
the compareTo method be consistent with equals. This consistency is achieved if and only if
e1.compareTo( (Object) e2 ) == 0 has the same boolean value as e1.equals( (Object) e2 ) for
every pair of objects e1 and e2 of the class. Lack of this consistency could elicit strange behavior
from the data structures that need to compare objects.

Many of the system supplied classes possess natural ordering. These include String, Integer,
Float, Double, Date, File and many others. For the String class, the natural order is
lexicographic; it is chronological for the Date class; lexicographic on the pathname for the File
class, etc.

55.What is a fail-fast iterator ?
An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of
the following two conditions:
In multithreaded processing: if one thread is trying to modify a Collection while another thread is
iterating over it.

In single-threaded or in multithreaded processing: if after the creation of the Iterator, the
container is modified at any time by any method other than the Iterator’s own remove or add
Note in particular what is implied by the second condition: After we create a container’s iterator,
during a loop that iterates over the container we must only use the remove (and when applicable
add) methods defined for the iterator and that we must NOT use the same methods defined for
the container itself. To illustrate this point, suppose we declare and initialize a List in the
following manner
List list = new ArrayList();

Let’s say we wish to iterate over this list. We’d need to declare a ListIterator as follows:
ListIterator iter = list.listIterator();

Having created this iterator, we could now set up a loop like:
String str =;
// do something with str

Because iter is fail-fast, we are not allowed to invoke List’s add or remove methods inside the
loop. Inside the loop, we are only allowed to use ListIterator’s add and remove methods. This
makes sense because it is the Iterator object that knows where it is in a List as the List is being
scanned. The List object itself would have no idea of that.
The Iterators supported by all the work-horse container classes, such as ArrayList, LinkedList,
TreeSet, and HashSet, are fail-fast. The Iterator type retrofitted to the older container class
Vector is also fail-fast. For associative containers, such as HashMap and the older HashTable,
the Iterator type for the Collections corresponding to either the keys or the values or the <key,
value> pairs are fail-fast with respect to the container itself. That means that even if you are
iterating over, say, just the keys of the container, any illegal concurrent modifications to the
underlying container would be detected.

One final note regarding iterators versus enumerations: It is also possible to use an Enumeration
object returned by the elements() method for iterating over the older container types such as
Vector. However, Enumerations do not provide a fail-fast method. On the other hand, the more
modern Iterator returned by a Vector’s iterator() and listIterator() methods are fail-fast. Hence,
iterators are recommended over enumerations for iterating over the elements of the older
container types.

56.How do you sort the elements of a vector ?
Since the Vector class implements the List interface, you can call the Collections.sort() method
to sort the elements in place. You can also manually insert elements into a Vector to keep the
vector sorted. Of course, if keeping sorted access is such a big deal, you should consider using a
different, more appropriate data structure like a TreeSet.
For 1.1 Java users, you’ll need to sort the elements yourself. There is no built-in support for this.
A better option might be to sort the elements as you insert each element.

57.What is a WeakHashMap? What is its use and when should you use it ?
A WeakHashMap is a special Map implementation where the keys of the map are stored in a
java.lang.ref.WeakReference. By storing the keys in a weak reference, key-value pairs can
dynamically be dropped from the map when the only reference to the key is from the weak
reference. This makes the WeakHashMap an excellent implementation for a weakly referenced
list, where entries that aren’t used elsewhere may be dropped with no side effects. Also, just
because a key may be dropped, doesn’t mean it will immediately be dropped. If the system has
sufficient resources, the weak key reference that isn’t externally referenced could stay around for
a long time.

58.What is the function of a load factor in a Hashtable ?
The load factor determines how full a hashtable may get before it expands its capacity. I think
that the comments on the Hashtable API docs explain it very well:
The load factor is a measure of how full the hash table is allowed to get before its capacity is
automatically increased. When the number of entries in the hashtable exceeds the product of the
load factor and the current capacity, the capacity is increased by calling the rehash method.
Generally, the default load factor (.75) offers a good tradeoff between time and space costs.
Higher values decrease the space overhead but increase the time cost to look up an entry (which
is reflected in most Hashtable operations, including get and put).

59. How do you control growth of vectors when their internal arrays are full ?
The vector constructor can include either an initial capacity or a capacity and growth increment.
When not specified, the initial size of the vector is 10 and growth will double when necessary.
Otherwise, initialize size and growth will grow when needed as specified by the arguments to the
If the argument to the constructor is a collection, the initial size of the internal structure is 10%
larger than the collection. Since there is no second argument to control growth, the capacity will
double when necessary.

60.How to sort the messages in JavaMail ?
Within the JavaMail classes there is no support for this. However, once you get the array of
messages back from a folder, you can call the Arrays.sort() method in the collections framework
to sort the messges. Since MimeMessage doesn’t implement Comparable, you’ll need to provide
your own Comparator specifying how you want the messages to be sorted.

61.When did Strings start caching their hash codes ?
Starting with the 1.3 release of Java, the java.lang.String class will only calculate the hashcode
once, when its first needed. Future calls to hashCode() will return the previously calculated

62.How can you retrieve the Hashtable’s load factor ?
There is no public interface to access the load factor setting.
Some choices you can do to expose this value…

Subclass Hashtable and add a read-only accessor method
Use reflection to access the private field (only possible in trusted environment)
Serialize the Hashtable and get the value from the stream (when reading back the stream, you’ll
have to figure out where the appropriate field is)

63.Why can’t I add a collection to itself ?
This will cause a stack overflow exception to be generated on calls to methods like toString() and
hashCode(), which recursively call the method on the elements of the collection.

The life cycle of a servlet can be categorized into four parts:

   1. Loading and Inatantiation: The servlet container loads the servlet during startup or
      when the first request is made. The loading of the servlet depends on the attribute <load-
      on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then
      the servlet is load with loading of the container otherwise it load when the first request
      comes for service. After loading of the servlet, the container creates the instances of the
   2. Initialization: After creating the instances, the servlet container calls the init() method
      and passes the servlet initialization parameters to the init() method. The init() must be
      called by the servlet container before the servlet can service any request. The
      initialization parameters persist untill the servlet is destroyed. The init() method is called
      only once throughout the life cycle of the servlet.

      The servlet will be available for service if it is loaded successfully otherwise the servlet
      container unloads the servlet.
   3. Servicing the Request: After successfully completing the initialization process, the
      servlet will be available for service. Servlet creates seperate threads for each request. The
      sevlet container calls the service() method for servicing any request. The service()
      method determines the kind of request and calls the appropriate method (doGet() or
      doPost()) for handling the request and sends response to the client using the methods of
      the response object.
   4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the
      servlet container calls the destroy() method . Like the init() method this method is also
      called only once throughout the life cycle of the servlet. Calling the destroy() method
      indicates to the servlet container not to sent the any request for service and the
      servlet releases all the resources associated with it. Java Virtual Machine claims for the
      memory associated with the resources for garbage collection.

           Life Cycle of a Servle

Reflection is a powerful approach to analyze the class at runtime. If new classes are added into
your application dynamically then Reflection is used to get the structure of the class.

Reflection uses special kind of java class: Class. The object of the Class type can hold all the
information of the class and have getter methods to extract this information.
What is the difference between Resultset and Rowset. Answer

A RowSet object contains a set of rows from a result set or
some other source of tabular data, like a file or

A ResultSet object represents the output table of data
resulted from a SELECT query statement.The data in a
ResultSet object is organized in rows and columns