Explain DTD

A document type definition (DTD) describes the permissible tags of an XML document.

The DTD serves as a data template. It defines entities, elements, attributes, and notations, as well as the relationships between these.

For example, the DTD can state that a memo element consists of To, From, Subject, and Message elements.

You need to use a DTD if you want the XML processor to validate your XML documents.

DTDs can help you ensure that your XML documents are well-formed.

You need to indicate to the XML processor that a DTD should be used. This is done by adding a document type declaration before the document element.

The DTD can be internal or external to the document. If the DTD is external, you will need to specify its location or URL.

Is an XML schema an alternative to DTD

Schemas are becoming more popular and DTDs less so. A schema is an XML-based syntax for describing how the XML document is marked up or how it looks – very similar to a DTD, but a DTD has a lot of drawbacks.
A DTD doesn’t use anything like XML syntax to describe the definition. You can’t do data typing in a DTD, and it’s not extensible.

An XML schema allows you to specify elements as an integer, a float, a Boolean, or whatever, and has more extensibility to it. Plus, it’s in XML format. Your XML schema, the definition for your XML, is also in XML format.
Microsoft is pushing the XML schema – so you’re likely to see schemas more and more. That’s all we use. In fact, the new BizTalk Server from Microsoft actually uses schemas.

Explain XML Namespaces

An XML namespace is a collection of element names or attribute names to be defined within an XML document.
Let’s say you have an invoice XML document and an order XML document and you want to put them together. You usually have certain names that overlap each other – like the date. You might have an invoice date and an order date – both called “date”.

With a namespace, you have an invoice date and an order date, and you can reference them as such – “invoice:date” and then “order:date.” That way you can still use the same two tag names and you won’t get confused about which is which. That’s really what an XML namespace is supposed to do for you.

What are the advantages of XML

XML is free form which means that you can configure it any way you want. It’s also very easy to read – you don’t have to read cryptic code to figure it out.
It was designed specifically for internet protocols, and this makes it simple to transmit an XML document across, for example, a HTTP protocol.
Strong data typing is available for xml, and it is also compatible with the SGML standard.

XML is Application independent – you can transfer XML data from a C language program to a Visual Basic program. Or you could, for example, have XML data going from one server out across the internet and being picked up by another application running on a Unix box. XML is also platform independent – it works equally well on Windows, UNIX, or for example, a CICS on a mainframe.
XML is also language independent so it doesn’t matter what type of programming language you’re using – C, Visual Basic, ASP using JavaScript. It doesn’t matter – all have mechanisms to read an XML document.

XML is Unicode-based which makes it very flexible and very good for operating across languages like English, Spanish, or French. You can describe all these types of languages since it’s in Unicode.
A huge benefit of XML is that it’s license free –
it doesn’t cost anything to use XML.

Differences between DTD and Schema

  XML Schema DTD
Markup validation Any global element can be root. No ambiguous content support. Can specify only the root element in the instance document. No ambiguous content support.
Namespace support Yes. Declarations only where multiple namespaces are used. No.
Code reuse Can reuse definitions using named types. Poorly supported. Can use parameter entities.
Datatype Validation Provides flexible set of datatypes. Provides multi-field key cross references. No co-occurrence constraints. No real datatype support.

What are the disadvantages of DTD

  • They are not written in XML syntax, which means you have to learn a new syntax in order to write them
  • there is no support for namespaces
  • there are no constraints imposed on the kind of character data allowed, so datatyping is not possible
  • there is minimal support for code modularity and none for inheritance
  • large DTDs are hard to read and maintain
  • there are no default values for elements and attribute defaults must be specified when they are declared
  • its attribute value models and ID attribute mechanism are simplistic
  • there is limited ability to control whitespace
  • there is limited documentation support, as you cannot use the structured documentation features available for schema notation

Exception Drill

1. What is an Exception ?
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.

2. What is a Java Exception ?
A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.

3.Where does Exception stand in the Java tree hierarchy ?
         java.lang.Object
         java.lang.Throwable
         java.lang.Exception
         java.lang.Error

4.What are checked exceptions ?
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

5.What are runtime exceptions ?
Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

6.What is the difference between error and an exception ?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. 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.).

7.How to create custom exceptions ?
Your class should extend class Exception, or some more specific type thereof.

8.If I want an object of my class to be thrown as an exception object, what should I do ?
The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

9.If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object ?
One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

10.How does an exception permeate through the code ?
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

11.What are the different ways to handle exceptions ?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

12.What is the basic difference between the 2 approaches to exception handling.
1 try catch block and
2 specifying the candidate exceptions in the throws clause ?
In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it’s own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

13.Is it compulsory to use the finally block  ?
It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block.

14.How are try, catch and finally block organized  ?
A try block should associate with at least a catch or a finally block. The sequence of try, catch and finally matters a lot. If you modify the order of these then the code won’t compile. Adding to this there can be multiple catch blocks associated with a try block. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch-finally block.

15.What is a throw in an Exception block ?
“throw” is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
throw new NullPointerException(“thrownException”);

16.What is the use of throws keyword ?
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.

type method-name(parameter-list) throws exception-list {
// body of method
}

Here, exception-list is a comma-separated list of the exceptions that a method can throw.

static void throwOne() throws IllegalAccessException {
System.out.println(“Inside throwOne.”);

17.Is it necessary that each try block must be followed by a catch block ?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

18.If I write return at the end of the try block, will the finally block still execute ?
Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

19.If I write System.exit (0); at the end of the try block, will the finally block still execute ?
No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

20.What are Checked and UnChecked Exception ?
A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream’s read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String’s charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

21.Give me some examples of Checked Exceptions and Unchecked Exceptions ?
Unchecked Exceptions. 
         ArithmeticException 
         ArrayIndexOutOfBoundsException
         ClassCastException
         IndexOutOfBoundsException
         IllegalStateException
         NullPointerException
         SecurityException 

Checked Exception
        ClassNotFoundException
        CloneNotSupportedException 
        IllegalAccessException
        InstantiationException
        InterruptedException
        NoSuchFieldException
        NoSuchMethodException

22. What are Chained Exceptions ?
The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. Lets take a simple example. You are trying to read a number from the disk and using it to divide a number. Think the method throws an ArithmeticException because of an attempt to divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. This is the place where chained exceptions come in to picture.

Throwable getCause( )
Throwable initCause(Throwable causeExc)

Collections Drill – II

1.What is meant by compatible equals() and hashCode() methods ?
In order for the Java Collections to work properly (and everything else in Java), the equals() and hashCode() methods must be compatible. Here, compatible means that if equals() reports that two instances are the same, then the hashCode() of both instances must be the same value.

2.Since Properties extends Hashtable, can I use the Hashtable methods to add elements to a Properties list ?
Technically speaking you can. However, you have to make sure you only add key-value pairs where both are strings. If you add something other than a String, the listing, loading, and saving methods won’t work as expected.
Like the Stack/Vector subclass relationship, Properties/Hashtable should be a has-a relationship, not an is-a/subclass relationship.

3.When I wrap a collection to be read-only or synchronized, why can’t I call any of the collection methods via reflection without getting an IllegalAccessException ?
When you wrap a collection through the static methods of the Collections class, this creates an instance of a package-private (default access) class. Because you don’t have access to these classes, you can’t call their methods via reflection (though you can call their methods directly through the appropriate interface).

4.What is a weak reference and what are they used for ?
Normally the Java garbage collector plays safe. It will only free up the memory used by an object when that object can no longer be accessed by the program. Once an object become impossible to reach it is eligible for collection, and eventually its memory will be reclaimed.
This eliminates one of the most common programming errors in some other languages (like C++), where code accidentally tries to access an object that has been freed. Unfortunately it can lead to another problem, where you leave open a potential access route to an object that you don’t need any more. Memory fills up, and the program slows down or reports an “Out of Memory” error.

To avoid this, you can be very careful to close off access paths to an object once you have finished using it. Java 2 introduces another alternative, the weak reference. Weak references provide access to an object without preventing it from being freed. When you use a weak reference you have to accept that the object referred to may have disappeared, which results in the reference being automatically set to null. On the other hand, the weak reference will not hold the object in memory once it is inaccessible via normal references (or via “soft” references – see below). Weak references are not appropriate in all circumstances, but sometimes they can make code easier to write and understand.

The most common use of weak references is indirect – they are used internally by the WeakHashMap class. Like HashMap, WeakHashMap associates key objects with values. However, once the key object becomes inaccessible via stronger references it becomes eligible for garbage collection. When it is freed, the map entry magically disappears. The assumption here is that if you are not using the key anywhere other than in the map you will have no need to look it up, so it should be freed.

Other specialist references are soft references (which inhibit collection until memory runs short), and phantom references (used for cleanup when objects are freed).

5.What is the minimum number of key-value pairs for which it makes sense to use a HashMap, as opposed to using a pair of arrays (one for keys, the other for values) with brute-force key searches ?

Many people often need maps for very small numbers (2-5) of key-value pairs. When does it make sense to forgo the convenience of the HashMap to avoid the associated overhead?
Well, is there really that much of a performance loss using a HashMap? There is no synchronization penalty (unless you impose your own). You can tune the sizing by adjusting the initial size and load factor. Plus, do you really want to be responsible for “rolling your own” code to handle the dynamic resizing of the key and value arrays, inserting/removing data from these arrays, optimizing the searching algorithm, etc. Yuck!

In general, the performance hit associated with using a general purpose Map (such as the HashMap) is far outweighed by the benefits of using a simple interface backed by a tested algorithm.

The only reason I could see wanting to use arrays is to guaruntee the type of your key/values to add type checking and avoid casting. Still, if this is a critical aspect of your application, you can wrap your HashMap in another object to provide type-safety, and the casting overhead should be minimal.

Another alternative to creating a custom solution is to explore other collection classes, such as ObjectSpaces’s JGL Libraries. There may be something there that would suit your needs.

So, to answer your question, I would say that the fewer the key-value pairs you have, the more reason you have to use a HashMap. Since the fewer the keys, the faster the search, why not use it for 2-5 key-value pairs. I would think that only when you get to many pairs (tens of thousands) and there is a performance problem you should consider an alternative. Basically, exhaust your search of tried-and-true collections before you try a custom solution. Let other people create these collections so you can focus on your application.

6.How does ArrayList increase its capacity ?
Unlike Vector where you can specify a capacity increment, ArrayList doesn’t support this. Instead, ArrayList will increase capacity by about a half when it runs out of space. The refernece implementation uses the forumla:
newCapacity = (oldCapacity * 3)/2 + 1
though, this isn’t part of the class definition so others can implement it differently.

7.What is the default initial size for a Hashtable / HashMap ?
This depends on what version of Java you are using. For JDK 1.2, the size was 101. For JDK 1.3, the size changed to 11.

8.How do you create a multi-dimensional List ?
Since the elements of a List are objects, in order to make the List multi-dimensional, each object in the outer list needs to be a List, too. For instance, …

List list = new ArrayList(10);
for (int i=0; i<10; i++) {
list.set(i, new LinkedList());
}

Then just fill up each inner list with items.

9.In a TreeMap, can I use a sorting algorithm other than the natural sorting for the keys ?
You can pass a Comparator to the TreeMap constructor to use a sorting order other than the natural order.

10.What are the differences between HashMap and Hashtable ?
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, v1.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.

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.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn’t.

For new code, I would tend to always use HashMap.

11.What are the differences between Vector and ArrayList? Which is best to use ?
Vector and ArrayList are very similar. Both of them represent a ‘growable array’, where you access to the elements in it through an index.

ArrayList it’s part of the Java Collection Framework, and has been added with version 1.2, while Vector it’s an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.

The main difference is that Vector it’s a synchronized object, while ArrayList it’s not.

While the iterator that are returned by both classes are fail-fast (they cleanly thrown a ConcurrentModificationException when the orignal object has been modified), the Enumeration returned by Vector are not.

Unless you have strong reason to use a Vector, the suggestion is to use the ArrayList.

12.How should I implement object comparisons in a flexible manner? For example, I have a Person class and sometimes I will compare based on name and sometimes I will compare based on age.
Instead of having the Person class implement the Comparable interface, you could delegate the comparing to another class. Perhaps you could have a PersonComparator interface that you could implement for the various types of comparisons. For example:
public interface Person {
public String getName();
public int getAge();
}

public interface PersonComparator {
public int compare(Person p1, Person p2);
}

public class AgeComparator implements PersonComparator {
public int compare(Person p1, Person p2) {
if (p1.getAge() == p2.getAge()) return 0;
return p1.getAge() > p2.getAge() ? 1 : -1;
}
}

public class NameComparator implements PersonComparator {
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
}

This is a very simple example of the Strategy Pattern. This allows your comparisons and your object to change independent of one another.

13.Does the equals() method of an array do element-level checking ?
If you have two arrays in memory with the same elements, and ask first.equals(second), this does not do an element-by-element comparison. Instead, it behaves just like Object’s equals() method, essentially asking if the variables point to the same place in memory:
int a[] = {1, 2, 3};
int b[] = {1, 2, 3};
// This prints false
System.out.println(a.equals(b));

To check for equality of two arrays, use Arrays.equals().
// This prints true
System.out.println(Arrays.equals(a,b));

14.How can I retrieve the items in my HashSet / HashMap in the order they were added ?
Prior to Java 1.4, you had to manage a separate insertion order list yourself. Starting with Java 1.4, you can use the new LinkedHashMap / LinkedHashSet classes. The iterators you get back from them return the items in insertion order.

15.How do you sort an ArrayList (or any list) of user-defined objects ?
Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

16.How can you get the hash code for an instance of a class if the class overrode hashCode() ?
The System class method identityHashCode() allows you to get this information:
int code = System.identityHashCode(anObject);

17.How can I easily shift the elements in a List / Vector such that all the elements rotate n elements ?
The Java 1.4 API adds a rotate() method to the Collections class: rotate(List list, int distance) that will shift the elements for you.

18.What’s the most optimum way of swapping two elements in a List ?
The 1.4 version of Collections has a swap() method to do this for you. However, for earlier version of Java, you can swap two elements w/o an intermediate variable with:
list.set(index1, list.set(index2, list.get(index1)));
This works because the set() method returns the original element.

19.What’s the purpose of the IdentityHashMap ?
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.

20.How do I convert an old-style Enumeration to something in the Collections Framework ?
Prior to Java 1.4, any conversion had to be manually done. With the introduction of 1.4, you can call Collections.list(enumeration) to automatically convert the Enumeration to an ArrayList.

21.How do I retrieve the values of a Hashtable/HashMap in sorted order ?
Basically, you can’t directly do this. What you can do is get the Collection of values() back from the map and create a sorted collection, or maintain two maps, one in each direction, and keep the second map sorted by being a TreeMap. Which you use depends on the frequency you must sort the elements.

22.How can I add a Collection to another Collection ?
The java.util.Collection interface includes an addAll(Collection c) method to add one collection to another.

23.How can I use two iterators to go through a collection ?
Just get a separate iterator for each loop:
Collection l = …;
for(Iterator i = l.iterator(); …) {
for(Iterator j = l.iterator();…) {
}
}

24.How do I traverse a map backwards ?
Just keep getting the last key and the head map before it:
if (!map.isEmpty()) {
Object last = map.lastKey();
boolean first = true;
do {
if (!first) {
System.out.print(“, “);
}
System.out.print(last);
last=map.headMap(last).lastKey();
first=false;
} while (last != map.firstKey());
System.out.println();
}

25.How do I traverse a sorted set backwards ?
Just keep getting the last element and the head set before it:
if (!set.isEmpty()) {
Object last = set.last();
boolean first = true;
do {
if (!first) {
System.out.print(“, “);
}
System.out.print(last);
last=set.headSet(last).last();
first=false;
} while (last != set.first());
System.out.println();
}

26.How can I go through an Iterator mulitple times ?
There is no direct support for this. You’ll need to create your own caching mechanism. For instance, as you go through the Iterator the first time, add the elements to a LinkedList. Then, you can just get an Iterator from the LinkedList for the second pass through.

27.What’s new to the Collections Framework in Java 1.4 ?
There are three new implementations:
          LinkedHashSet
          LinkedHashMap
          IdentityHashMap
         One marker interface: 
         RandomAccess
        And six new utility methods for the Collections class:
        rotate(List list, int distance)
        replaceAll(List list, Object oldVal, Object newVal)
        indexOfSubList(List source, List target)
        lastIndexOfSubList(List source, List target) 
       swap(List list, int i, int j) 
       list(Enumeration e)

28.How can I add an array of objects to a collection ?
First you need to convert the array to a Collection. This can be done with Arrays.asList(objectArray). Once you have the array as a List, you can add it to another Collection with theCollection.addAll(theList).

29.Is Vector’s clone method thread-safe ?
Sure it is, since it is a Vector which is thread-safe.

30.How do I load property settings with the Properties class ?
java.util.Properties objects can load values from a file using the method load(InputStream).
Here is the code you need:

Properties props = new Properties();
props.load(new FileInputStream(“propertyfile.properties”));
String value = props.getProperty(“propertyname”);

//Just a trick: in a web archive (war) you can get the InputStream inside the war archive using
ClassLoader cl = this.getClass().getClassLoader();
InputStream is = cl.getResourceAsStream(“it/package/application.properties”);

This is better than using a FileInputStream, because you are loading the file within the archive as it was a resource. You should use this.getClass().getClassLoader() to use the same ClassLoader as the one used the servlet container to load your JSP/Servlet. This code is snipped from a JSP page inside Tomcat.

31.How do I save properties settings with the Properties class ?
Try this:
Properties prop = new Properties();
FileOutputStream output = new FileOutputStream(“Test.properties”);
prop.store(output,”my testproperties”);
output.flush();
output.close();

You’ll need to catch an IOException.

32.What happens if two threads perform a get of one hashmap at the same time ?
Synchronization needs to be done only when there is a chance of changing the data from different threads simultaneously. In your case, it is simply going to be a read, the synchronization is not required. If you need to remove or modify the values in the hashmap, then you [may] need to synchronize that.

For synchronizing a HashMap, you can use Collections.synchronizedMap(<your hashmap reference>) which will return a synchronized map for you, which is thread-safe.

Remember, synchronization will cause a performance problem. So, it needs to be used carefully, when really required.

33.How can I convert a Collection to an Array then back to a Collection ?
The Collection interface provides a mechanism to turn a Collection into an Array using the methods <T> T[] toArray(T[] a) or Object[] toArray(). The first method will return a Array containing all the elements of the Collection with the array being that of the type provided in the method call. The second method just returns an array being of an Object[] type.

The Arrays class provides the opposite. A way to turn an array into a List using the List<T> asList(Array[] a) method. The List returned is of a fixed length with any attempts to add an element throwing an UnsupportedOperationException.

import java.util.*;

public class G{
public static void main(String[] args){
List<String> sun = new ArrayList<String>();
sun.add(“Feel”);
sun.add(“the”);
sun.add(“power”);
sun.add(“of”);
sun.add(“the”);
sun.add(“Sun”);
String[] s1 = sun.toArray(new String[0]); //Collection to array
for(int i = 0; i < s1.length; ++i){
String contents = s1[i];
System.out.print(contents);
}
System.out.println();
List<String> sun2 = Arrays.asList(s1); //Array back to Collection
for(String s2: sun2){
String s3 = s2; System.out.print(s3);
}
//sun2.add(new String(“Hello”)); // throws UnsupportedOperationException
}
}

34.How can I create a Collection based on another Collection ?
Every concrete implementation provides a constructor, which takes a Collection as an argument. Care must be taken when creating a Collection based another Collection, this is because depending on the target concrete implementation being created, specific rules regarding duplicates may be be enforced. Such as creating a Set based on a List.

The following is a short list of the constructors provided by some of the concrete Classes of the JCF (Java Collections Framework), which enable the creation of a Collection based an another implementation.

ArrayList(Collection<? extends E> c)
LinkedList(Collection<? extends E> c)
Vector(Collection<? extends E> c)
TreeSet(Collection<? extends E> c)

Creating a Collection based on another Collection is quite easy. The hard part is knowing which Collection to use based on performance and other issues.

For example the ArrayList created will contain the same elements in the same order as the first ArrayList created.

List<String> slist = new ArrayList<String>();
slist.add(“g”);
slist.add(“a”);
slist.add(“d”);
slist.add(“a”);
slist.add(“f”);
slist.add(“e”);
slist.add(“c”);
slist.add(“b”);
for(String s : slist){
System.out.print(s + “\t”);
}
System.out.println();
List<String> s2list = new ArrayList<String>(slist);
for(String s : s2list){
System.out.print(s + “\t”);
}

When creating a Set based on an existing List the Set will be void of duplicates.
List<String> slist = new ArrayList<String>();
slist.add(“g”);
slist.add(“a”);
slist.add(“d”);
slist.add(“a”);
slist.add(“f”);
slist.add(“e”);
slist.add(“c”);
slist.add(“b”);
for(String s : slist){
System.out.print(s + “\t”);
}
System.out.println();
Set<String> s2set = new TreeSet<String>(slist);
for(String s : s2set){
System.out.print(s + “\t”);
}

35.How can I define my own Comparable type so that it can be naturally sorted within a List ?
When taking a peek at the Java docs you will notice certain classes implement an interface named Comparable. Take a look at some of the subclasses of Number such as Byte, Integer, Long, Float or some of the classes like String and Date. What the Comparable interface provides is a way for a class to be sorted by it’s natural ordering. So what do we mean by natural ordering? Depending on the type wishing to be sorted the natural ordering can be different things. If we are sorting Strings the ordering is lexicographic or alphabetic if we are sorting Dates the ordering is chronological if we are sorting Integers the ordering is numerical.

Comparable only contains one method that needs to be implemented by the class wishing to be sorted naturally. Remember if you try and sort a list that contains elements that do not implement the Comparable interface then Collections.sort() will throw an exception specifically a ClassCastException.

public interface Comparable<T>{
public int compareTo(T o);
}

The following is a short example on how to implement the Comparable interface and use the compareTo(T o) method.
import java.util.*;

public final class Alpha implements Comparable<Alpha>{
public static void main(String[] args){
List<Alpha> alpha = new ArrayList<Alpha>();
alpha.add(new Alpha(“z”));
alpha.add(new Alpha(“g”));
alpha.add(new Alpha(“k”));
alpha.add(new Alpha(“q”));
alpha.add(new Alpha(“a”));
alpha.add(new Alpha(“b”));
alpha.add(new Alpha(“o”));
alpha.add(new Alpha(“v”));
alpha.add(new Alpha(“c”));
Collections.sort(alpha);
System.out.println(alpha);
}
private String letter;
public Alpha(String letter){
if(letter == null){throw new NullPointerException();}
this.letter = letter;
}
public String toString(){return letter;}
public boolean equals(Alpha a){
if(!(a instanceof Alpha))
return false;
return letter.equals(a.letter);
}
public int compareTo(Alpha a){
int i = letter.compareTo(a.letter);
return i;
}
}

More complex examples might included sorting on multiple fields. Most things that you would have to sort probably have more then one part like a name for instance (First:Middle:Last) or maybe you have to sort in (Brand:Model) order.
import java.util.*;

public final class Car implements Comparable<Car>{
public static void main(String[] args){
Car[] cararry = {new Car(“Toyota”,”Celica”), new Car(“Honda”,”Civic”),
new Car(“Ford”,”Mustang”), new Car(“Lexus”,”ES”), new Car(“Acura”,”Integra”),
new Car(“Honda”,”Accord”), new Car(“Acura”,”RL”), new Car(“Toyota”,”Avalon”)
};
List<Car> car = Arrays.asList(cararry);
Collections.sort(car);
System.out.println(car);
}
private String brand;
private String model;
public Car(String brand, String model){
if(brand == null || model == null){throw new NullPointerException();}
this.brand = brand;
this.model = model;
}
public String toString(){return brand + ” ” + model;}
public boolean equals(Car car){
if(!(car instanceof Car))
return false;
boolean samebrand = brand.equals(car.brand);
return samebrand != true ? samebrand: model.equals(car.model);
}
public int compareTo(Car car){
int i = brand.compareTo(car.brand);
return(i != 0 ? i : model.compareTo(car.model));
}
}

36.What are Generics and how can I use them ?
One of the biggest additions since the creation of the Collections framework is Generics.This long awaited update to the type system is a welcomed feature, which C++ developers have had in their toolbox for years using the STL. A generic type is defined using one or more type variables with it’s contained methods using that type variable as a place holder to mark a parameter or return type. For instance the interface List has now been defined as.

public interface List<E>{
public add(E e);
Iterator<E> iterator();
}
public interface Iterator<E>{
E next();
boolean hasNext();
}

Type Safe Collections

So you might ask. What are Generics and why should I use them? Generics are a way to restrict a data structure to hold only a specific type thus providing compile time type checking. One of the added bonuses is that it is no longer necessary to cast a returned Object to a specific type because the compiler is aware of what type is being held by the Collection and what type is to be returned.

Set s = new SortedSet();
s.add(new String(“Java”));
String j = (String) s.get(0); // cast required;

// java 5
Set<String> s = new SortedSet<String>();
s.addElement(new String(“String Type”));
String s = s.get(0); // no cast required!

Having a type safe system not only obviates the need to cast to a specific type but shields the programmer against miss-casting or casting to an unrelated type at runtime.

String s = “Java, write once run anywhere”
List l = new ArrayList();
l.add(new String(“Java”));
Integer i = (Integer)l.get(0); // Runtime exception! ClassCastException!

// Using Generics the compiler catches
String s = “Java. Write once run anywhere!”
List<String> l = new ArrayList<String>();
l.add(new String(“Java”));
Integer i = l.get(0);

Generics and Subtyping

Generics do not share some of the things that are commonly held true in the Java language and one of them is subtyping. One would assume the following perfectly legal since it is true that Object is a supertype of String. But the following is in fact illegal and will cause a compile time error.

List<Object> l = new ArrayList<String>();

As a rule. If X is a superclass or superinterface of Y and E is a generic type declaration then it not the case that E<X> is a supertype of E<Y>. So if E<Object> is not a super type of E<String> then what is the super type of E<String>? Read on and find out!

Wild Cards

Wild Cards represent what is called “the unknown type”. Essentially they can be thought of as the supertype of any Collection. Wildcards allow some flexibility in certain situations where it is needed that a type be abstracted out. For instance what if we define the following method, printSet(Collection<Object> x). We just saw in the previous example that E<Object> is not the super type of E<String> or any other type for that matter. In this case we can change the printSet’s parameter to Collection<?>. This allows us to pass in E<X> where X is any type.

public void printElements(Collection<?> c){
for(Object o: c){
System.out.println(o);
}
}

When working with wildcards it is always legal to read and assign the contents to an Object type

List<String> l = new ArrayList<String>();
l.add(new String(“Java”));
Object o = getElement(l, 0); // legal

public Object getElement(List<?> l, int index){
Object o = null;
try{
o = l.get(0);
}catch(IndexOutOfBoundsException e){
//…….
}
return o;
}

assigning values is another matter. The add() method takes an argument of type E which is the type that the Collection is to hold. Any type wishing to be added to the Collection would have to be of the same type. Since<?> represents an unknown type it is impossible to determine what the type parameter of the collection represents.

Bounded Wildcards

A Bounded Wildcard allows as type to be constrained. Bounded Wildcards are useful when there is some type of partial knowledge about the type arguments. While it is still illegal to try and add an element to a unknown Collection with a bounded type they come in handy in other situations. One use is to be able to pass not only types into a method but sub-types also. In doing this we are able to implement polymorphic behavior.

import java.util.*;

class Printer{
public void print(String s){
for(int i = 0; i < s.length(); i++){
System.out.print(s.charAt(i));
}
}
}
class ReversePrinter extends Printer{
public void print(String s){
for(int i = s.length() – 1 ; i >= 0; i–){
System.out.print(s.charAt(i));
}
}
}
public class G{
public static void main(String[] args){
String s = “Nothing like a good cup of Java in the morning!”
List<Printer> l = new ArrayList<Printer>();
l.add(new Printer());
printElements(l,s);
List<ReversePrinter> rl = new ArrayList<ReversePrinter>();
rl.add(new ReversePrinter());
printElements(rl,s);
}
public static void printElements(List<? extends Printer> l, String s){
Printer printer = l.get(0);
printer.print(s);
System.out.println();
}
}

37.How can I shuffle the elements of a Collection ?
The Collections class which can be found within the java.util namespace provides two methods which suffle the elements of a Collection.

static void shuffle(List<?> list)
static void shuffle(List<?> list, Random rnd)

The first method shuffles the elements according to a default source of randomness, with the second using a specified source of randomness.
import java.util.*;

public class ShuffleTest{
public static void main(String[] args){
List<String> sl = new ArrayList<String>();
sl.add(“One”);
sl.add(“Two”);
sl.add(“Three”);
sl.add(“Four”);
sl.add(“Five”);
sl.add(“Six”);
for(String s: sl){
System.out.println(s);
}
System.out.println();
Collections.shuffle(sl);
for(String s: sl){
System.out.println(s);
}
}
}

38.How can i tell if two Collections contain the same elements or have no elements in common ?
Two methods are needed in this case.

boolean containsAll(Collection<?> c)
boolean disjoint(Collection<?>c1 Collection<?>c2)

Since containsAll(Collection<?> c) is defined within the Collection interface all concrete implementations will be able to use this method. disjoint(Collection<?>c1 Collection<?>c2) is defined within the Collections class.

Using both of these methods is pretty straightforward. containsAll(Collection<?> c) is an instance method so naturally it must be invoked on an object. disjoint(Collection<?>c1 Collection<?>c2) is defined as Static within the Collections class so all that is needed is to invoke it using the class name ie Collections.disjoint(Collection<?>c1 Collection<?>c2)

39.How can I traverse a List backwards ?
In order to traverse a List backwards a ListIterator must be used. The List interface provides a method, which returns a ListIterator.

ListIterator<E> listIterator()

Using a returned ListIterator, concrete implementations of List can be traverse backwards using the following methods.

boolean hasPrevious()
E previous()

Since ListIterator extends the Iterator interface forward direction is still possible via Iterators methods.
boolean hasNext()
E next()

import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;

public class {
public static void main(String[] args){
List<String> slist = new ArrayList<String>();
slist.add(“1”);
slist.add(“2”);
slist.add(“3”);
slist.add(“4”);
ListIterator i = slist.listIterator();
while(i.hasNext()){
System.out.print(i.next());
}
System.out.println();
while(i.hasPrevious()){
System.out.print(i.previous());
}
}
}

40.How can I get a sorted list of keys that are contained within a Map ?
The Map interface defines a method named keySet() which concrete classes such as HashMap and TreeMap implement. Depending on the implementation on which keySet() is invoked the returned Set might not contain it’s elements (keys) in sorted order. For instance the HashMap class makes no guarantees as to the order of the elements contained within. Whereas the TreeMap class does guarantee element ordering since it implements the SortedMap interface.

/* TreeMap used. Keys stored in ascending order */

Map<String,String> book = new TreeMap<String,String>();
book.put(new String(“Java”),new String(“A trademark used for a programming language designed to develop applications, especially ones for the Internet, that can operate on different platforms.”));
book.put(new String(“C#”),new String(“An object-oriented language devised and promoted by Microsoft, intended to replace Java, which it strongly resembles.”));
book.put(new String(“Python”),new String(“A simple, high-level interpreted language by Guido van Rossum”));
book.put(new String(“LISP”),new String(“A programming language designed to process data consisting of lists. It is widely used in artificial intelligence research.”));
Set words = book.keySet();
for(Iterator i = words.iterator();i.hasNext();){
System.out.print(i.next() + “\t”);
}

41.How can I create a read only Collection ?
Unmodifiable Collections can be easily created using various static methods which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException.

Collection<T> unmodifiableCollection(Collection<? extends T> c)
List<T> unmodifiableList(List<? extends T> list)
Set<T> unmodifiableSet(Set<? extends T> s)
SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)

import java.util.*;

public class Unmod{
public static void main(String[] args){
List<String> strlist = new ArrayList<String>();
strlist.add(“C”);
strlist.add(“B”);
strlist.add(“A”);
Collection<String> unmodstrlist = Unmod.makeUnmodifiable(strlist);
// unmodstrlist.add(“G”); throws UnsupportedOperationException
Set<String> strset = new TreeSet<String>();
strset.add(“C”);
strset.add(“B”);
strset.add(“A”);
Collection<String> unmodstrset = Unmod.makeUnmodifiable(strset);
// unmodstrset.add(“G”); throws UnsupportedOperationException
}
public static Collection<String> makeUnmodifiable(Collection<String> c){
return(Collections.unmodifiableCollection(c));
}
}

42.Is there a way determine how many times an Object occurs within a Collection ?
The Collections class provides a method which returns the number of times an Object appears within a given Collection.

public static int frequency(Collection<?> c, Object o)

If a null Collection is passed in then a NullPointerException is thrown.
import java.util.*;

public class Freq {
public static void main(String[] args){
List<Integer> password = new ArrayList<Integer>();
password.add(new Integer(4));
password.add(new Integer(6));
password.add(new Integer(8));
password.add(new Integer(4));
password.add(new Integer(9));
Integer passwordelement = new Integer(4);
System.out.println(passwordelement + ” appears “
+ getFrequency(password,passwordelement) + ” times within password”);
}
private static int getFrequency(Collection c, Object o){
return(Collections.frequency(c,o));
}
}

43.What is the easiest way to obtain a Map Entry ?
The easiest way to obtain a Map Entry or (key-value pair) is by invoking the following method provided by the Map interface.

Set<Map.Entry<K,V>> entrySet();

The entrySet() method returns a Set which is populated with Map.Entry objects. The only way to obtain a reference to a Map.Entry is by using an Iterator on the returned Set view. Once a reference to a Map.Entry is obtained the follow methods can be invoked which return the key and value corresponding to the entry.

K getKey()
V getValue()

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Iterator;

public class Emps{
public static void main(String[] args){
Map<String,String> empmap = new TreeMap<String,String>();
empmap.put(“956544″,”Bob Jones”);
empmap.put(“132485″,”Phil Harris”);
empmap.put(“102161″,”Kamal Uganda”);
empmap.put(“226545″,”Bill Russel”);
empmap.put(“116423″,”Dorris Smith”);
Set s = empmap.entrySet();
for(Iterator i = s.iterator();i.hasNext();){
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey() + ” : ” + me.getValue());
}
}
}

44.How can I find the maximum element contained within a Collection ?
Finding the maximum element within a Collection is easy. The following method can be used which can be found within the Collections class.

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)

This method returns the maximum element of the given Collection according to the natural ordering of it’s elements. This means that all elements must implement the Comparable interface. With the following code below the implementation of the Comparable interface is already taken care of since the class Byte already implements this interface.
import java.util.Set;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class Max{
public static void main(String[] args){
Collection<Byte> numl = new ArrayList<Byte>();
numl.add(new Byte(“2”));
numl.add(new Byte(“6”));
numl.add(new Byte(“3”));
numl.add(new Byte(“1”));
numl.add(new Byte(“5”));
numl.add(new Byte(“4”));
System.out.print(“Max element is ” + getMax(numl));
}
public static Byte getMax(Collection<Byte> c){
return Collections.max(c);
}
}

If the element type being store within the Collection is user defined, implementation of the Comparable interface must be provided.

import java.util.Set;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class Max{
public static void main(String[] args){
Collection<Num> numl = new ArrayList<Num>();
numl.add(new Num(“2”));
numl.add(new Num(“6”));
numl.add(new Num(“3”));
numl.add(new Num(“1”));
numl.add(new Num(“5”));
numl.add(new Num(“4”));
System.out.print(“Max element is ” + getMax(numl).getNum());
}
public static Num getMax(Collection<Num> c){
return Collections.max(c);
}
}
class Num implements Comparable<Num>{
private String i;
public Num(String i){
this.i = i;
}
public int compareTo(Num num){
int x = i.compareTo(num.i);
return x;
}
public String getNum(){
return i;
}
}

45.How can I create an immutable List consisting of n Copies of an Object ?
nCopies(int n, T o) can be used to create an immutable List which contains a specific number of copies of an Object. Care must be taken when trying to add elements to or extract elements from the returned List. Both attempts will throw UnsupportedOperationExceptions.

public static <T> List<T> nCopies(int n, T o)

import java.util.List;
import java.util.Collections;

public class NCopiesTest{
public static void main(String[] args){
List<String> slist = Collections.nCopies(5, “Java Blend”); //immutable list!
slist.add(“Moca Blend”); // throws UnsupportedOperationException!
String selement = slist.remove(0); // throws UnsupportedOperationException!
}
}

46.What is the difference between a Stack and a Queue ?
First things first. Where can Stacks and Queue’s be found? Java provides a Stack class, which can be found within the java.util namespace. Within the same namespace you will find a Queue interface. All concrete Queue implementations can be located within the java.util.concurrent package.

What is a Stack?

Java’s Stack class extends the Vector class. A Stack represents a Collection of objects that are in LIFO (Last In First Out Order). The Stack class provides operations that allow testing for zero elements, inspection of it’s top most element, removal of it’s top most element, and the addition of elements.

boolean empty() Tests if this stack is empty.
E peek() Looks at the object at the top of this stack without removing it from the stack.
E pop() Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item) Pushes an item onto the top of this stack.
int search(Object o) Returns the 1-based position where an object is on this stack.

What is a Queue?

A Queue is also a Collection of Objects similar to a Stack. Queues typically order the elements contained within in FIFO order but this is not always the case. Elements that are inserted into a Queue are inserted at the tail end as opposed to a Stack where the elements are pushed into it at the head. Looking at the Queue interface the operations are similar to what a Stack provides.

E element() Retrieves, but does not remove, the head of this queue.
boolean offer(E o) Inserts the specified element into this queue, if possible.
E peek() Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
E poll() Retrieves and removes the head of this queue, or null if this queue is empty.
E remove() Retrieves and removes the head of this queue.

So what are the differences between Queues and Stacks?

Besides how each order their elements there really isn’t much difference. Both provided pretty much the same operations. The big difference is that one is a concrete implementation (Stack) while the other is an interface (Queue) thus implying that additional functionality is provided by the concrete classes that implement the Queue interface such as blocking, and synchronization.

47.How can I insert an element into a List ?
In order to insert an element into a List add(int index, E element) must be used since the List interface does not provide an insert method. If the index is out of rage ie. index < 0 || index > size() an exception will be thrown.

import java.util.*;

public class Insert{
public static void main(String[] args){
List<String> slist = new ArrayList<String>();
slist.add(new String(“Java”));
slist.add(new String(“Write”));
slist.add(new String(“run”));
slist.add(new String(“anywhere!”));
slist.add(2,new String(“once”));
for(String s:slist){
System.out.println(s);
}
}
}

48.How do I make a copy of an array ?
The clone() in Clonable interface allows to make a copy of the array. In the previous case i.e. arraycopy() we must mention the source array,the source offset(starting position),the destination array,the destination offset(Starting position),and the final one is the number of elements to be copied.This method is useful when you copy a part of the array to a new one. But when we need to copy a whole array to another,then we need not mention all the arguments and have a tough time instead we go for clone() method.In case of the clone() we need to mention the source array and destination array. eg: Array a2=a1.clone(); here the elements of the Array a1 is copied to the Array a2.If we add new elements in Array a1 it will not be reflected in a2.For doing so we need to use the Object refrences.

49.What is the purpose of the CopyOnWriteArrayList and CopyOnWriteArraySet collections ?
Synchronized operations are costly and if you aren’t modifying a collection much, it is best not to synchronize all collection accesses. The CopyOnWriteXXX collections avoid concurrent modification issues during traversal by traversing through the original collection and the modifications happening in a copy of the original store. Think of CopyOnWriteArrayList as a thread-safe version of ArrayList without the syncrhonized access limitations. CopyOnWriteArraySet acts as like a Set, backed by a CopyOnWriteArrayList.

50.What implementations of the Deque interface does Java offer ?
ArrayDeque offers an array backed deque. LinkedList offers a linked list version. LinkedBlockingDeque offers an optionally bounded blocking version.

51.Why do I keep getting an UnsupportedOperationException thrown when I try some collection operations ?
Several methods of the collection interfaces are considered optional. If an unsupported operation is called, that is when you’ll see the UnsupportedOperationException thrown. The javadoc for a collection implementation should document which methods are optional.

53.Is it better to use a for-each loop or an Iterator with a collection ?
It depends on what you need to do. The remove() method of an Iterator is the safe way to remove elements from an underlying collection. You can’t safely remove elements with a for-each loop. For just “visiting” each element, either way works.

54.How can I detect if a duplicate is added to a Set ?
The add() method returns a boolean. If the set did not previously contain the element, true is returned. If the set previoulsy did contain the element, false is returned. Of course, you can also check with the contains() method to see if the element is contained in the Set first.

55.What is a multimap ?
A multimap is a map where a single key can map to multiple values.(And a value can be associated with multiple keys.)

54.How do I create a multimap in Java ?
Typically a Map maps a key to a single value. To have a multimap, the values of a Map should be a List instead. Thus there can be multiple values in the List associated with a single key.

56.What is the natural ordering of a Boolean? Does FALSE come first or second ?
Boolean.FALSE < Boolean.TRUE

57.What does Class<String> mean ?
Class<String> is the generics way of writing String.class. It allows you to improve type safety.

58.What type of data structure would you use to store java objects (Element) with the following requirements ?
I.
Created/loaded only once
Elements are frequently read by multiple threads
No updates (add/remove) to the data structure are required once loaded
Order is not important
Random object access is required by a unique key search.

Answer: HashMap

II.
Created once
Elements are added / removed in a multi threaded environment
Elements are frequently read in a multi threaded environment
Order is not important
Random object access is required by a unique key search.

Answer: HashTable is synchronized
III.
Created/loaded only once
Elements are frequently read in a multi threaded environment
Elements are added / removed in a multi threaded environment
Elements are frequently read in a multi threaded environment
Order is important
Random object access is require based on an index
Duplicate objects allowed

Answer: Vector is synchronized

IV.

Created once
Order is important
Random object access is require based on an index
Elements are frequently read in a multi threaded environment

Answer: ArrayList

Collections Drill – I

1.How to find the maximum size of heap used in the memory in java ?
maxMemory
(): Returns the maximum amount of memory that the Java virtual machine will attempt to use
totalMemory(): Returns the total amount of memory in the Java virtual machine.
Also you can use -Xmx parameter to set the max heap size.

2.What is the difference between marshalling and unmarshalling ?
marshling is convert from byte code to network understand able format
unmarshsling is converting from network understand able fromat to byte code convertion.

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

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

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

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

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

8.What is the GregorianCalendar class ?
The GregorianCalendar provides support for traditional Western calendars

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

10.What is the SimpleTimeZone class ?
The SimpleTimeZone class provides support for a Gregorian calendar .

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

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

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

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

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

16.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?
The existing object will be overwritten and thus it will be lost.

17.What is the difference between the size and capacity of a Vector?
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.

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

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

20.What is an enumeration ?
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.

21.Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList ?
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.

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

23.How do I use an Iterator to go through a Collection ?
Collection collection = …;
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Object element = iterator.next();
// Do something with element
}
}

24.How do I use a ListIterator to go through a List backwards ?
List list = …;
ListIterator iterator = list.listIterator(list.size());
while (iterator.hasPrevious()) {
Object element = iterator.previous();
// Process element
}

25.How do I count the frequency of some word/object ?
The Map interface can be used to count the number of times a word/object appears. The following program demonstrates counting word frequency from the command line:

import java.util.*;

public class MapExample {
public static void main(String args[]) {
Map map = new HashMap();
Integer ONE = new Integer(1);
for (int i=0, n=args.length; i<n; i++) {
String key = args[i];
Integer frequency = (Integer)map.get(key);
if (frequency == null) {
frequency = ONE;
} else {
int value = frequency.intValue();
frequency = new Integer(value + 1);
}
map.put(key, frequency);
}
System.out.println(map);
Map sortedMap = new TreeMap(map);
System.out.println(sortedMap);
}
}

26. How do I sort objects into their reverse natural ordering ?
The Collections.reverseOrder() method returns a Comparator that sorts objects that implement the Comparable interface in reverse order.

27.How do I use Enumeration to iterate through a collection ?
Enumeration enum = …;
while (enum.hasMoreElements()) {
Object element = iterator.nextElement();
// process element
}

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

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

Integer in = new Integer(5);

30.How do I create linked lists if there are no pointers ?
No pointers does not mean no reference variables. You just can’t deference them as you can in C/C++ or perform pointer arithmetic. You can still use abstract data types that require dynamic data structures. See the LinkedList class for an example of a linked list implementation.

31.How do I use an array with the Collections Framework ?
The Arrays.asList() method provides a fixed-length List view of an array, where changes to the List are stored in the original array. The Arrays class also provides additional support methods for sorting and searching an array.

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

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

Basically:

ResultSet result = stmt.executeQuery(“…”);
List list = new LinkedList();
while(result.next()) {
list.add(result.getString(“col”));
}

If there are multiple columns in the result set, you’ll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

34.Why doesn’t the Iterator interface extend the Enumeration interface ?
If the Iterator interface extended the Enumeration interface, the Iterator interface would end up with five methods where two methods just called other methods in the interface. The designers of the framework wanted to get rid of the cumbersome Enumeration method names so had the Iterator interface stand on its own with new shorter method names.

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

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

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

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

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

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

40.How do I get the list of system properties that tell me things like which version of Java a user is running and their platform-specific line separator ?
The System.getProperties() method will return the standard property set. However, in untrusted applets, you can only ask for specific properties, as in System.getProperty(“java.version”).

41.How do I sort an array ?
The Arrays class in java.util provides a series of sort() methods for sorting arrays. If the array is an array of primitives or an array of a class that implements Comparable then you can just call the method directly:

Arrays.sort(theArray);

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

Arrays.sort(theArray, theComparator);

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

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

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

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

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

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

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

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

Otherwise, create your own class with its own signatures, and keep the Collection strictly private. This is best done if you are designing a class for others to use.

44.How does a Hashtable internally maintain the key-value pairs ?
The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

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

Map map = some hash map
Set set = map.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

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

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

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

48.Which collections in Java are synchronized and which aren’t ?
The original collection classes in Java are all synchronized: Vector and Hashtable, along with their subclasses Stack and Properties. Those classes introduced with the Java 2 Collections Framework are all NOT synchronized by default, the sets, lists, and maps

49.What are the differences between ArrayList and LinkedList ?
An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the number of elements in the collection increases, the internal array grows to fit them. If there are lots of growth periods, performance degrades as the old array needs to be copied into the new array. However, random access is very quick as it uses an array index to access.
With a LinkedList, the List implementation is backed by a doubly linked list data structure, allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the access must start at an end to get to the specific position.

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

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

import java.io.*;
import java.util.*;

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

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

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

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

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

String args[] = {“1”, “2”, “3”};
Vector v = new Vector();
v.addElement(args);

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

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

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

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

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

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

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

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

Having created this iterator, we could now set up a loop like:
while(iter1.hasNext()){
String str = iter1.next();
// do something with str
}

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

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

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

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

58.What is the function of a load factor in a Hashtable ?
The load factor determines how full a hashtable may get before it expands its capacity. I think that the comments on the Hashtable API docs explain it very well:
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method.

Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).

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

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

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

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

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

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

MQ Series – Drill One

 

What is MQSeries.

MQSeries is a software family developed by IBM and its components are used to enable different applications running on different operating systems to exchange data using messages and queues. MQSeries is also known as business integration software or business integration framework because of its ability to tie different types of applications together.

The MQSeries family of software also includes a standard library of functions known as the Message Queue Interface (MQI). The MQI is identical on different platforms and operating systems allowing straightforward and easy implementation. The MQI takes care of the communication layer and operating environment specifics allowing developers to concentrate on the applications business logic.

What is MQI

The Message Queue Interface (MQI) is the common API for MQSeries. It contains calls and messages that are language independent.

What is QUEUE

A queue is a data structure that stores messages. Applications send messages to, and receive messages from, a queue. Multiple applications can send information to the same queue.

Each queue has a name, similar to a TCP port.

Every queue belongs to a Queue Manager. The Queue Manager organizes the messages and places them in the appropriate queue. Each system can have multiple queue managers.

Queue managers talk to other queue managers through channels.

What is Channel.

A channel serves as a communication path that enables queue managers to transmit messages between each other. There are various types of transport protocols that can be used with channels, the most common being TCP/IP.

Explain IBM MQ Series.

MQSeries  is  IBM¢s  award-winning  middleware  for  commercial  messaging and  queuing.    It  runs  on  a  variety  of  platforms.   The  MQSeries  products enable  programs  to  communicate  with  each  other  across  a  network  of unlike  components,  such  as  processors,  subsystems,  operating  systems  and communication  protocols.    MQSeries  programs  use  a  consistent  application program  interface  (API)  across  all  platforms.

Programs use  MQSeries  API  calls,  that  is  the  message  queue  interface  (MQI),  to communicate  with  a  queue  manager  (MQM),  the  run-time  program  of MQSeries.    For  the  queue  manager  to  do  its  work,  it  refers  to  objects,  such as  queues  and  channels.    The  queue  manager  itself  is  an  object  as  well.

What Is Messaging and Queuing?

Messaging means  that  programs  communicate  with  each  other  by  sending data  in  messages  and  not  by  calling  each  other  directly. Queuing means  that  programs  communicate  through  queues.    Programs communicating  through  queues  need  not  be  executed  concurrently. With  asynchronous  messaging,  the  sending  program  proceeds  with  its  own processing  without  waiting  for  a  reply  to  its  message.    In  contrast, synchronous  messaging  waits  for  the  reply  before  it  resumes  processing.

MQSeries  is  used  in  a  client/server  or  distributed  environment.    Programs belonging  to  an  application  can  run  in  one  workstation  or  in  different machines  on  different  platforms.

What is a Queue  Manager?

 The  heart  of  MQSeries  is  its  run-time  program,  the queue  manager  (MQM). Its  job  is  to  manage  queues  of  messages.    Application  programs  invoke functions  of  the  queue  manager  by  issuing  API  calls.    For  example,  the MQPUT  API  puts  a  message  on  a  queue  to  be  read  by  another  program using  the  MQGET  API.   This  scenario  is  shown  in  Figure   31  on  page   54. A  program  may  send  messages  to  another  program  that  runs  in  the  same machine  as  the  queue  manager,  or  to  a  program  that  runs  in  a  remote system,  such  as  a  server  or  a  host.    The  remote  system  has  its  own  queue manager  with  its  own  queues. Application  programmers  do  not  need  to  know  where  the  program  runs  they send  messages  to.    They  put  their  message  on  a  queue  and  let  the  queue manager  worry  about  the  destination  machine  and  how  to  get  it  there. For  the  queue  manager  to  do  its  work,  it  refers  to  objects  that  are  defined  by an  administrator,  usually  when  the  queue  manager  is  created  or  when  a new  application  is  added.    The  objects  are  described  in  the  next  section. The  functions  of  a  queue  manager  can  be  defined  as  follows: · It  manages  queues  of  messages  for  application  programs. · It  provides  an  application  programming  interface,  the  Message  Queue Interface  (MQI).

read more @ http://www.redbooks.ibm.com/redbooks/SG244896.html

JMS Drill One

What is JMS?

Java Message Service: An interface implemented by most J2EE containers to provide point-to-point queueing and topic (publish/subscribe) behavior. JMS is frequently used by EJB’s that need to start another process asynchronously.
For example, instead of sending an email directly from an Enterprise JavaBean, the bean may choose to put the message onto a JMS queue to be handled by a Message-Driven Bean (another type of EJB) or another system in the enterprise. This technique allows the EJB to return to handling requests immediately instead of waiting for a potentially lengthy process to complete.

What are the advantages of JMS?

You can use it in the context of mutithreading but it means JMS is not meant for Multithreading. Its basically meant for object communication.
It will be useful when you are writing some event based applications like Chat Server which needs a publish kind of event mechanism to send messages between the server to the clients who got connected with the server.
Moreover JMS gives Loosely-coupled kind of mechanism when compared with RMI which is tightly-coupled. In JMS there is no need for the destination object to be available online while sending a message from the client to the server. But in RMI it is necessary. So we can use JMS in place of RMI where we need to have loosely-coupled mechanism.

What are major JMS products available in the market?

IBM’s MQ Series, SonicMQ, iBus etc.
All the J2EE compliant application servers come built with thier own implementation of JMS. 

What are the different types of messages available in the JMS API?

Message, TextMessage, BytesMessage, StreamMessage, ObjectMessage, MapMessage are the different messages available in the JMS API. 

What is the difference between Point to Point and Publish/Subscribe Messaging Domains

A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire
In a publish/subscribe (pub/sub) product or application, clients address messages to a topic. Publishers and subscribers are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic’s multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.

What is the diffrence between JAVA Mail and JMS Queue

Java Mail – API siting on top of e-mail protocols like SMTP, POP, IMAP – essentially same stuff e-mail clients like MS outlook use .. hence make sense if at least on one side of conversation we have human.
JMS Queue – is asynchronous point-to-point communication between systems

What is the difference between ic and queue?

A ic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging.

What is the role of JMS in enterprise solution development?

JMS is typically used in the following scenarios
1. Enterprise Application Integration: – Where a legacy application is integrated with a new application via messaging.
2. B2B or Business to Business: – Businesses can interact with each other via messaging because JMS allows organizations to cooperate without tightly coupling their business systems.
3. Geographically dispersed units: – JMS can ensure safe exchange of data amongst the geographically dispersed units of an organization.
4. One to many applications: – The applications that need to push data in packet to huge number of clients in a one-to-many fashion are good candidates for the use JMS. Typical such applications are Auction Sites, Stock Quote Services etc.

What is the use of Message object?

Message is a light weight message having only header and properties and no payload. Thus if the receivers are to be notified about an event, and no data needs to be exchanged then using Message can be very efficient.

What are the three components of a Message ?

A JMS message consists of three parts:
Message header
For message identification. For example, the header is used to determine if a given message is appropriate for a “subscriber”
Properties
For application-specific, provider-specific, and optional header fields
Body
Holds the content of the message. Several formats are supported, including TextMessage, which wrap a simple String, that wrap arbitrary Java objects (which must be serializable). Other formats are supported as well.

What kind of information found in the header of a Message ?

The header of a message contains message identification and routing information. This includes , but is not limited to :
JMSDestination
JMSDeliveryMode
JMSMessageID
JMSTimeStamp
JMSExpiration
JMSReplyTO
JMSCorrelationID
JMSType
JMSRedelivered

What is the basic difference between Publish Subscribe model and P2P model?

Publish Subscribe model is typically used in one-to-many situation. It is unreliable but very fast. P2P model is used in one-to-one situation. It is highly reliable.

 

What is the use of BytesMessage?

BytesMessage contains an array of primitive bytes in it’s payload. Thus it can be used for transfer of data between two applications in their native format which may not be compatible with other Message types. It is also useful where JMS is used purely as a transport between two systems and the message payload is opaque to the JMS client. Whenever you store any primitive type, it is converted into it’s byte representation and then stored in the payload. There is no boundary line between the different data types stored. Thus you can even read a long as short. This would result in erroneous data and hence it is advisable that the payload be read in the same order and using the same type in which it was created by the sender.

What is the use of StreamMessage?

StreamMessage carries a stream of Java primitive types as it’s payload. It contains some conveient methods for reading the data stored in the payload. However StreamMessage prevents reading a long value as short, something that is allwed in case of BytesMessage. This is so because the StreamMessage also writes the type information alonwgith the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another. 

What is the use of TextMessage?

TextMessage contains instance of java.lang.String as it’s payload. Thus it is very useful for exchanging textual data. It can also be used for exchanging complex character data such as an XML document.

What is the use of ObjectMessage?

ObjectMessage contains a Serializable java object as it’s payload. Thus it allows exchange of Java objects between applications. This in itself mandates that both the applications be Java applications. The consumer of the message must typecast the object received to it’s appropriate type. Thus the consumer should before hand know the actual type of the object sent by the sender. Wrong type casting would result in ClassCastException. Moreover the class definition of the object set in the payload should be available on both the machine, the sender as well as the consumer. If the class definition is not available in the consumer machine, an attempt to type cast would result in ClassNotFoundException. Some of the MOMs might support dynamic loading of the desired class over the network, but the JMS specification does not mandate this behavior and would be a value added service if provided by your vendor. And relying on any such vendor specific functionality would hamper the portability of your application. Most of the time the class need to be put in the classpath of both, the sender and the consumer, manually by the developer.

What is the use of MapMessage?

A MapMessage carries name-value pair as it’s payload. Thus it’s payload is similar to the java.util.Properties object of Java. The values can be Java primitives or their wrappers.

What is the difference between BytesMessage and StreamMessage?

BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.

What is point-to-point messaging?

With point-to-point message passing the sending application/client establishes a named message queue in the JMS broker/server and sends messages to this queue. The receiving client registers with the broker to receive messages posted to this queue. There is a one-to-one relationship between the sending and receiving clients. 

Can two different JMS services talk to each other? For instance, if A and B are two different JMS providers, can Provider A send messages directly to Provider B? If not, then can a subscriber to Provider A act as a publisher to Provider B?

The answers are no to the first question and yes to the second. The JMS specification does not require that one JMS provider be able to send messages directly to another provider. However, the specification does require that a JMS client must be able to accept a message created by a different JMS provider, so a message received by a subscriber to Provider A can then be published to Provider B. One caveat is that the publisher to Provider B is not required to handle a JMSReplyTo header that refers to a destination that is specific to Provider A. 

What is the advantage of persistent message delivery compared to nonpersistent delivery?

If the JMS server experiences a failure, for example, a power outage, any message that it is holding in primary storage potentially could be lost. With persistent storage, the JMS server logs every message to secondary storage. (The logging occurs on the front end, that is, as part of handling the send operation from the message producing client.) The logged message is removed from secondary storage only after it has been successfully delivered to all consuming clients .   

Give an example of using the publish/subscribe model.

JMS can be used to broadcast shutdown messages to clients connected to the Weblogic server on a module wise basis. If an application has six modules, each module behaves like a subscriber to a named ic on the server. 

Why doesn’t the JMS API provide end-to-end synchronous message delivery and notification of delivery?

Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API.
JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can ensure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer.
The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.

What are the various message types supported by JMS?

Stream Messages — Group of Java Primitives
Map Messages — Name Value Pairs. Name being a string& Value being a java primitive
Text Messages — String messages (since being widely used a separate messaging Type has been supported)
Object Messages — Group of serialize able java object
Bytes Message — Stream of uninterrupted bytes 

How is a java object message delivered to a non-java Client?

It is according to the specification that the message sent should be received in the same format. A non-java client cannot receive a message in the form of java object. The provider in between handles the conversion of the data type and the message is transferred to the other end. 

What is MDB and What is the special feature of that?

MDB is Message driven bean, which very much resembles the Stateless session bean. The incoming and out going messages can be handled by the Message driven bean. The ability to communicate asynchronously is the special feature about the Message driven bean.

What are the types of messaging?

There are two kinds of Messaging.
Synchronous Messaging: Synchronous messaging involves a client that waits for the server to respond to a message.
Asynchronous Messaging: Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server. 

What are the core JMS-related objects required for each JMS-enabled application?

Each JMS-enabled client must establish the following:
• A connection object provided by the JMS server (the message broker)
• Within a connection, one or more sessions, which provide a context for message sending and receiving
• Within a session, either a queue or ic object representing the destination (the message staging area) within the message broker
• Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively)
Within a session, a message object (to send or to receive)

ANT drill – One

 

What is ant?

Ant is a small animal who can build magnificent buildings. Ant builds!
ANT is a Java based building tool, which is similar to make, and so much better than make.
ANT, what a smart name for a building tool, even the original author of ANT, James Duncan Davidson, meant “Another Neat Tool”.

A win-win ant learning method

There is a shortcut.
If you download a small jakarta project, such as Log4J, which is built by ant. It is a good and simple example for you to learn ant. Actually, you hit two birds with one stone.
Ant is easy!
The hard part is how to make a very complicated diversified system work very simple and elegant. Knowledge about ant is not enough, you need an elegant and simple design, you need great naming convention, you need to optimize the code reusability and flexibility, you need a least maintenance system…
Then it is not easy now ..

How do I get started to use ant? Can you give me a “Hello World” ant script?

Simple.
    * Download the most recent version of ant from Apache; unzip it some where on your machine.
    * Install j2sdk 1.4 or above.
    * Set JAVA_HOME and ANT_HOME to the directory your installed them respectively.
    * Put %JAVA_HOME%/bin;%ANT_HOME%/bin on your Path. Use ${JAVA_HOME}/bin:${ANT_HOME}/bin on UNIX. Yes, you can use forward slash on windows.
    * Write a “Hello world” build.xml
                  <project name=”hello” default=”say.hello” basedir=”.” >
                    <property name=”hello.msg” value=”Hello, World!” />
                    <target name=”say.hello” >
                      <echo>${hello.msg}</echo>
                    </target>
                  </project>
    * Type ant in the directory your build.xml located.
    * You are ready to go!!!!

How to delete files from a directory if it exists? The following code fails when directory does not exist!
<delete quiet=”true” dir=”${classes.dir}” includes=”*.class”/>

Your code has many problems.
   1. You should not use implicit fileset, which is deprecated. You should use nested fileset.
   2. If dir does not exist, the build will fail, period!
   3. If you are not sure, use a upper level dir, which exists for sure. See the following fileset.
  <delete>
    <fileset dir=”${upperdir.which.exists}”>
      <include name=”${classes.dir}/*.class” />
    </fileset>
  </delete>

How do I set classpath in ant?

Here is some snippet of code
  <path id=”build.classpath”>
    <fileset dir=”${build.lib}” includes=”**/*.jar”/>
    <fileset dir=”${build.classes}” />
  </path>
  <target….>
    <javac ….>
      <classpath refid=”build.classpath” />
    </java>
  </target>
  <target….>
    <java ….>
      <classpath refid=”build.classpath” />
    </java>
  </target>

How does ant read properties? How to set my property system?

Ant sets properties by order, when something is set, the later same properties cannot overwrite the previous ones. This is opposite to your Java setters.
This give us a good leverage of preset all properties in one place, and overwrite only the needed. Give you an example here. You need password for a task, but don’t want to share it with your team members, or not the developers outside your team.
Store your password in your ${user.home}/prj.properties
pswd=yourrealpassword
In your include directory master prj.properties
pswd=password
In your build-common.xml read properties files in this order
   1. The commandline will prevail, if you use it: ant -Dpswd=newpassword
   2. ${user.home}/prj.properties (personal)
   3. yourprojectdir/prj.properties (project team wise)
   4. your_master_include_directory/prj.properties (universal)
<cvsnttask password=”${pswd} … />
Problem solved!

How to modify properties in ant?

No, you can’t!
Properties in Ant are immutable. There is a good reason behind this, see this FAQ item for more details.
Q. How to use ant-contrib tasks?
A: Simple, just copy ant-contrib.jar to your ant*/lib directory
And add this line into your ant script, all ant-contrib tasks are now available to you!
    <taskdef resource=”net/sf/antcontrib/antcontrib.properties” />

How to loop on a list or fileset?

Use ant-contrib <for> <foreach> tasks
General to say, use <for> is better than use <foreach> since for each is actually open another ant property space, use more memory too.

Why do I get en exception when I use location=”D:\\Code\\include” as attribute of includepath?

See here.
You need to escape the string to “D:\\\\Code\\\\include” or use “D:/Code/include” instead!
Believe me or not? Forward slash works on windows in all ant or java code. It also works in windows environment variables. It does not work in cmd (dos) window before XP. It also works in XP dos window now!

Can I put the contents of a classpath or fileset into a property?

Yes, you can.
This is very similar to the call of Java class toString() method and actually it is calling the toString() method inside ant. For example
<fileset id=”fs1″ dir=”t1″ includes=”**/*.java”/>
<property name=”f1.contents” refid=”fs1″/>
<echo>f1.contents=${f1.contents}</echo>

Where can I find the javadoc for ant API?

Download apache ant src version. Use ant javadocs command to see generated javadoc for ant in build/docs directory.

 

How can I use ant to run a Java application?

Here is a real world example.
  <target name=”run” depends=”some.target,some.other.target”>
    <java classname=”${run.class}” fork=”yes”>
      <classpath>
        <path refid=”classpath” />
      </classpath>
      <jvmarg line=”${debug.jvmargs}” />
      <jvmarg line=”${my.jvmargs}” />
      <jvmarg value=”-Dname=${name}” />
      <jvmarg line=”${run.jvmargs}” />
      <arg line=”${run.args}” />
    </java>
  </target>

How to use ant to run commandline command? How to get perl script running result?

Use exec ant task.
Don’t forget ant is pure Java. That is why ant is so useful, powerful and versatile. If you want ant receive unix command and result, you must think Unix. So does in MS-Windows. Ant just helps you to automate the process.

How do I debug my ant script?

Many ways
    * Do an echo on where you have doubt. You will find out what is the problem easily. Just like the old c printf() or Java System.println()
    * Use project.log(“msg”) in your javascript or custom ant task
    * Run Ant with -verbose, or even -debug, to get more information on what it is doing, and where. However, you might be tired with that pretty soon, since it give you too much information.

How to exclude multi directories in copy or delete task?

Here is an example.
  <copy todir=”${to.dir}” >
    <fileset dir=”${from.dir}” >
      <exclude name=”dirname1″ />
      <exclude name=”dirname2″ />
      <exclude name=”abc/whatever/dirname3″ />
      <exclude name=”**/dirname4″ />
    </fileset>
  </copy>

How to use Runtime in ant?

You don’t need to use Runtime etc. Ant have exec task.
The class name is org.apache.tools.ant.taskdefs.ExecTask. You can create the task by using the code in your customized ant Task.
ExecTask compile = (ExecTask)project.createTask(“exec”);

How to rearrange my directory structure in my jar/war/ear/zip file? Do I need to unarchive them first?

No, you don’t need to unarchive them first.
    * You don’t need to unzip the files from archive to put into your destination jar/ear/war files.
    * You can use zipfileset in your jar/war/ear task to extract files from old archive to different directory in your new archive.
    * You also can use zipfileset in your jar/war/ear task to send files from local directory to different directory in your new archive.
See the follow example:
  <jar destfile=”${dest}/my.jar”>
    <zipfileset src=”old_archive.zip” includes=”**/*.properties” prefix=”dir_in_new_archive/prop”/>
    <zipfileset dir=”curr_dir/abc” prefix=”new_dir_in_archive/xyz”/>
  </jar>

Why did I get such warning in ant?
compile:
[javac] Warning: commons-logging.properties modified in the future.
[javac] Warning: dao\\DAO.java modified in the future.
[javac] Warning: dao\\DBDao2.java modified in the future.
[javac] Warning: dao\\HibernateBase.java modified in the future.

System time problem, possible reasons:
    * You changed the system time
    * I had the same problem before, I checked out files from cvs to windows, and transfer them to a unix machine, somehow, I got huge amount of such warnings because the system timing issue.
    * If you transfer files from Australia/China/India to the United States, you will get the problem too. True enough, I did and met the problem once.

How can I write my own ant task?

Easy!
Writing Your Own Task How-To from ant.
In your own $ANT_HOME/docs/manual directory, there also is tutorial-writing-tasks-src.zip
Use them! Use taskdef to define it in your script, define it before using it.

How to copy files without extention?

If files are in the directory:
<include name=”a,b,c”/>
If files are in the directory or subdirectories:
<include name=”**/a,**/b,**/c”/>
If you want all files without extension are in the directory or subdirectories:
<exclude name=”**/*.*”/>

How do I use two different versions of jdk in ant script?

The followings are what I’m doing.
   1. Don’t define java.home by yourself. Ant uses an internal one derived from your environment var JAVA_HOME. It is immutable.
   2. I do the followings:
          * In my build.properties (read first)
            jdk13.bin=${tools.home}/jdk1.3.1_13/bin
            jdk14.bin=${tools.home}/j2sdk1.4.2_08/bin/
          * In my master properties file (read last), set default
            javac.location=${jdk13.bin}
          * In my prj.properties, if I need to use 1.4
            javac.location=${jdk14.bin}
          * in my javac task
            executable=”${javac.location}/javac.exe”

How to pass -Xlint or -Xlint:unchecked to 1.5 javac task?

pass it as compilerarg nested <compilerarg> to specify.
  <compilerarg value=”-Xlint”/>
  <!– or –>
  <compilerarg value=”-Xlint:unchecked”/>

Can you give me a simple ant xslt task example?

Here is a working one!
    <xslt style=”${xslfile}” in=”${infile}” out=”${outfile}” >
      <classpath>
        <fileset dir=”${xml.home}/bin”
          includes=”*.jar” />
      </classpath>
    </xslt>

How to hide password input?

Override ant Input task.
Response every user input with a backspace. Not the best, but it works

How do I add elements to an existing path dynamically?

Yes, it is possible. However, you need to write a custom ant task, get the path, and add/modify it, and put it in use. What I am doing is that I define a path reference lib.classpath, then add/modify the lib.classpath use my own task.

How to do conditional statement in ant?

There are many ways to solve the problem.
    * Since target if/unless all depend on some property is defined or not, you can use condition to define different NEW properties, which in turn depends on your ant property values. This makes your ant script very flexible, but a little hard to read.
    * Ant-contrib has <if> <switch> tasks for you to use.
    * Ant-contrib also has <propertyregex> which can make very complicate decisions.

Can I change/override ant properties when I use ant-contrib foreach task?

<foreach> is actually using a different property space, you can pass any property name/value pair to it. Just use <param> nested tag inside foreach

How to let auto-detect platform and use platform specific properties?

Tell you a great trick, it works excellent.
In your major build-include.xml, put in this line
  <property file=”${antutil.includes}/${os.name}-${os.arch}.properties” />
This will auto-detect your platform, and you write one file for each environment specific variables. For example: HP-UX-PA_RISC2.0.properties SunOS-sparc.properties Windows XP-x86.properties … They work great!!!

How to make ant user interactive? I tried to use BufferedReader to get user input, it hangs.

See here.
Use this class TimedBufferedReader instead of your BufferedReader will work. This is a working one in our installation process. The original author is credited in the code. I’ve made some improvement.
TimedBufferedReader.java
package setup;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.IOException;
/**
 * Provides a BufferedReader with a readLine method that
 * blocks for only a specified number of seconds. If no
 * input is read in that time, a specified default
 * string is returned. Otherwise, the input read is returned.
 * Thanks to Stefan Reich
 * for suggesting this implementation.
 * @author: Anthony J. Young-Garner
 * @author: Roseanne Zhang made improvement.
 */
public class TimedBufferedReader extends BufferedReader
{
  private int    timeout    = 60; // 1 minute
  private String defaultStr = “”;
  /**
   * TimedBufferedReader constructor.
   * @param in Reader
   */
  TimedBufferedReader(Reader in)
  {
    super(in);
  }
  /**
   * TimedBufferedReader constructor.
   * @param in Reader
   * @param sz int Size of the input buffer.
   */
  TimedBufferedReader(Reader in, int sz)
  {
    super(in, sz);
  }
  /**
   * Sets number of seconds to block for input.
   * @param seconds int
   */
  public void setTimeout(int timeout)
  {
    this.timeout=timeout;
  }
  /**
   * Sets defaultStr to use if no input is read.
   * @param str String
   */
  public void setDefaultStr(String str)
  {
    defaultStr = str;
  }
  /**
   * We use ms internally
   * @return String
   */
  public String readLine() throws IOException
  {
    int waitms = timeout*1000;
    int ms     = 0;
    while (!this.ready())
    {
      try
      {
        Thread.currentThread().sleep(10);
        ms += 10;
      }
      catch (InterruptedException e)
      {
        break;
      }
      if (ms >= waitms)
      {
          return defaultStr;
      }
    }
    return super.readLine();
  }
}

What is a good directory structure for main code and junit test code?

Dev
    |_src
    |  |_com
    |     |_mycom
    |        |_mypkg
    |           |_A.java
    |_test
       |_src
         |_com
            |_mycom
               |_mypkg
                  |_ATest.java

JUnit Drill – One

What is JUnit?

JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. JUnit features include:
Assertions for testing expected results
Test fixtures for sharing common test data
Test runners for running tests

How do I install JUnit?

First, download the latest version of JUnit, referred to below as junit.zip.
Then install JUnit on your platform of choice:
Windows
To install JUnit on Windows, follow these steps:
Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
Unix (bash)
To install JUnit on Unix, follow these steps:
Unzip the junit.zip distribution file to a directory referred to as $JUNIT_HOME.
Add JUnit to the classpath:
export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar
(Optional) Unzip the $JUNIT_HOME/src.jar file.
Test the installation by running the sample tests distributed with JUnit. Note that the sample tests are located in the installation directory directly, not the junit.jar file. Therefore, make sure that the JUnit installation directory is on your CLASSPATH. Then simply type:
java org.junit.runner.JUnitCore org.junit.tests.AllTests
All the tests should pass with an “OK” message.
If the tests don’t pass, verify that junit.jar is in the CLASSPATH.

How do I write and run a simple test?  

Create a class:
  package junitfaq;
  import org.junit.*;
  import static org.junit.Assert.*;
  import java.util.*;
  public class SimpleTest {
Write a test method (annotated with @Test) that asserts expected results on the object under test:
@Test
    public void testEmptyCollection() {
        Collection collection = new ArrayList();
        assertTrue(collection.isEmpty());
    }
If you are running your JUnit 4 tests with a JUnit 3.x runner, write a suite() method that uses the JUnit4TestAdapter class to create a suite containing all of your test methods:
    public static junit.framework.Test suite() {
        return new junit.framework.JUnit4TestAdapter(SimpleTest.class);
    }
Although writing a main() method to run the test is much less important with the advent of IDE runners, it’s still possible:
    public static void main(String args[]) {
      org.junit.runner.JUnitCore.main(“junitfaq.SimpleTest”);
    }
  }
      Run the test:
To run the test from the console, type:
java org.junit.runner.JUnitCore junitfaq.SimpleTest
To run the test with the test runner used in main(), type:
java junitfaq.SimpleTest
The passing test results in the following textual output:
        .
Time: 0
OK (1 tests)

How do I use a test fixture?

A test fixture is useful if you have two or more tests for a common set of objects. Using a test fixture avoids duplicating the code necessary to initialize (and cleanup) the common objects.
Tests can use the objects (variables) in a test fixture, with each test invoking different methods on objects in the fixture and asserting different expected results. Each test runs in its own test fixture to isolate tests from the changes made by other tests. That is, tests don’t share the state of objects in the test fixture. Because the tests are isolated, they can be run in any order.
To create a test fixture, declare instance variables for the common objects. Initialize these objects in a public void method annotated with @Before. The JUnit framework automatically invokes any @Before methods before each test is run.
The following example shows a test fixture with a common Collection object.
    package junitfaq;
    import org.junit.*;
    import static org.junit.Assert.*;
    import java.util.*;
    public class SimpleTest {
        private Collection<Object> collection;
        @Before
        public void setUp() {
            collection = new ArrayList<Object>();
        }
        @Test
        public void testEmptyCollection() {
            assertTrue(collection.isEmpty());
        }
        @Test
        public void testOneItemCollection() {
            collection.add(“itemA”);
            assertEquals(1, collection.size());
        }
    }
      Given this test, the methods might execute in the following order:
setUp()
testEmptyCollection()
setUp()
testOneItemCollection()
The ordering of test-method invocations is not guaranteed, so testOneItemCollection() might be executed before testEmptyCollection(). But it doesn’t matter, because each method gets its own instance of the collection.
Although JUnit provides a new instance of the fixture objects for each test method, if you allocate any external resources in a @Before method, you should release them after the test runs by annotating a method with @After. The JUnit framework automatically invokes any @After methods after each test is run. For example:
    package junitfaq;
    import org.junit.*;
    import static org.junit.Assert.*;
    import java.io.*;
    public class OutputTest {
        private File output;
        @Before
        public void createOutputFile() {
            output = new File(…);
        }
        @After
        public void deleteOutputFile() {
            output.delete();
        }
        @Test
        public void testSomethingWithFile() {
            …
        }
    }
With this test, the methods will execute in the following order:
createOutputFile()
testSomethingWithFile()
deleteOutputFile()

How do I test a method that doesn’t return anything?

Often if a method doesn’t return a value, it will have some side effect. Actually, if it doesn’t return a value AND doesn’t have a side effect, it isn’t doing anything.
There may be a way to verify that the side effect actually occurred as expected. For example, consider the add() method in the Collection classes. There are ways of verifying that the side effect happened (i.e. the object was added). You can check the size and assert that it is what is expected:
    @Test
    public void testCollectionAdd() {
        Collection collection = new ArrayList();
        assertEquals(0, collection.size());
        collection.add(“itemA”);
        assertEquals(1, collection.size());
        collection.add(“itemB”);
        assertEquals(2, collection.size());
    }
      Another approach is to make use of MockObjects.
A related issue is to design for testing. For example, if you have a method that is meant to output to a file, don’t pass in a filename, or even a FileWriter. Instead, pass in a Writer. That way you can pass in a StringWriter to capture the output for testing purposes. Then you can add a method (e.g. writeToFileNamed(String filename)) to encapsulate the FileWriter creation.
Under what conditions should I test get() and set() methods?
Unit tests are intended to alleviate fear that something might break. If you think a get() or set() method could reasonably break, or has in fact contributed to a defect, then by all means write a test.
In short, test until you’re confident. What you choose to test is subjective, based on your experiences and confidence level.

Under what conditions should I test get() and set() methods?

Unit tests are intended to alleviate fear that something might break. If you think a get() or set() method could reasonably break, or has in fact contributed to a defect, then by all means write a test.

Under what conditions should I not test get() and set() methods?

Most of the time, get/set methods just can’t break, and if they can’t break, then why test them? While it is usually better to test more, there is a definite curve of diminishing returns on test effort versus “code coverage”. Remember the maxim: “Test until fear turns to boredom.”
Assume that the getX() method only does “return x;” and that the setX() method only does “this.x = x;”. If you write this test:
@Test
public void testGetSetX() {
    setX(23);
    assertEquals(23, getX());
}
      then you are testing the equivalent of the following:
@Test
public void testGetSetX() {
    x = 23;
    assertEquals(23, x);
}
or, if you prefer,
@Test
public void testGetSetX() {
    assertEquals(23, 23);
}
At this point, you are testing the Java compiler, or possibly the interpreter, and not your component or application. There is generally no need for you to do Java’s testing for them.
If you are concerned about whether a property has already been set at the point you wish to call getX(), then you want to test the constructor, and not the getX() method. This kind of test is especially useful if you have multiple constructors:
@Test
public void testCreate() {
    assertEquals(23, new MyClass(23).getX());
}

How do I write a test that passes when an expected exception is thrown?

Add the optional expected attribute to the @Test annotation. The following is an example test that passes when the expected IndexOutOfBoundsException is raised:
    @Test(expected=IndexOutOfBoundsException.class)
    public void testIndexOutOfBoundsException() {
        ArrayList emptyList = new ArrayList();
    Object o = emptyList.get(0);
    }

How do I write a test that fails when an unexpected exception is thrown?

Declare the exception in the throws clause of the test method and don’t catch the exception within the test method. Uncaught exceptions will cause the test to fail with an error.
The following is an example test that fails when the IndexOutOfBoundsException is raised:
    @Test
    public void testIndexOutOfBoundsExceptionNotRaised()
        throws IndexOutOfBoundsException {
        ArrayList emptyList = new ArrayList();
        Object o = emptyList.get(0);
    }

How do I test protected methods?

Place your tests in the same package as the classes under test.

Why does JUnit only report the first failure in a single test?

Reporting multiple failures in a single test is generally a sign that the test does too much, compared to what a unit test ought to do. Usually this means either that the test is really a functional/acceptance/customer test or, if it is a unit test, then it is too big a unit test.
JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports failure on each test. Shared setup code is most natural when sharing between tests. This is a design decision that permeates JUnit, and when you decide to report multiple failures per test, you begin to fight against JUnit. This is not recommended.
Long tests are a design smell and indicate the likelihood of a design problem. Kent Beck is fond of saying in this case that “there is an opportunity to learn something about your design.” We would like to see a pattern language develop around these problems, but it has not yet been written down.
Finally, note that a single test with multiple assertions is isomorphic to a test case with multiple tests:
One test method, three assertions:
public class MyTestCase {
    @Test
    public void testSomething() {
        // Set up for the test, manipulating local variables
        assertTrue(condition1);
        assertTrue(condition2);
        assertTrue(condition3);
    }
}
      Three test methods, one assertion each:
public class MyTestCase {
    // Local variables become instance variables
    @Before
    public void setUp() {
        // Set up for the test, manipulating instance variables
    }
    @Test
    public void testCondition1() {
        assertTrue(condition1);
    }
    @Test
    public void testCondition2() {
        assertTrue(condition2);
    }
    @Test
    public void testCondition3() {
        assertTrue(condition3);
    }
}
      The resulting tests use JUnit’s natural execution and reporting mechanism and, failure in one test does not affect the execution of the other tests. You generally want exactly one test to fail for any given bug, if you can manage it.     

How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?

Refactoring J2EE components to delegate functionality to other objects that don’t have to be run in a J2EE container will improve the design and testability of the software.
Cactus is an open source JUnit extension that can be used to test J2EE components in their natural environment.

Do I need to write a test class for every class I need to test?

No. It is a convention to start with one test class per class under test, but it is not necessary.
Test classes only provide a way to organize tests, nothing more. Generally you will start with one test class per class under test, but then you may find that a small group of tests belong together with their own common test fixture.[1] In this case, you may move those tests to a new test class. This is a simple object-oriented refactoring: separating responsibilities of an object that does too much.
Another point to consider is that the TestSuite is the smallest execution unit in JUnit: you cannot execute anything smaller than a TestSuite at one time without changing source code. In this case, you probably do not want to put tests in the same test class unless they somehow “belong together”. If you have two groups of tests that you think you’d like to execute separately from one another, it is wise to place them in separate test classes.
[1] A test fixture is a common set of test data and collaborating objects shared by many tests. Generally they are implemented as instance variables in the test class.

Is there a basic template I can use to create a test?

The following templates are a good starting point. Copy/paste and edit these templates to suit your coding style.
SampleTest is a basic test template:
import org.junit.*;
import static org.junit.Assert.*;
public class SampleTest {
    private java.util.List emptyList;
    /**
     * Sets up the test fixture.
     * (Called before every test case method.)
     */
    @Before
    public void setUp() {
        emptyList = new java.util.ArrayList();
    }
    /**
     * Tears down the test fixture.
     * (Called after every test case method.)
     */
    @After
    public void tearDown() {
        emptyList = null;
    }
    @Test
    public void testSomeBehavior() {
        assertEquals(“Empty list should have 0 elements”, 0, emptyList.size());
    }
    @Test(expected=IndexOutOfBoundsException.class)
    public void testForException() {
        Object o = emptyList.get(0);
    }
}

When should tests be written?

Tests should be written before the code. Test-first programming is practiced by only writing new code when an automated test is failing.
Good tests tell you how to best design the system for its intended use. They effectively communicate in an executable format how to use the software. They also prevent tendencies to over-build the system based on speculation. When all the tests pass, you know you’re done!
Whenever a customer test fails or a bug is reported, first write the necessary unit test(s) to expose the bug(s), then fix them. This makes it almost impossible for that particular bug to resurface later.

Why not just use System.out.println()?

Inserting debug statements into code is a low-tech method for debugging it. It usually requires that output be scanned manually every time the program is run to ensure that the code is doing what’s expected.
It generally takes less time in the long run to codify expectations in the form of an automated JUnit test that retains its value over time. If it’s difficult to write a test to assert expectations, the tests may be telling you that shorter and more cohesive methods would improve your design.

The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP
consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls.

Can servlet have a constructor ?

Servlet can have a constructor. But you never call the constructor for the servlet / instantiate them , because the container handles it.
So you are better of doing initialization / one-time setup code in the init method of the servlet. Also, the container passes the ServletConfig object to the servlet only when it calls the init method. So ServletConfig will not be accessible in the constructor.However, you might still need the init parameters, so initialization is done in init instead of a constructor.