Wednesday, 3 July 2013

Collections

Q1. Tell us the collections hierarchy.
Ans.
 

Q2. Talk about collections and Collections in Java.
Ans. collection(s) is a group of various Container classes in Java.

Collections is a class which consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.

The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null.

The "destructive" algorithms contained in this class, that is, the algorithms that modify the collection on which they operate, are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitive(s), such as the set method. These algorithms may, but are not required to, throw this exception if an invocation would have no effect on the collection. For example, invoking the sort method on an unmodifiable list which is already sorted may or may not throw UnsupportedOperationException.

This class is a member of the Java Collections Framework.

Q3. Talk about Collections.sort() method.
Ans.sort(List<T> list): Sorts the specified list into ascending order, according to the natural ordering of its elements.
sort(List<T> list, Comparator<? super T> c): Sorts the specified list according to the order induced by the specified comparator.

Q4. What are the differences between Comparator and Comparable?
Ans.Comparable: Comparing itself with another object i.e comparing own instances. This contains compareTo(Object o) method. 

Comparator: Comparing two different objects. The class is not comparing its instances, but some other class’s instances. This contains compare(Object o1, Object o2) method.

You might want to create a Comparator object for the following.
  • Multiple comparisons: To provide several different ways to sort something.            Ex: You might want to sort a Person class by name, ID, age, height etc. You would define a Comparator for each of these to pass to the sort() method.
  • System class: To provide comparison methods for classes that you have no control over. Ex: You could define a Comparator for Strings that compared them by length.
  • Strategy pattern: To implement a Strategy pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.
If your class objects have one natural sorting order, you may not need this.

Q5. Difference between instance and static addAll method of Collection.
Ans.
Instance method can take only one argument of another Collection object.
i.e c.addAll(c2) // where c and c2 are collection objects

Static method can accept variable argument list.
i.e Collections.addAll(c, c2, 1, 2, 3, 4)
c is the collection object to which elements are added
c2 is the collection object of which elements are added

We add other elements also to c, alongwith c2.

Q6. What happens if we don't specify a object type (in angled brackets) while initializing a array list.
ex: saying new ArrayList() instead of ArrayList<Integer>()
Ans. If I don't specify the object type, it automatically inherits from type Object. In short, program compiles and run properly though.

Q7. How can one prove that the array is not null but empty?
Ans. You can do it by printing array.length - it will print 0. That means it is empty. But if it would have been null, then it would have thrown a NullPointerException.

Q8. What is the difference between Array List and Array.
Ans
1. Array is a primitive data structure, which stores the values in indexed format.  ArrayList is a more like a vector (re-sizeable array). It is a collection and stores any value as an object. If you know the size, then use array, if not try array list. When you have a fixed array, there is no difference in use. 

2. There are several differences, but the biggest, is that an arraylist grows as you add items to it and does not have to be redimmed to allow additional elements. Arrays cannot be changed in size at runtime (except using 'ReDim' which will create a new array, copy the old array in the new array and destroy the old array).

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

It's said that (not sure if it's true), a Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

3. Arraylists are sortable, searchable, etc – they are far superior to arrays.

Q9. What are the limitations of Arrays.asList?

Ans. A limitation of Arrays.asList( ) is that it takes a best guess about the resulting type of the List, and doesn’t pay attention to what you’re assigning it to. Sometimes this can cause a problem:
// holding   AsListInference.java
// Arrays.asList() makes its best guess about type.
import java.util.*;
class Snow {}
class Powder extends Snow {}
class Light extends Powder {}
class Heavy extends Powder {}
class Crusty extends Snow {}
class Slush extends Snow {}
public class AsListInference {
public static void main(String[] args) {
List<Snow> snow1 = Arrays.asList(
new Crusty(), new Slush(), new Powder());
// Won’t compile:
// List<Snow> snow2 = Arrays.asList(
// new Light(), new Heavy());
// Compiler says:
// found : java.util.List<Powder>
// required: java.util.List<Snow>
// Collections.addAll() doesn’t get confused:
List<Snow> snow3 = new ArrayList<Snow>();
Collections.addAll(snow3, new Light(), new Heavy());

Q10. Define collections toArray() method.
Ans. You can convert any Collection to an array using toArray(). This is an overloaded method; the no-argument version returns an array of Object, but if you pass an array of the target type to the overloaded version, it will produce an array of the type specified (assuming it passes type checking). If the argument array is too small to hold all the objects in the List (as is the case here), to Array() will create a new array of the appropriate size.

Q11. What is sorting technique used by Arrays.sort().
Ans. In Java, the Arrays.sort() methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency switch to insertion sort when fewer than seven array elements are being sorted.

The algorithm at present is a mergesort with an insertion sort once you get down to a certain size of sublists (N.B. this algorithm is very probably going to change in Java 7).


Java's sorting algorithm
The sorting algorithm used is a version of mergesort1. Mergesort is based on a "divide and conquer" strategy: we recursively divide the list into two halves and sort each half, then merge the two sorted halves back together. As we break the data down into smaller and smaller parts, we eventually reach a critical size where it's not worth dividing any more, and we sort in situ. Java uses an insertion sort for these 'atomic' sorts. Together, this gives Java's sort routine the following characteristics:
● stable: i.e. if two elements are equal, their order won't be swapped after sorting.
● Because of the requirement to merge lists together into a new list, the algorithm operates on a copy of the data: when you call Arrays.sort(), the first thing the method does is take a clone of the array. Taking a clone of the array means taking a copy of the list of references, not of the actual data. The cost is generally negligible for large-ish arrays, but relatively considerable for sorting very small sets of data.
● The underlying insertion sort has a worst case where the input data is in reverse order; thus in principle, it is possible to hit an unlucky case consisting of a series of sub-lists in reverse order.
● In terms of recursion, this hybrid algorithm improves on some "textbook" cases of recursing right down until the sublist size is 1 or 2 (but at the expense of a less constant sort time as mentioned in the previous point).
● In most practical cases, doubling the size of the list more or less doubles the time taken to sort.

Q12. What is the difference between List and set? How do you maintain ordering feature in set?
Ans. List allows duplicate elements and maintains the order of elements. However, set doesn't allow duplicates and doesn't maintain order of the elements. To maintain the order of elements in a set, use Linked Hashset.

Q13. Difference btw add(Object o) and addElement(Object o) in Vector?
Ans:
add(int indx, Object e): Inserts the specified element at the specified position in this Vector. Return type is void

add(Object e): Appends the specified element to the end of this Vector. Return type is boolean

addElement(Object obj): Adds the specified component to the end of this vector, increasing its size by one. Return type is void.This method is identical in functionality to the add(Object) method (which is part of the List interface). add(Object) is due the fact that Vector implements List Interface and it has appeared since Java 1.2, time when Vector was moved to Collections. The collection classes from earlier releases, Vector and Hashtable, have been retrofitted to implement the collection interfaces. addElement is "original" Vector's method.


Q14. Tell me something about capacity increment in Vector?

Ans. Capacity increment is the amount by which the capacity of the vector is automatically incremented when its size becomes greater than its capacity.

Q15. What is the need for iterator?
Ans. The concept of an Iterator (another design pattern) can be used to achieve the abstraction. An iterator is an object whose job is to move through a sequence and select each object in that sequence without the client programmer knowing or caring about the underlying structure of that sequence i.e underlying structure can be Set, Array, Linked List or queue or anything else. Client need not know about the same, as he will make use of iterator() to traverse and iterator will take care of everything. In addition, an iterator is usually what’s called a lightweight object: one that’s cheap to create.

Q16. Explain List Iterator.
Ans. ListIterator is bidirectional. It can also produce the indexes of the next and previous elements relative to where the iterator is pointing in the list, and it can replace the last element that it visited using the set() method. You can produce a ListIterator that points to the beginning of the List by calling listIterator(), and you can also create a ListIterator that starts out pointing to an index n in the list by calling listIterator(n).

Also, regarding modification of collection, ListIterator has add(), remove() and set() methods, whereas Iterator has only remove method.

Q17. How does .remove() or .set() method work in iterator?

Ans. These operations work on last element being visited i.e. element returned by next() in case of iterators and next()/previous() in case of list iterators.

Q18. What do you mean by iterators are fail-safe or fail-fast?

Ans. If the map is "structurally" modified i.e. elements are added/removed (set operation is not structural modification) at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behaviour at an undetermined time in the future.

Q19. When do you get a ConcurrentModificationException while working with collections?

Ans. An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions:
1. In multithreaded processing: If one thread is trying to modify a Collection while another thread is iterating over it.
2. 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 Iterator's own remove or add methods.

Q20. What happens to Iterator and Enumerator if collection is modified after obtaining iterator or enumerator?

Ans. If collection is modified after obtaining iterator or enumerator:

1. Enumeration keeps state information about the collection; if the collection is modified while the enumeration is active, the enumeration may become confused. The enumeration fails in some random way, possibly through an unexpected runtime exception (e.g., a NullPointerException).


2. Iterators behave somewhat differently. If the underlying collection of an iterator is modified while the iterator is active, the next access to the iterator throws a ConcurrentModificationException, which is also a runtime exception. Unlike enumerations, if the iterator fails, the underlying collection can still be used. The way in which iterators fail immediately after a modify operation is called "fail-fast."


Q21. Explain Iterable interface.
Ans. Java SE5 introduced a new interface called Iterable which contains an iterator() method to produce an Iterator, and the Iterable interface is what foreach uses to move through a sequence. So if you create any class that implements Iterable and implements iterator() method of the interface, you can use it in a foreach statement:

Ex: 
public class MyCollection<E> implements Iterable<E>{
     public Iterator<E> iterator() {
          return new MyIterator<E>();
                  // where MyIterator is implementation of Iterator interface.
          }
}

public class MyIterator <T> implements Iterator<T> {
          public boolean hasNext() { //implement... }
          public T next() { //implement...; }
          public void remove() { //implement... if supported. }
}

Usage:
public static void main(String[] args) {
          MyCollection<String> stringCollection = new MyCollection<String>();
          for (String string : stringCollection) {
              System.out.println(string);
          }


}

Q22. Do you any drawback in design of stack?
Ans. If you want only stack behavior, inheritance is inappropriate here because it would produce a class with all the rest of the LinkedList methods.

Q23. Is it true that Map implements collection?

Ans. False

Q24. What is the difference btw entrySet() and keySet() ( in Map).
Ans. entrySet() gives a set view of the mappings in the map whereas keySet() gives a set view of the keys in the map. entrySet() provides a view on the map and not a copy. Thus if you modify entrySet(), original set will be modified.

Q25. Difference b/w HashSet(HashMap) and TreeSet(TreeMap)

Ans. HashSet is unsorted and has access time of O(1). TreeSet is a sorted set. It’s implemented on Red Black Tree, thus providing O(log n) time for all operations. 

Biggest advantage of latter is that elements are always sorted at any point of time.

Q26. What is default implementation of hashcode method.
Ans. The general contract of hashCode is:
  • Whenever it is invoked on the same object more than once during an execution of a Java application, hashCode method must consistently return the same integer. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtable.

Hashcode is NOT address, it says that it is based on the address. Consider that hash codes are 32 bits, but there are 64-bit JVMs. Clearly, directly using the address wouldn't always work. Thus, the default hash code of an object will not change with change in address of object after garbage collector runs.

Q27. Is it necessary to override hashcode() method if you override equals() method.
Ans. The value returned by hashCode() by default is the object's hash code. By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

Q28. What are the properties for equals() method?
Ans.
1. Reflexive
2. Symmetric
3. Transitive
4. Consistent
5. x.equals(null) is false

Q29. Do we need to implement or override both equals() and hashcode() method in Set and Map?
Ans. equals() -> Must be implemented for all forms of Set and Map.

hashcode() -> Necessary for HashSet(), LinkedHashSet() and HashMap(), LinkedHashMap() but *NOT* for TreeSet() and TreeMap()

NOTE: Value produced by hashcode() is not the index into the hashmap or hashset. Its computed further to calculate index. Mostly, it is modulo operation.

Q30. Data structure for accessing elements in least recently used way.
Ans. LinkedHashMap initialized as below
         new LinkedHashMap( capacity, load_factor, true);

Q31. Difference btw HashMap and HashTable?
Ans.
1. Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2.
2. The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.
3. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.
4. HashMap permits null values in it, while Hashtable doesn't.

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. 

Ex: HashMap usage example:
HashMap hm = new HashMap<Integer, Integer>();
Set set = hm.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
      Map.Entry me = (Map.Entry) i.next();
      System.out.println(me.getKey());
}

Q32. What are the primary considerations when implementing a user defined key?
Ans. 
1. You should override the equals() and hashCode() methods from the Object class. If a class overrides equals(), it must override hashCode().
2. If two objects are equal, then their hashCode values must be equal as well.
3. If a field is not used in equals(), then it must not be used in hashCode().
4. It is a best practice to implement the user defined key class as an immutable object.

Q33. How to create an immutable class?

Ans. To create an immutable class following steps should be followed:
1.  Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
2.  Make all fields final and private.
3.  Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
4.  If the instance fields include references to mutable objects, don't allow those objects to be changed:
o Don’t provide methods that modify the mutable objects.
o Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

Q34. What are the advantages of immutable objects?
Ans. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. The advantages are: 
1)    Immutable objects are automatically thread-safe; the overhead caused due to use of synchronisation is avoided.
2)    Once created the state of the immutable object cannot be changed, so there is no possibility of them getting into an inconsistent state.
3)    Freedom to cache, as they will never change and hence will reflect the correct data.
4)    Need not implement clone and copy constructors. 
5)    The best use of the immutable objects is as the keys of a map.
6) Safe against bad code. If someone tries to change a property of immutable object by mistake, he will get an error. On the other hand, if it was mutable, property would have been changed though not required.

Disadvantages:
Cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated. However, it can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.
           
Q35. Why String class is made immutable in Java?
Ans. Though, performance is also a reason since it maintains internal String pool to make sure the same String object is used more than once without having to create/re-claim it.  However, main reason is Security.

Ex: Suppose you need to open a secure file which requires the users to authenticate themselves. Let's say there are two users named 'user1' and 'user2' and they have their own password files 'password1' and 'password2', respectively. Obviously 'user2' should not have access to 'password1' file.  Now, since filenames in Java are specified by using Strings. Even if you create a 'File' object, you pass the name of the file as a String only and that String is maintained inside the File object as one of its members.

Had String been mutable, 'user1' could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from 'password1' to 'password2' before JVM actually places the native OS system call to open the file. This would have allowed 'user1' to open user2's password file. Understandably it would have resulted into a big security flaw in Java.

With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged "filename" String object. The 'filename' instance member being a 'final' in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).

Q36. Default size/capacity of various collections.
Ans. 
Collection    capacity   size     Load factor(if applicable)
ArrayList        10           0         N/A
Vector           10           0         N/A
HashTable      11           0         0.75
PriorityQueue 11          0          N/A
HashSet          16          0         0.75
HashMap         16          0         0.75

Constructs a new, empty hashtable with a default initial capacity (11) and load factor, which is 0.75.

Q37. What is WeakHashMap?
Ans. WeakHashMap is a hashtable based Map implementation with weak keys. Both null values and the null key are supported. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use i.e. presence of a mapping for a given key will not prevent the key from being discarded by the GC. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations. Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector.

This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. However, this class will also work with key objects whose equals methods are not based upon object identity, such as String instances. With such re-creatable key objects, however, the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing.


The behaviour of the WeakHashMap class depends in part upon the actions of the garbage collector. Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. In particular, even if you synchronize on a WeakHashMap instance and invoke none of its mutator methods, it is possible for the size method to return smaller values over time, for the isEmpty method to return false and then true, for the containsKey method to return true and later false for a given key, for the get method to return a value for a given key but later return null, for the put method to return null and the remove method to return false for a key that previously appeared to be in the map, and for successive examinations of the key set, the value collection, and the entry set to yield successively smaller numbers of elements.


Note: The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded. Note that a value object may refer indirectly to its key via the WeakHashMap itself. One way to deal with this is to wrap values themselves within WeakReferences before inserting, as in: m.put(key, new WeakReference(value)), and then unwrapping upon each get.


The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast.


Q38. Give me a WeakHashMap usage example.

Ans. A good example of WeakHashMap in action is the ThreadLocal class. ThreadLocal uses a WeakHashMap internally where the keys are Threads. When you call get(), the ThreadLocal class gets a reference to the current thread and looks up its value in the WeakHashMap. When the thread dies, it becomes unreachable and WeakHashMap automatically removes its mapping. If ThreadLocal used a regular HashMap, then the Threads stored in it would never become unreachable and they could hang around for a long, long time. This would essentially be a memory leak.

Q39. What is IdentityHashMap?

Ans. This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)). Like WeakHashMap, it permits null keys and null values.

This class is NOT a general-purpose Map implementation! It intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.


A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged.


This class has one tuning parameter (which affects performance but not semantics): expected maximum size. This parameter is the maximum number of key-value mappings that the map is expected to hold. Internally, this parameter is used to determine the number of buckets initially comprising the hash table. The precise relationship between the expected maximum size and the number of buckets is unspecified. For many JRE implementations and operation mixes, this class will yield better performance than HashMap (which uses chaining rather than linear-probing).


The iterators returned by all of this class's "collection view methods" are fail-fast.


Q40. What is DBI, i.e double brace initialization?
Ans. I had run into a use case of having to initialize a private static Map with a set of predefined values. Usually we define the variable and perform the setting of values via a static block. For some reason, this static block reminds me of the procedural way of doing things whereas we would like the initialization of the collection with its definition. While it is easy to do this for ArrayLists (by passing Arrays.asList to the constructor arg), I thought that there exists no such solution for Maps until now.

private static final Map<Integer, String> myConstantMap =
     new HashMap<Integer, String>() {
          {
               put(1, “abc”);               put(2, “def”);          }
     }

While this is not as straight-forward as the literal initialization done in Perl or Javascript, I was happy that something like this atleast existed. This is called the Double Brace Initialization (DBI) idiom. http://c2.com/cgi/wiki?DoubleBraceInitialization gives further details. In a nutshell, this piece of code creates an anonymous sub class which may be initialized in the inner brace. Since this is creating a subclass on the fly, it cannot be done for final classes (which are mostly not a problem with collections classes).

On further searching, I came across very different opinions. People either love it or loathe it. So it is important that we understand the reason behind their rationales and be mindful as to where we should use (and not use) them.

Cons:
1. Cannot be applied for final classes, except for Collections.
2. An additional anonymous class in your jar.
3. Objects created via DBI break the popular implementation of equals when compared against objects created without DBI (ones where class name comparisons are done -- not in most collections classes). Objects created by DBI will never be equal to objects created without it. However, collection classes should be fine.
4. Performance overhead of creating several anonymous classes.
5. This initializer is run before constructors, something that not everyone is readily aware of making it open for a newcomer to shoot themselves in the foot.
6. If the class in question is serializable, the new anonymous subclass thus created also needs to specify the serial version id -- pain to maintain. Also a problem if you wish to send it across the wire, where you always statically assume the class name of the object being resurrected.

Pros:

1. Elements are nested and inline making it more OO (than procedural).
2. Better readability
3. Performance overhead is minimal when usage is extremely sparse.
4. No worry about the order of execution of static block.

It would be nice if Java only created and initialized an instance, not create a new class for DBI and any anonymous "class" that does not add fields or override methods.

Thursday, 20 June 2013

Generics

Q1. Explain Type interface
Ans. This feature, known as type inference, allows you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets.
The complete syntax for invoking this method is:
         Box.<Crayon>fillBoxes(red, crayonBoxes);

Here we've explicitly provided the type to be used as U, but more often than not, this can be left out and the compiler will infer the type that's needed:

       Box.fillBoxes(red, crayonBoxes); // compiler infers that U is Crayon

Q2. Explain subtyping.
Ans. It is explained by generics. Now consider the following method:

public void boxTest(Box<Number> n) {
      // method body omitted
}


Looking at its signature, we can see that it accepts a single argument whose type is Box<Number>. So, we think that it should accept Box<Integer> or Box<Double>. Surprisingly, the answer is "no", because Box <Integer> and Box<Double> are not subtypes of Box<Number>, but Integer and Double are subtypes of Number.


Q3. Can you limit the generic type <T> to few types or Explain bounded types.

Ans. Yes. It can be done using extends keyword.
Ex. using <T extends Number> expects the parameter to be passed of type Number or its sub-class. It can’t accept a String.

To specify additional interfaces to implement, use & character, as shown below:
      <U extends Number & MyInterface>
Bounded type parameters limit the kinds of types that can be passed into a type parameter; they can specify an upper bound only.


Q4. Explain use of wildcards in generics

Ans. In contrast to bounded parameters, Wildcards represent unknown types, and they can specify an upper or lower bound.

Keyword extends gives upper bound, saying “an unknown type that is a subtype of Number or Number itself" and keyword super gives a lower bound, saying “an unknown type that is super-type of Number or is Number itself”.


Ex. <Box<? extends Number>

Box<Integer> and Box<Double> are not subtypes of Box<Number>, they are in fact subtypes of “<Box<? extends Number>”. Here ? is a wildcard character.

Ex. <? super Number> -> Class must be a super class of Number or Number itself. Thus, it can be Number or Object.


Q5. Explain type erasure.

Ans. During compilation, type erasure removes all generic information from a generic class or interface, leaving behind only its raw type. It is possible for generic code and legacy code to interact, but in many cases the compiler will emit a warning telling you to recompile with special flags for more details.
java.sun.com/docs/books/tutorial/java/generics/erasure.html

Random Java Ques

Q1. Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
Ans. No, you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of its subpackage.

Q2. Dictionary is an interface or class?
Ans. class.

Q3. Which one throws arithmetic exception:
a. int i = 100/0;b. float f = 100.00/0.0
Ans. b, float f = 100.00/0.0.
Float division by zero returns NAN (not a number) instead of exception.

Q4. Which one is not correct
a. x = = Float.NaNb. Float.isNan(x);
c. Myobject .equals(float.NaN);

Ans. a

Q5. Is below statement valid?
float f = 3.4;

Ans. No, a decimal number is a double by default. Assigning it to float requires a cast.


Q6. Java supports both multi dimension and nested arrays. True/False
Ans . False

Q7. What is the immediate super class of Container?
Ans. Component

Q8. What is the difference between the >> and >>> operators?
Ans. The >> operator carries the sign bit when shifting right. The >>> zero fills bits that have been shifted out.

Q9. Why would you prefer a short circuit “&&, ||” operators over logical “& , |” operators?
Ans: Firstly NullPointerException is by far the most common RuntimeException. If you use the logical operator you can get a NullPointerException. This can be avoided easily by using a short circuit “&&” operator as shown below.

if((obj != null) & obj.equals(newObj)) {

      //can cause a NullPointerException if obj == null because obj.equals(newObj) is always executed.
      ...
}

Short-circuiting means that an operator only evaluates as far as it has to, not as far as it can. If the variable 'obj' equals null, it won't even try to evaluate the 'obj.equals(newObj)’ clause as shown in the following example. This protects the potential NullPointerException.


if((obj != null) && obj.equals(newObj)) {

      //cannot get a NullPointerException because obj.equals(newObj) is executed only if obj != null
      ...
}

Q10. What happens if you put semicolon after if statement?
Ans. If you put a semicolon directly after the condition in if statement, Java thinks it's finished with the body of "if" statement (ONLY if statement).

NOTE: You can still continue with else statement.

if ( 1 == 2);
else System.out.println("false.");

Above code snippet prints "false", as else is considered continuation of "if" statement (since there is no other statement before else). However, if you put any other statement after "if" statement finished by semicolon, and then try to put else (as below), it will give a compilation error.


if ( 1 == 2); System.out.println("true.");

else System.out.println("false.");


Q11. In System.out.println(); explain what is System,out and println.
Ans. System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

Q12. What is the difference b/w procedure and function?

Ans. A procedure has a return type of void, whereas a function must return something.

Q13. Explain re-entrant, recursive and idempotent methods.
Ans. All Java methods are automatically re-entrant. It means that several threads can be executing the same method at once, each with its own copy of the local variables.

A Java method may call itself without needing any special declarations. This is known as a recursive method call. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive methods are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive.


Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. Ex: clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server (i.e. scalable).


Q14. Explain autoboxing and auto-unboxing?
Ans. It happens when converting primitive types to relevant object or vice-versa.

Ex:

Integer i;
int x = 5;
i = 5; // Auto-boxing happens since primitive int is converted to integer object.
float y = i ; //Auto un-boxing happens as value of Integer obj is converted to float.

Q15. What do you understand by downcasting?

Ans. The process of downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy

Q16. Give a scenario where explicit casting is not allowed, but implicit casting happens.

Ans. Incidentally, there is one situation in Java when only implicit casting is allowed, and that is string concatenation. Any time a string is concatenated with any object or base type, that object or base type is automatically converted to a string. Explicit casting of an object or base type to a string is not allowed, however.

Ex:String s = (String) 4.5; // this is wrong!

String s = “” + 4.5; // this is correct.

Q17. What is design by contract?
Ans. Design by contract specifies the obligations of a calling-method and called-method to each other. The strength of this programming methodology is that it gets the programmer to think clearly about what a function does, what pre and post conditions it must adhere to and also it provides documentation for the caller.

Java uses the assert statement to implement pre and post-conditions. Java’s exceptions handling also support design by contract especially in checked exceptions. In design by contract in addition to specifying programming code to carrying out intended operations of a method the programme also specifies:

1. Preconditions – This is the part of the contract the calling-method must agree to. Preconditions specify the conditions that must be true before a called method can execute. Preconditions involve the system state and the arguments passed into the method at the time of its invocation. If a precondition fails then there is a bug in the calling-method or calling software component.
2. Post-conditions – This is the part of the contract the called-method agrees to. What must be true after a method completes successfully. Post-conditions can be used with assertions in both public and non-public methods. The post-conditions involve the old system state, the new system state, the method arguments and the method’s return value. If a post-condition fails then there is a bug in the called-method or called software component.
3. Class invariants - what must be true about each instance of a class? A class invariant as an internal invariant that can specify the relationships among multiple attributes, and should be true before and after any method completes. If an invariant fails then there could be a bug in either calling-method or called-method. There is no particular mechanism for checking invariants but it is convenient to combine all the expressions required for checking invariants into a single internal method that can be called by assertions.
Ex: if you have a class, which deals with negative integers then you define the isNegative() convenient internal method.

Q18. Can we print address of a variable in java? If not, why?

Ans. In Java, say one object has been created at some particular address in Heap. At this point of time, we may feel that there should be some API which can return the address back. But, that is not possible because of another feature in Java - Garbage Collection. GC in Java not only collects the objects which are not live, it also does something called heap de-fragmentation. New objects gets created and old object gets deleted from the heap. As a result of this, free memory may lie non-utilized in between live objects. The GC moves all the live objects from one part of the memory to another part, so that contiguous free space remains available in the heap. Each time the object gets moved, its address gets changed. Depending on object's life span, this may happen many times. Hence the address also gets changed accordingly.

However, in java, it is possible to make JNI calls, which means I will be able to pass variables to JNI or I can access java variables in my JNI c++ code. And through my c++ code, I can print the address of the variable. But in that case, variable is not placed in jvm, instead it is stored in system memory. 


Q19. Why Java doesn't support sizeof operator?
Ans. Because all data types are the same size on all machines.

Q20. Why there are no global variables in Java?
Ans. Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
  • The global variables break the referential transparency.
  • Global variables create collisions in namespace.
Java doesn't support global variables, by design. Java was designed with object oriented principles in mind and as such, every variable in Java is either local or a member of a class. Static class members, whilst accessible via the class name and therefore across multiple scopes, are still class members; and therefore not global variables as such. Java's lack of support for global variables is a good thing, as using global variables is a design anti-pattern.

Q21. Difference btw getName(), getCanonicalName() and getSimpleName()

Ans. getName() and getCanonicalName() are same. Both includes package information, whereas getSimpleName() produces the class name alone.

Q22. Can you instantiate the Math class?
Ans. You can’t instantiate the Math class. All the methods in this class are static. And the constructor is not public.

Q23. Math.random and java.util.Random
Ans. Using Math.random works well when you need to generate a single random number. If you need to generate a series of random numbers, you should create an instance of java.util.Random and invoke methods on that object to generate numbers

Math.random() method returns a pseudo-randomly selected number between 0.0 and 1.0. The range includes 0.0 but not 1.0. In other words: 0.0 <= Math.random() < 1.0.


NOTE:  Default seed to java.util.Random is based on the current time.  However, same can be passed as an argument while initializing Random object.


Q24. Explain valueOf, toString and parseXXX in Number class?

Ans.
valueOf: The valueOf method converts a string to a number, and returns an object of given type.
Ex. Float.valueof(“5”) converts a string containing 5 into a float object with value 5.
parseXXXX: Similar to valueOf, except that it returns a primitive type.
Ex. Float.parseFloat(“5”) converts a string containing 5 into a primitive float with value 5.
toString: This method converts a number to a string.
Ex. toString(5) returns a string object containing 5 in it.


Q25. How can you get environment variables?

Ans. An application uses System.getEnv to retrieve environment variable values. Without an argument, getEnv returns a read-only instance of java.util.Map, where the map keys are the environment variable names, and the map values are the environment variable values.

Q26. How will you get the platform dependent values like line separator, path separator, etc.?
Ans. Using Sytem.getProperty(…) (line.separator, path.separator, …)

Q27. Can we pass a new-line ('\n') character or any other escape sequence via command line in Java?
Ans. No. The question arises, if you pass the same escape sequence programmatically, it works fine, so why doesn't it work well when passed via command line.

Ex: System.setProperty("line.separator", " Bye!\nBBye!"); will work fine, but if try to do the same via command line as (java -Dline.separator=" Bye!\nBBye!" ClassName) then '\n' will be treated as two distinct ASCII characters ('\' and 'n') and not as a single escape sequence new-line Unicode character.

This behaviour was logged as a bug on Sun's Bug Database. But, it was closed saying 'not a bug'. The reason given is that interpretation of text passed on command line is a shell specific stuff and it is not reasonable to expect that to work in lines with the handling of escape sequences by any particular programming language.

It's not something to do with Java as even if you pass a command line argument having '\n' to a C program, it will be treated as two distinct ASCII characters only and not as a escape sequence.

Q28. How to define it a pattern and match it against a string.
Ans. The java.util.regex package primarily consists of three classes:
           Pattern, Matcher, and PatternSyntaxException.
- A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile methods, which will then return a Pattern object. These methods accept a regular expression as the first argument.

- A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the static matcher method on a Pattern object.


- A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.


Q29. How can you specify union, intersection & subtraction in regular expressions.

Ans:
Union: To create a union, simply nest one class inside the other, such as [0-4[6-8]]. This particular union creates a single character class that matches the numbers 0, 1, 2, 3, 4, 6, 7, and 8.

Intersection: To create a single character class matching only the characters common to all of its nested classes, use &&, as in [0-9&&[345]]. This particular intersection creates a single character class matching only the numbers common to both character classes: 3, 4, and 5


Subtraction: Finally, you can use subtraction to negate one or more nested character classes, such as [0-9&&[^345]]. This example creates a single character class that matches everything from 0 to 9, except the numbers 3, 4, and 5.


Q30. Explain assertions.

Ans. An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. Ex: If you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.


Simpler form of assertion is assert Expression1; where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.


Q31: Explain some of the new features in J2SE 5.0, which improves ease of development?

Ans : The J2SE 5.0 release is focused along the key areas of ease of development, scalability, performance, quality, etc. The new features include
1. Generics
2. Metadata (aka annotations)
3. Autoboxing and auto-unboxing of primitive types
4. Enhanced “for” loop
5. Enums i.e. enumerated type
6. static import
7. C style formatted output and formatted input
8. varargs
9. New I/O which is non blocking: Scanner API provide a more robust mechanism for reading in data types rather than simply parsing strings from buffered System.in calls. Prior to Scanner feature was introduced, to read from standard input it would be necessary to write exception handling code and wrap an InputStreamReader and a BufferedReader around System.in. Scanner class throws an unchecked exception InputMismatchException, which you could optionally catch. Scanner API simplifies your code as follows:

//read from keyboard using the java.util.ScannerScanner

keyboard = new Scanner(System.in);
System.out.println("Enter your first number?");
int i1 = keyboard.nextInt();

Q32. What is phantom memory?

Ans. Phantom memory is false memory, one that does not exist in reality.

Q33. What is the GregorianCalendar class?

Ans. The GregorianCalendar provides support for traditional Western calendars.

Q34. What is the ResourceBundle class?

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

Q35. What is reflection in Java?

Ans. Java Reflection is a technology that looks inside a Java object at runtime and sees what variables it contains, what methods it supports, what interfaces it implements, what classes it extends - basically everything about the object that you would know at compile time.

Q36. What is the difference between instanceof and isInstance?

Ans.
instanceof - Used to check to see if an object can be cast into a specified type without throwing a cast class exception.
isInstance() - Determines if specified object is assignment-compatible with the object represented by this Class.

Instanceof() is a reserved word of Java, but isInstance() is a method of java.lang.Class. isInstance() method is dynamic equivalent of instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException and false otherwise. If argument is null, method returns false.


In instanceof operator, you can compare it to a named type only, and not to a Class object. Like, there is no way to cleverly automate objects by creating a Vector of Class objects and comparing it to those. isInstance() remove this problem and call instanceof() operator dynamically.


You could use instanceof() on types (which are known on compile time), and isInstance() could only be called on an instance of java.lang.Class.

if (obj instanceof MyType) {
     ...
}

if (MyType.class.isInstance(obj)) {

      ...
}

So you can have dynamism using isInstance() as given below. You could check the type of an object with an unknown class during compile time! 



Class x = Integer.class;
if (x.isInstance(obj)) {
    ...
}

x = String.class;
if (x.isInstance(obj)) {
    ...
}

Q37. Explain type.getConstructor(int.class).newInstance()?
Ans. type -> A class whose constructor is to be retrieved
        int.class -> Constructor accepting an integer argument
        newInstance() -> Create a object of type “type”, with constructor obtained.

The newlnstance() method of Class is a way to implement a "virtual constructor," which allows you to say, "I don’t know exactly what type you are, but create yourself properly anyway." And when you create a new instance, you get back an Object reference. In addition, the class that’s being created with newlnstance() must have a default constructor.


Q38. What is a native method?
Ans. A native method is a method that is implemented in a language other than Java.

Q39. Explain annotations.
Ans. It’s a way to introduce meta-data with the program.3 annotations are:
1. @Deprecated – @deprecated used to serve the same purpose before introduction of annotations.
2. @Override
3. @SuppressWarnings (type)
2 and 3 are new annotations introduced.


One can define its own annotations. Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the interface keyword. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, 

enums, annotations, and arrays of the preceding types. Methods can have default values.

Here is an example annotation type declaration:

/* Describes the RequestForEnhancement(RFE) that led to the presence of the annotated API element.
*/
public @interface RequestForEnhancement {
      int id();

      String synopsis();
      String engineer() default "[unassigned]";
      String date(); default "[unimplemented]";
}

@RequestForEnhancement(

      id = 2868724,
      synopsis = "Enable time-travel",
      engineer = "Mr. Peabody",
)


Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above.


Q40. Hot deployment & dynamic reloading

Ans. Hot deployment is the process of adding new components (such as WAR files, EJB Jar files, enterprise Java beans, servlets, and JSP files) to a running server without having to stop the application server process and start it again.

Dynamic reloading is the ability to change an existing component without needing to restart the server in order for the change to take effect. Dynamic reloading involves:

a. Changes to the implementation of a component of an application, such as changing the implementation of a servlet.
b. Changes to the settings of the application, such as changing the deployment descriptor for a Web module

Although hot deploy seems a good feature, it's not natively supported by the Java Virtual Machine (JVM) because. Once a given class is defined by a ClassLoader it cannot be redefined. That's where a custom class loader enters. The idea is simple, exploit the JVM behaviour.


Classes are not only identified by its package name and class name, but also by the class loader instance that defined the class. Hence, using a new instance when needed will allow the developer to load the new class version into the JVM. It might sound simple, but the process itself has implications regarding how to deal the new class casting. Other problems related with the use of class loaders are:

a. Memory usage: Various definitions of classes will be loaded into memory, since new class loaders instances keep defining new versions of classes.
b. The possible scenario of old instances and new instances co-existing, this is especially problematic if object serialization is being used.

Hot Deployment

Web containers commonly have a special directory (e.g. “webapps” in Tomcat, “deploy” in JBoss) that is periodically scanned for new web applications or changes to the existing ones. When the scanner detects that a deployed .WAR is updated, the scanner causes a redeploy to happen (in Tomcat it calls the StandardContext.reload() method). Since this happens without any additional action on the user’s side it is commonly referred to “Hot Deployment”.

Hot Deployment is supported by all wide-spread application servers under different names: autodeployment, rapid deployment, autopublishing, hot reload, and so on. In some containers, instead of moving the archive to a predefined directory you can configure the server to monitor the archive at a specific path. Often the redeployment can be triggered from the IDE (e.g. when the user saves a file) thus reloading the application without any additional user involvement. Although the application is reloaded transparently to the user, it still takes the same amount of time as when hitting the “Reload” button in the admin console, so code changes are not immediately visible in the browser.


Q41. What major patterns do the Java APIs utilize?

Ans. Design patterns are used and supported extensively throughout the Java APIs. Here are some examples:
1. MVC pattern: Used extensively throughout the Swing API.
2. Factory Method Design Pattern: Used in getInstance() method in java.util.Calendar
3. Singleton Pattern: Classes java.lang.System and java.sql.DriverManager, though they are not implemented using the approach recommended in the GoF book but with static methods.
4. Prototype Pattern: Supported in Java through the clone() method defined in class Object and the use of java.lang.Cloneable interface to grant permission for cloning.
5. Command Pattern: The Java Swing classes support the Command pattern by providing an Action interface and an AbstractAction class.
6. Observer Pattern: The Java 1.1 event model is based on the observer pattern. In addition, the interface java.util.Observable and the class java.util.Observer provide support for this pattern.
7. Adapter Pattern: Used extensively by the adapter classes in java.awt.event.
8. Proxy Pattern: Used extensively in the implementation of Java's Remote Method Invocation (RMI) and Interface Definition Language (IDL) features.
9. Composite Pattern: The structure of Component and Container classes in java.awt provide a good example of the Composite pattern.
10. Bridge Pattern: The Bridge pattern can be found in the separation of the components in java.awt (e.g., Button and List), and their counterparts in java.awt.peer.

Q42. Which patterns were used by Sun in designing the Enterprise JavaBeans model

Ans. Many design patterns were used in EJB, and some of them are clearly identifiable by their naming convention. Here are several:
1. Factory Method: Define a interface for creating classes, let a subclass (or a helper class) decide which class to instantiate.
This is used in EJB creation model. EJBHome defines an interface for creating the EJBObject implementations. They are actually created by a generated container class. See InitialContextFactory interface that returns an InitialContext based on a properties hashtable.

2. Singleton: Ensure a class has only one instance, and provide a global point of access to it. There are many such classes. One example is javax.naming.NamingManager


3. Abstract Factory: Provide an interface for creating families of relegated or dependent objects without specifying their concrete classes.We have interfaces called InitialContext, InitialContextFactory. InitialContextFactory has methods to get InitialContext.


4. Builder: Separate the construction of a complex factory from its representation so that the same construction process can create different representations. InitialContextFactoryBuilder can create a InitialContextFactory.


5. Adapter: Convert the interface of a class into another interface clients expect.In the EJB implementation model, we implement an EJB in a class that extends SessionBean or a EntityBean. We don't directly implement the EJBObject/home interfaces. EJB container generates a class that adapts the EJBObject interface by forwarding the calls to the enterprise bean class and provides declarative transaction, persistence support.


6. Proxy: Provide a surrogate for other object to control access to it. We have remote RMI-CORBA proxies for the EJB's.


7. Memento: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.


Q43. Which design pattern does I/O classes use?

Ans. I/O classes use Decorator design pattern. The decorator design pattern attaches responsibilities to objects at runtime. Decorators are more flexible than inheritance because inheritance attaches responsibility to classes at compile time. The java.io.* classes use the decorator pattern to construct different combinations of behaviour at runtime based on some basic classes.

Q44. Explain the Java I/O streaming concept and the use of the decorator design pattern in Java I/O?
Ans: Java input and output is defined in terms of an abstract concept called a “stream”, which is a sequence of data. There are 2 kinds of streams.
1. Byte streams (8 bit bytes) -> Abstract classes are: InputStream and OutputStream
2. Character streams (16 bit UNICODE) -> Abstract classes are: Reader and Writer

Design pattern: java.io.* classes use the decorator design pattern. The decorator design pattern attaches responsibilities to objects at run time. Decorators are more flexible than inheritance because the inheritance attaches responsibility to classes at compile time. The java.io.* classes use the decorator pattern to construct different combinations of behavior at run time based on some basic classes.

Q45. Loading, Linking and Initialization
Ans. The class loader subsystem is responsible for more than just locating and importing the binary data for classes. It must also verify the correctness of imported classes, allocate and initialize memory for class variables, and assist in the resolution of symbolic references. These activities are performed in a strict order:
1. Loading: finding and importing the binary data for a type

2. Linking: performing verification, preparation, and (optionally) resolution
   a. Verification: ensuring the correctness of the imported type
   b. Preparation: allocating memory for class variables and initializing the memory to default values
   c. Resolution: transforming symbolic references from the type into direct references.


3. Initialization: Invoking Java code that initializes class variables to their proper starting values.


Q46. What happens when you call Class.forName() method?
Ans. Creating a reference to a Class object using ".class" doesn’t automatically initialize the Class object. However, Class.forName() initializes the class immediately in order to produce the Class reference There are actually three steps in preparing a class for use:
1. Loading: It is performed by the class loader. This finds the bytecodes and creates a Class object from those bytecodes.
2. Linking: The link phase verifies the bytecodes in the class, allocates storage for static fields, and if necessary, resolves all references to other classes made by this class.
3. Initialization: If there’s a superclass, initialize that. Execute static initializers and static initialization blocks.

If a static final value is a "compile-time constant" that value can be read without causing the class to be initialized. Making a field static and final, however, does not guarantee this behaviour. However, if static final variable value is calculated at run time, it forces class initialization because it cannot be a compile-time constant.

If a static field is NOT final, accessing it always requires linking (to allocate storage for the field) and initialization (to initialize that storage) before it can be read.

Q47. Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?
Ans: Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So, how is the very first class loaded? The very first class is especially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.                        CLASS LOADERS                                                                       RELOADABLE                                                                                     EXPLAINATION

BootStrap(Primordial)
No
Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar)
Extensions
No
Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)
System
No
Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line
options)

Bootstrap
(primordial)
(rt.jar, i18.jar)
           /|\
            |
Extensions
(lib/ext)
           /|\
            |
System
(-classpath)
           /|\
            |
[Sibling1 classloader]              [Sibling1 classloader]

Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.

Hence,

1.) Classes loaded by Bootstrap class loader have NO visibility into classes loaded by its descendants (ie Extensions and Systems class loaders).
2.) The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).
3.) If there were any sibling class loaders they cannot see classes loaded by each other. They can seen only by classes loaded by their parent class loader.

For example Sibling1 class loader cannot see classes loaded by Sibling2 class loader Both Sibling1 and Sibling2 class loaders have visibilty into classes loaded by their parent class loaders (eg: System, Extensions, and Bootstrap).

In the general case, when a thread runs the code of class A and comes across a reference for class B, it attempts to load the code for class B from the same classloader that loaded class A (or one of that classloader's ancestors in the classloading hierarchy). This approach is taken irrespective of which threads or classloaders were originally involved in loading class A. A classloader knows only about its ancestors, not its descendants.


Q48. Can two objects loaded by different class loaders be same?
Ans. Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton.

Q49. Explain about context Class loaders.
Ans. Threads interact with the classloader in one particular case. Each thread is assigned a specific classloader known as the context classloader. This classloader is retrieved with the getContextClassLoader() method and set with the setContextClassLoader() method.

The context classloader only comes into play with certain internal classes in the virtual machine. 

Q50. Explain static vs. dynamic class loading?
Ans.
Static class loading
 Dynamic class loading
Classes are statically loaded with Java’s “new” operator.
class MyClass {
          public static void main(String args[]) {
                   Car c = new Car();
          }
}
Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically.

Class.forName (String className); //static method which returns a Class

The above static method returns the class object associated with the class
name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.
class.newInstance (); //A non-static method, which creates an instance of a
//class (i.e. creates an object).

Jeep myJeep = null ;
//myClassName should be read from a .properties file or a Constants class.
// stay away from hard coding values in your program. CO
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);
A NoClassDefFoundException is thrown if a class is referenced with Java’s “new” operator (i.e. static loading) but the runtime system cannot find the referenced class.
A ClassNotFoundException is thrown when an application tries to load in a
class through its string name using the following methods but no definition for the class with the specified name could be found:
●      The forName(..) method in class - Class.
●      The findSystemClass(..) method in class - ClassLoader.
●      The loadClass(..) method in class - ClassLoader.

Q51. Towers of Hanoi Problem Solution

Stable sorts
count sort, merge sort, bubble sort, radix sort, insertion sort, binary tree sort

Non stable sorts
quick sort, heap sort, selection sort, shell sort

Burstsort and its variants are cache-efficient algorithms for sorting strings and are faster than quicksort and radix sort for large data sets. Burstsort algorithms use tries to store prefixes of strings, with growable arrays of pointers as end nodes containing sorted, unique, suffixes (referred to as buckets). Some variants copy the string tails into the buckets. As the buckets grow beyond a predetermined threshold, the buckets are "burst", giving the sort its name. A more recent variant uses a bucket index with smaller sub-buckets to reduce memory usage. Most implementations delegate to multi key quicksort, an extension of three-way radix quicksort, to sort the contents of the buckets. By dividing the input into buckets with common prefixes, the sorting can be done in a cache-efficient manner.

Max subarray problem
1-d ->  http://en.wikipedia.org/wiki/Maximum_subarray_problem

Big Endian: MSB’s at beginning