Thursday, July 21, 2011

JSP Implicit Objects

Implicit objects in jsp are the objects that are created by the container automatically and the container makes them available to the developers, the developer do not need to create them explicitly. Since these objects are created automatically by the container and are accessed using standard variables; hence, they are called implicit objects. The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration. Implicit objects are used for different purposes. Our own methods (user defined methods) can't access them as they are local to the service method and are created at the conversion time of a jsp into a servlet. But we can pass them to our own method if we wish to use them locally in those functions.There are nine implicit objects. Here is the list of all the implicit objects:

Object==> Class
application==> javax.servlet.ServletContext
config==>javax.servlet.ServletConfig
exception==>java.lang.Throwable
out==>javax.servlet.jsp.JspWriter
page==>java.lang.Object
PageContext==>javax.servlet.jsp.PageContext
request==>javax.servlet.ServletRequest
response==>javax.servlet.ServletResponse
session==>javax.servlet.http.HttpSession

Application: These objects has an application scope. These objects are available at the widest context level, that allows to share the same information between the JSP page's servlet and any Web components with in the same application.

Config: These object has a page scope and is an instance of javax.servlet.ServletConfig class. Config object allows to pass the initialization data to a JSP page's servlet. Parameters of this objects can be set in the deployment descriptor (web.xml) inside the element . The method getInitParameter() is used to access the initialization parameters.

Exception: This object has a page scope and is an instance of java.lang.Throwable class. This object allows the exception data to be accessed only by designated JSP "error pages."

Out: This object allows us to access the servlet's output stream and has a page scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the output stream that enable access to the servlet's output stream.

Page: This object has a page scope and is an instance of the JSP page's servlet class that processes the current request. Page object represents the current page that is used to call the methods defined by the translated servlet class. First type cast the servlet before accessing any method of the servlet through the page.

Pagecontext: PageContext has a page scope. Pagecontext is the context for the JSP page itself that provides a single API to manage the various scoped attributes. This API is extensively used if we are implementing JSP custom tag handlers. PageContext also provides access to several page attributes like including some static or dynamic resource.

Request: Request object has a request scope that is used to access the HTTP request data, and also provides a context to associate the request-specific data. Request object implements javax.servlet.ServletRequest interface. It uses the getParameter() method to access the request parameter. The container passes this object to the _jspService() method.

Response: This object has a page scope that allows direct access to the HTTPServletResponse class object. Response object is an instance of the classes that implements the javax.servlet.ServletResponse class. Container generates to this object and passes to the _jspService() method as a parameter.

Session: Session object has a session scope that is an instance of javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to manage the state contexts. This object persist information across multiple user connection.

Friday, July 15, 2011

Overloading and Overriding

Overloading
If two (or more) methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but different signatures, then the method name is said to be overloaded. The signature of a method consists of the name of the method and the number and types of formal parameters in particular order. A class must not declare two methods with the same signature, or a compile-time error occurs. Only the method name is reused in overloading, so method overloading is actually method name overloading. Overloaded methods may have arguments with different types and order of the arguments may be different. Overloaded methods are not required to have the same return type or the list of thrown exceptions. Overloading is particularly used while implementing several methods that implement similar behavior but for different data types. Overloaded methods are independent methods of a class and can call each other just like any other method.

Constructor Overloading
Constructors can also be overloaded in similar fashion, as they are also methods.
Java has some classes with overloaded constructors. For example, wrapper class for int has two overloaded constructors. One constructor takes int as argument and another takes string argument.o Integer aNumber = new Integer(2);o Integer anotherNumber = new Integer("2005");
One constructor can call another overloaded constructor of the same class by using this keyword. One constructor can call constructor of its super class by using the super keyword.
Overriding.When a class defines a method with same method name, argument types, argument order and return type as a method in its super class, its called method overriding.
The method in the super class is said to be overridden by the method in the subclass.
Overriding method actually replaces the behavior in super class for a subclass.
Rules for overriding .Methods overriding cannot be declared more private than the super class method. Any exceptions declared in overriding method must be of the same type as those thrown by the super class, or a subclass of that type. Methods declared as final cannot be overridden. An overriding method can be declared as final as the keyword final only suggests that this method cannot be further overridden. Methods declared as private cannot be overridden as they are not visible outside the class. Overriding method can call the overridden method (just like any other method) in its super class with keyword super.The call super.method() will invoke the method of immediate super class. Though keyword super is used to refer super class, method call super.super.method() is invalid.


Overloading methods.
Overloaded methods supplement each other. Overloading methods may have different argument lists of different types. The return type may be different for overloaded methods
Since overloading methods are essentially different methods, there is no restriction on exceptions they can throw. An overriding method replaces the method it overrides. An overriding method must have argument lists of identical type and order. The return type must be same as that of overridden method. The overriding method must not throw checked exceptions which cannot be thrown by the original method. 'Is a', 'has a' relationshipThe Generalization (Inheritance) and 'is-a' relationshipGeneralization is the result of abstracting the common attributes and behavior from a group of closely related classes and moving them into a common super class. Specialization is the inverse of generalization.A common test for generalization is the IS-A test. Generalization may also look for following phrases in problem definition to identify the inheritance. "is a" "is a type of" "is a kind of" For example, if part of problem definition says 'Dog IS AN animal', implementation will more likely have Animal class and Dog class will be the subclass of the Animal class.The Composition and 'has-a' relationship Composition is the relationship between a class and its constituent parts. Composition passes the “HAS-A” test.Example: An Automobile 'has-a' Engine. Composition also passes the 'life and death' test. The parts have the same life as the whole. Example: A Polygon has points, and the points live and die with the Polygon object. Variables are shadowed and methods are overridden.When a class member variable is accessed through an object reference, the variable to be selected depends on the declared class of the object reference variable.However, when a method is called on through an object reference, the actual method invoked depends on the type of an object reference.
example A subclass can have a variable with the same name as a variable in the parent class. This is called as shadowing the parent class variable. It is not overriding of variable. Late BindingIn any method call, actual method to invoke is determined by the 'Class' (or type) of an object on which the method is called and not on the type of variable holding the object reference. In addition, this is decided at runtime.

Thursday, July 14, 2011

Collection

Q: What is the Collections API?
A: The Collections API is a set of classes and interfaces that support operations on collections of objects.

Q: What is the List interface?
A: The List interface provides support for ordered collections of objects.

Q: What is the Vector class?
A: The Vector class provides the capability to implement a growable array of objects.

Q: What is an Iterator interface?
A: The Iterator interface is used to step through the elements of a Collection .

Q: Which java.util classes and interfaces support event handling?
A: The EventObject class and the EventListener interface support event processing.

Q: What is the GregorianCalendar class?
A: The GregorianCalendar provides support for traditional Western calendars

Q: What is the Locale class?
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region .

Q: What is the SimpleTimeZone class?
A: The SimpleTimeZone class provides support for a Gregorian calendar .

Q: What is the Map interface?
A: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

Q: What is the highest-level event class of the event-delegation model?
A: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

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

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


Q: What is the typical use of Hashtable?
A: Whenever a program wants to store a key value pair, one can use Hashtable.

Q: I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?
A: The existing object will be overwritten and thus it will be lost.

Q: What is the difference between the size and capacity of a Vector?
A: The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.

Q: Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

Q: Can a ArrayList contain heterogenous objects?
A: Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.

Q: What is an enumeration?
A: An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

Q: Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList?
A: The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.

Q: Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

Q:What is HashMap and Map?
A:Map is Interface and Hashmap is class that implements this interface.

Q:What is the significance of ListIterator? Or What is the difference b/w Iterator and ListIterator?
A:Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements

Q:Difference between HashMap and HashTable? Can we make hashmap synchronized?
A:1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.


Note on Some Important Terms

1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);

Q:What is the difference between set and list?
A: Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.

Q:Difference between Vector and ArrayList? What is the Vector class?
Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.

Q:What is an Iterator interface? Is Iterator a Class or Interface? What is its use?
The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.

Q:What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

Q:What is the List interface?
The List interface provides support for ordered collections of objects.

Q:How can we access elements of a collection?
We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.

Q: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.

Q:What’s the difference between a queue and a stack?
Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-out (FIFO) rule.

Q:What is the Map interface?
The Map interface is used associate keys with values.

Q:What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.

Q:Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
a. Vector
b. ArrayList
c. LinkedList
d. None of the above
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

Q:How can we use hashset in collection interface?
This class implements the set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the Null element.
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.

Q:What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?
Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.
ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements, including null. It is not thread -safe.
Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.
Collections: It implements Polymorphic algorithms which operate on collections.
Collection: It is the root interface in the collection hierarchy.

Q:What is difference between array & arraylist?
An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.
Array: can store primitive ArrayList: Stores object only
Array: fix size ArrayList: resizable
Array: can have multi dimensional
Array: lang ArrayList: Collection framework

Q:Can you limit the initial capacity of vector in java?
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity public vector(int initialcapacity)

What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().

Q:What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.
So Enumeration is used when ever we want to make Collection objects as Read-only.


Q: What is difference between ArrayList and vector?
Ans: ) 1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Q: How can Arraylist be synchronized without using Vector?
Ans) Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)

Q: If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
Ans) 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
2) Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.

Q:What is difference between HashMap and HashTable?
Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Fail-safe - “if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.

Q: What are the classes implementing List interface?
Ans) There are three classes that implement List interface:
1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.

Q: Which all classes implement Set interface?
Ans) A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

Q: What is difference between List and a Set?
Ans) 1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)

Q: What is difference between Arrays and ArrayList ?
Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :
1. int [] intArray= new int[6];
2. intArray[7] // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
2. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
3. ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1]; // 3 dimensional array
4. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.

Q: When to use ArrayList or LinkedList ?
Ans) Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.

Q: Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?
Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.

Q: Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.
Ans) For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

Q: Which design pattern Iterator follows?
Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.
Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.

Q: Is it better to have a HashMap with large number of records or n number of small hashMaps?
Ans) It depends on the different scenario one is working on:
1) If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.
2) If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.

Q: Why is it preferred to declare: List list = new ArrayList(); instead of ArrayList = new ArrayList();
Ans) It is preferred because:
1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
2. The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible

Q: What is difference between iterator access and index access?
Ans) Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the 'n' location and get the element. It doesnot traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.

Q: How to sort list in reverse order?
Ans) To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
List list = new ArrayList();
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)

Q: Can a null element added to a Treeset or HashSet?
Ans) A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.

Q: How to sort list of strings - case insensitive?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Q: How to make a List (ArrayList,Vector,LinkedList) read only?
Ans) A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

Q: What is ConcurrentHashMap?
Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

Q: Which is faster to iterate LinkedHashSet or LinkedList?
Ans) LinkedList.

Q: Which data structure HashSet implements
Ans) HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.

Q: Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap, concurrentHashmap
Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.

Q: What is identityHashMap?
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

Q: What is WeakHashMap?
Ans) A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.

Class Loader

Class loaders offer a very powerful mechanism by which classes can be loaded at runtime. Its power lies in its extensibility, i.e. custom classes needed for the application can be loaded in addition to the basic classes loaded by bootstrap loader. But with such powerful tool comes some security problems as well. Its important for application developers to understand the functioning of classloaders to make their application efficient and and it will also make debugging easy.


One of the main features of java is "Write Once and Run Anywhere". The
Java Virtual Machine (JVM) is responsible for loading and executing the code. For this purpose, it uses the java class loader. The java class loaders are responsible for loading appropriate classes in the JVM at the runtime. In a JVM, each and every class is loaded by some instance of a java.lang.ClassLoader. The main feature of the classloader is that JVM. doesn’t need to have any knowledge about the classes that will be loaded at runtime. ClassLoaders support features like hot deployment and run time platform e extensibility. The next section explains how a class loader works.

Class Loader Functioning:
A class file is the smallest unit that gets loaded by the class loader. It contains binary representation of a java class and contains bytecodes and links to other class files that will be used. Class loader reads this bytecode and creates the instance of java.lang.Class. When the JVM starts, initially only the class file is loaded and other classes are loaded as and when required by the JVM. In this process, JVM is initially unaware of what classes will be loaded later on. Lazy loading plays a key role in providing dynamic extensibility to the Java platform.
In lazy loading, dependents are only loaded as they are specifically
requested.

Different class loaders are responsible for loading different classes from different repositories.

First the " bootstrap class " loader loads the key classes
Next comes the " java extension class "loader. It loads the libraries, which are not part of the core java run time. The ExtClassLoader is responsible for loading all .jar files kept in the java.ext.dirs path. Finally, developer ,can add his own custom classes needed by the application .


The process of loading of a class by a class loader is not standalone process. Its a 3-step process.
Loading
Linking
Initialization

Loading is the process of locating the binary representation of a type and bringing it into the JVM. Linking is the process of taking the type and incorporating it into the runtime state of the JVM so that it can be executed. Initialization is the process of executing the initializers of a type (static initializers for classes; static field initializers for classes and interfaces). Once a class becomes unreachable it is available for garbage collection.

The next section deals with how the requested class is searched and loaded by a class loader

How Class Loader Works:
When a client requests to load a particular class, a check is performed by the class loader to see whether the requested class is already loaded. If the class is already loaded then loaded class is returned and the request ceases. However if the class is not loaded, then the request is sent to the parent class loader to search for the requested class. This request for search can go up to the level of bootstrap loader (highest in the hierarchy). If the parent is successful in finding the class then that class is returned and the request ceases, but if that does not work out, then the current class loader has to find the requested class.

Each class loader has a specific location for searching the class. e.g bootstrap loader searches for folders, zips and jars. The methods that are invoked to search for and load the requested class are
protected Class findClass (String className) throws ClassNotFoundException
public class loadClass (String className) throws ClassNotFoundException.

Java Classloader :
The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine.[1] Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems because of class loaders. Delegation is an important concept to understand when learning about class loaders. A software library is a collection of related object code. In the Java language, libraries are typically packaged in Jar files. Libraries can contain objects of different types. The most important type of object contained in a Jar file is a Java class. A class can be thought of as a named unit of code. The class loader is responsible for locating libraries, reading their contents, and loading the classes contained within the libraries. This loading is typically done "on demand", in that it does not occur until the class is actually used by the program. A class with a given name can only be loaded once by a given classloader. Class loading process Each Java class must be loaded by a class loader.[2] Furthermore, Java programs may make use of external libraries (that is, libraries written and provided by someone other than the author of the program) or they may be composed, at least in part, of a number of libraries.

When the JVM is started, three class loaders are used
1. Bootstrap class loader
2. Extensions class loader
3. System class loader

The bootstrap class loader loads the core Java libraries[5] (/lib directory). This class loader, which is part of the core JVM, is written in native code.The extensions class loader loads the code in the extensions directories (/lib/ext or any other directory specified by the java.ext.dirs system property). It is implemented by the sun.misc.Launcher$ExtClassLoader class.
The system class loader loads code found on java.class.path, which maps to the system CLASSPATH variable. This is implemented by the sun.misc.Launcher$AppClassLoader class.

Exception Handling

Q1) What is an Exception?
Ans) The exception is said to be thrown whenever an exceptional event occurs in java which signals that something is not correct with the code written and may give unexpected result. An exceptional event is a occurrence of condition which alters the normal program flow. Exceptional handler is the code that does something about the exception.

Q2) Exceptions are defined in which java package?
Ans)All the exceptions are subclasses of java.lang.Exception

Q3) How are the exceptions handled in java?
Ans)When an exception occurs the execution of the program is transferred to an appropriate exception handler.The try-catch-finally block is used to handle the exception. The code in which the exception may occur is enclosed in a try block, also called as a guarded region. The catch clause matches a specific exception to a block of code which handles that exception. And the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block

Q4) Explain the exception hierarchy in java.
Ans) The hierarchy is as follows:
Throwable is a parent class off all Exception classes. They are two types of Exceptions: Checked exceptions and UncheckedExceptions. Both type of exceptions extends Exception class.

Q5) What is Runtime Exception or unchecked exception?
Ans) Runtime exceptions represent problems that are the result of a programming problem. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. Runtime exceptions need not be explicitly caught in try catch block as it can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can). The solution to rectify is to correct the programming logic where the exception has occurred or provide a check.

Q6) What is checked exception?
Ans) Checked exception are the exceptions which forces the programmer to catch them explicitly in try-catch block. It is a subClass of Exception. Example: IOException.

Q7) What is difference between Error and Exception?
Ans) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

Q8) What is difference between ClassNotFoundException and NoClassDefFoundError?
Ans) A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. Consider if NoClassDefFoundError occurs which is something like java.lang.NoClassDefFoundError
src/com/TestClass does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.

Q9) What is throw keyword?
Ans) Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}

public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException("Throwing exception using throw keyword");
}
}

Q10) What is use of throws keyword?
Ans) If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the throws clause at the function declaration.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}

public void child throws MyCustomException{
//put some logic so that the exception occurs.
}

Q11) What are the possible combination to write try, catch finally block?
Ans) 1) try{
//lines of code that may throw an exception
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}finally{
//the clean code which is executed always no matter the exception occurs or not.
}
2 try{
}finally{}
3 try{
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}
The catch blocks must always follow the try block. If there are more than one catch blocks they all must follow each other without any block in between. The finally block must follow the catch block if one is present or if the catch block is absent the finally block must follow the try block.

Q12) How to create custom Exception?
Ans) To create you own exception extend the Exception class or any of its subclasses.
1 class New1Exception extends Exception { } // this will create Checked Exception
2 class NewException extends IOExcpetion { } // this will create Checked exception
3 class NewException extends NullPonterExcpetion { } // this will create UnChecked exception

Q13) When to make a custom checked Exception or custom unchecked Exception?
Ans) If an application can reasonably be expected to recover from an exception, make it a checked exception. If an application cannot do anything to recover from the exception, make it an unchecked exception.

Q14)What is StackOverflowError?
Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM.
e.g. void swap(){ swap(); }

Q15) Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope?
Ans) Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.

Q16) Once the control switches to the catch block does it return back to the try block to execute the balance code?
Ans) No. Once the control jumps to the catch block it never returns to the try block but it goes to finally block(if present).

Q17) Where is the clean up code like release of resources is put in try-catch-finally block and why?
Ans) The code is put in a finally block because irrespective of try or catch block execution the control will flow to finally block. Typically finally block contains release of connections, closing of result set etc.

Q18) Is it valid to have a try block without catch or finally?
Ans) NO. This will result in a compilation error. The try block must be followed by a catch or a finally block. It is legal to omit the either catch or the finally block but not both.
e.g. The following code is illegal.
try{
int i =0;
}
int a = 2;
System.out.println(“a = “+a);
Q19) Is it valid to place some code in between try the catch/finally block that follows it?
Ans) No. There should not be any line of code present between the try and the catch/finally block. e.g. The following code is wrong.
try{}
String str = “ABC”;
System.out.println(“str = “+str);
catch(Exception e){}
Q20) What happens if the exception is never caught and throws down the method stack?
Ans) If the exception is not caught by any of the method in the method’s stack till you get to the main() method, the main method throws that exception and the JVM halts its execution.
Q21) How do you get the descriptive information about the Exception occurred during the program execution?
Ans) All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred. It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top.
Q22) Can you catch more than one exceptions in a single catch block?
Ans)Yes. If the exception class specified in the catch clause has subclasses, any exception object that is a subclass of the specified Exception class will be caught by that single catch block.
Eg try { // Some code here that can throw an IOException }
catch (IOException e) { e.printStackTrace(); }
The catch block above will catch IOException and all its subclasses e.g. FileNotFoundException etc.
Q23)Why is not considered as a good practice to write a single catchall handler to catch all the exceptions?
Ans) You can write a single catch block to handle all the exceptions thrown during the program execution as follows : try {
// code that can throw exception of any possible type
}catch (Exception e) {
e.printStackTrace();
}
If you use the Superclass Exception in the catch block then you will not get the valuable information about each of the exception thrown during the execution, though you can find out the class of the exception occurred. Also it will reduce the readability of the code as the programmer will not understand what is the exact reason for putting the try-catch block.
Q24) What is exception matching?
Ans) Exception matching is the process by which the the jvm finds out the matching catch block for the exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at the available catch clauses in the top down manner. If it doesn't find one, it will search for a handler for a supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then the exception is propagated down the call stack. This process is called exception matching.
Q25) What happens if the handlers for the most specific exceptions is placed above the more general exceptions handler?
Ans) Compilation fails. The catch block for handling the most specific exceptions must always be placed above the catch block written to handle the more general exceptions.
e.g. The code below will not compile.
1 try {
// code that can throw IOException or its subtypes
} catch (IOException e) {
// handles IOExceptions and its subtypes
} catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
The code below will compile successfully :-
try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only
}
Q26) Does the order of the catch blocks matter if the Exceptions caught by them are not subtype or supertype of each other?
Ans) No. If the exceptions are siblings in the Exception class’s hierarchy i.e. If one Exception class is not a subtype or supertype of the other, then the order in which their handlers(catch clauses) are placed does not matter.
Q27) What happens if a method does not throw an checked Exception directly but calls a method that does? What does 'Ducking' the exception mean?
Ans) If a method does not throw an checked Exception directly but calls a method that throws an exception then the calling method must handle the throw exception or declare the exception in its throws clause. If the calling method does not handle and declares the exception, the exceptions is passed to the next method in the method stack. This is called as ducking the exception down the method stack.
e.g. The code below will not compile as the getCar() method has not declared the CarNotFoundException which is thrown by the getColor () method.
void getCar() { getColor(); }
void getColor () { throw new CarNotFoundException(); }
Fix for the above code is
void getCar() throws CarNotFoundException {
getColor();
}
void getColor () { throw new CarNotFoundException(); }
Q28) Is an empty catch block legal?
Ans) Yes you can leave the catch block without writing any actual code to handle the exception caught.
e.g. The code below is legal but not appropriate, as in this case you will nt get any information about the exception thrown.
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
//no code to handle the FileNotFound exception
}
Q29)Can a catch block throw the exception caught by itself?
Ans) Yes. This is called rethrowing of the exception by catch block.
e.g. the catch block below catches the FileNotFound exception and rethrows it again.
void checkEx() throws FileNotFoundException {
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
throw FileNotFound();
}
}
"throws clause" is the way to specify exceptions which means to notify the calling method that the callee might throw some type of exceptions somewhere.

"throw clause" is to define which part of the code is actually throwing exceptions.
The throws clause is part of a method declaration. It tells callers of that method what exceptions that method could throws.

A throw statement actually throws the exception.
void foo() throws BarException { // throws clause says this method [i]might[/i] throw BarException
do some stuff
if (some bar-like condition is met) {
throw new BarException("Oh No! It's Bar!"); // throw statement actually throws the exception
}

we only get here if we didn't throw the exception so we go on executing this method
}