Archive

Archive for May, 2011

Collection Framework – Question Answer way!

May 30, 2011 Leave a comment

Q. What is collection framework ?

A. The collection framework presents a set of standard utility classes for manging group of objects.

Arbitrary objects can be stored, retrieved and manipulated as elements of collection.

Q. Which package has collection framework ?

this framework is provided in java.util package

Q. What is Mathamatical concept of a set?

A. A set is just a group of unique items, meaning that the group contains no duplicates.

Some real-world examples of sets include the following:

  • The set of uppercase letters ‘A’ through ‘Z’
  • The set of nonnegative integers {0, 1, 2 …}

These examples show the basic properties of sets:

  • Sets contains only one instance of each item
  • Sets may be finite or infinite
  • Sets can define abstract concepts
The idea of a “connection pool” is a set of open connections to a database server.
Web servers have to manage sets of clients and connections.
File descriptors provide another example of a set in the operating system.
Q. What is Mathamatical concept of a Map?
A. It is a set of pairs, each pair representing a one-directional “mapping” from one element to another. Some examples of maps are:

  • The map of IP addresses to domain names (DNS)
  • A map from keys to database records
  • A dictionary (words mapped to meanings)
  • The conversion from base 2 to base 10
Q. Why Map don’t extend collection ?
A. The typical application of a Map is to provide access to values stored by keys. The set of collection operations are all there, but you work with a key-value pair, instead of an isolated element. Map is therefore designed to support the basic operations of get() and put() which are not required by Set.
!Note: When designing software with the Collections Framework, it is useful to remember the following hierarchical relationships of the four
basic interfaces of the framework:
  • The Collection interface is a group of objects, with duplicates allowed
  • Set extends Collection but forbids duplicates
  • List extends Collection also, allows duplicates and introduces positional indexing (order of element is retained)
  • Map extends neither Set nor Collection
The following table shows the six collection implementations introduced with the Java 2 framework
Interface Implementation Historical
Set(.) no duplicate(.)at most one null HashSet(.) No OrderHashing: Constant time for add, remove, contain, size

Key->Hashcode->Index

(.) no guaranty of order

TreeSet(.) Sorted

Assenting

(.) Use tree for storage

(.) large data, sorted order, found quickly

Comparator

LinkedHashSet(.) Insertion Order
List(.)allow duplicate(.)Positional indexing(.) Insertion Order ArrayList(.)notSynchronized(.)Random Access

(.)Easy Tail manipulation

(.)default size 0.

LinkedList(.)Sequential Access(.)Add Remove Element in between Vector
Stack(.)synchronized, make it slow(.) default size 10Then double
Map(.)Unique Key HashMap(.)Allow Null as key & value(.)unsynchronized(.)no order

(.) get/put constant time for larger map

TreeMap(.) Sorted in Key order(.)Natural ordering

Comparator

LinkeHashMap(.) Key insertion order. Hashtable
Properties(.)synchronized(.)can only store object the override hashCode() and equals()

Sting does.

Collection Interface
The Collection interface is used to represent any group of objects, or elements. You use the interface when you wish to work with a group of elements in as general a manner as possible.
UML Diagram for Collection Interface
Iterator Interface

UML Diagram for Iterator Interface

Q. What is the difference between HashSet & TreeSet
A. HashSet is not sorted while TreeSet is.
1) HashSet: For efficiency, objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. While most system classes override the default hashCode() implementation in Object, when creating your own classes to add to a HashSet remember to override hashCode()
2) TreeSet: The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. In order to work property, elements added to a TreeSet must be sortable.

To optimize HashSet space usage, you can tune the initial capacity and load factor. The TreeSet has no tuning options, as the tree is always balanced, ensuring log(n) performance for insertions, deletions, and queries.

!Note: All Collection concrete classes implements Cloneable & Serializable interface.

Q. Can an implementation of collection be changed ?

Each of the implementation of Collection interface provides a constructor for creating a collection based on elements of another Collection object passed as an argument. This interchangeability is true among Map implementation as well.

But Collection and Maps are not interchangeable.

Below example demonstrate use of HashSet, TreeSet and the way HashSet can be interchanged to TreeSet.

public class SetExample {
  public static void main(String args[]) {
    Set set = new HashSet();
    set.add("Bernadine");
    set.add("Elizabeth");
    set.add("Gene");
    set.add("Elizabeth");
    set.add("Clara");
    System.out.println(set);
    Set sortedSet = new TreeSet(set);
    System.out.println(sortedSet);
  }
}
Running the program produces the following output. Notice that the duplicate entry is only present once, and the second list output is sorted.
[Gene, Clara, Bernadine, Elizabeth]
[Bernadine, Clara, Elizabeth, Gene]
Q. What does  AbstractSet class overrides?
A.The AbstractSet class overrides the equals() and hashCode() methods to ensure two equal sets return the same hash code. Two sets are equal if they are the same size and contain the same elements. By definition, the hash code for a set is the sum of the hash codes for the elements of the set. Thus, no matter what the internal ordering of the sets, two equal sets will report the same hash code.

Q. How List is different from Set ?

A. List is an

Ordered collection

Permitting Duplicates

Ability to work with part of the list

Bidirectional Iterattion

Q. When to use LinkedList & when ArrayList?

 ArrayList: If you need to support random access, without inserting or removing elements from any place other than the end, than ArrayList offers the optimal collection

LinkedList: you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially then LinkedList offers the better implementation

!Note: Two List are equal if they are the same size and contain the same elements in the same order.

Q. How can we determine the length of an ArrayList ? 

A. a.size();

Q. What is Map.Entity?

A. The entrySet() method of Map returns a collection of objects that implement Map.Entry interface. Each object in the collection is a specific key-value pair in the underlying Map.

!Note : Both the key and value can be null. However, you should not add a Map to itself as a key or value.

Q. Difference between HashMap & TreeMap ?

A. HashMap: Deleting, and locating elements in a Map, the HashMap offers the best alternative

TreeMap: You need to traverse the keys in a sorted order, then TreeMap is your better alternative.

Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. Using a HashMap requires that the class of key added have a well-defined hashCode() implementation. With the TreeMap implementation, elements added to the map must be sortable.

To optimize HashMap space usage, you can tune the initial capacity and load factor. The TreeMap has no tuning options, as the tree is always balanced.

!Note: Similar to the other abstract collection implementations, the AbstractMap class overrides the equals() and hashCode() methods to ensure two equal maps return the same hash code. Two maps are equal if they are the same size, contain the same keys, and each key maps to the same value in both maps. By definition, the hash code for a map is the sum of the hash codes for the elements of the map, where each element is an implementation of the Map.Entry interface. Thus, no matter what the internal ordering of the maps, two equal maps will report the same hash code.

Q. What is Comparator?

A. Defines how two objects are compared.

Q. What is Autoboxing and Unboxing

A. As Collection can not store primitives. Java perform the proper Autoboxing and Unboxing needed when storing or retrieving primitive types.

Q. Collection extends Iterable interface

A. Means can be cycled using for each type for loop.

Q. 

Categories: J2SE

Synchronization – The Question Answer way!

May 29, 2011 Leave a comment

Q. What is the difference between Synchronization Method & Synchronization Block.

They can be differentiated on two basis:-

1) The nature of lock:-

Synchronized method of an object is synchronized on the lock of the object or class (static synchronized method) of the method, while

Synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.

2)  Granularity of lock:-

Synchronization Block mechanism allows fine-grained synchronization, while

Synchronized method are to be used when a method can manipulate the state of the object in ways that can corrupt the state if executed concurrently.

Q. What are Locks ?

A. Lock is used to synchronize access to shared resources

A thread gain access to a shared resource by first acquiring the lock associated with the resource

A lock thus implements mutual exclusion

All objects have a lock, only one thread at a time can access the shared resource guarded by the lock.

Q. Number of ways access of the resource can be synchronized ?

There are two ways in which access of the resource can be syncronized

a. Synchronized method

b. Synchronized block

a. Synchronized method:-

A thread wish to execute synchronized method must first obtain the OBJECTS LOCK before it can enter the object to execute the method.

In other words, Synchronized method of an object is synchronized on the lock of the object

Q. How is lock of the object achieved ?

A. This is simply achieved Lock is by calling the method,  if the object’s lock is acquired by some other thread, the calling thread waits.

Q. When to Use synchronized method ?

Synchronized method are to be used when a method can manipulate the state of the object in ways that can corrupt the state if executed concurrently.

Example:- Stack Push & Pop methods. When one thread is pushing other thread can not pop.

When one thread is executing the synchronized method of an object, all other threads that wish to execute this or any other sync. method have to wait.

This does not applies to thread that already has the lock, such a method can call other sync. method without being blocked.

Important Note:-

Q. How Static method are synchronized ?

Static method synchronize on the class lock.

Also, synchronization of static method in a class is independent from the synchronization of instance method of the class.

Q. A synchronized method, when overridden in sub class, what happens to its synchronized quality ?

A sub class decides whether the  new definition of an inherited synchronized method will remain synchronized in the subclass.

b. Synchronized block

Synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.

synchronized (<object reference expression>) {<Code block>}

“object reference expression” must evaluate to a non null reference value, else a null pointer exception is thrown

The code block is usually related to the object on which synchronization is done.

example:- synchronized (this) {}

Once the thread had entered the code block, no other thread will be able to execute the code block, or any other code requiring the same object lock.

This mechanism allows fine-grained synchronization of code on arbitrary object.

Q. Synchronization Block, are all part of the sytex mandatory?

“synchronized (<object reference expression>) {<Code block>}” 

Object specification & {} are mandatory even if we have a single line of code.

Q. An inner object might need to synchronize on its associated outer object, how is it achievable ?

class Outer{

private double myPi;

protected class inner{

public void setPi(){

synchronized void setPi(Outer.this){

myPi = Math.PI;

}

}

}

}

Q. Can Synchronized block be specified on class lock ?

Yes, by:-

synchronized (<class name>.class) {<code block>}

A static synchronized method of class A is equivalent to

static void classAction(){

synchronized (A.class)  {

}

}

Q. In how many ways a thread can hold a lock on an object ? 

1) By executing a member synchronized method, object lock.

2) By executing a static  synchronized method, class lock.

3) By executing a synchronized block, lock on an object or class.

Categories: J2SE

What is “System”, “out”, “println” in System.out.println ? Explain !

May 29, 2011 Leave a comment
System.out.println()

System is a built-in class present in java.lang package.
This class has a final modifier, which means that, it cannot be inherited by other classes.
It contains pre-defined methods and fields, which provides facilities like standard input, output, etc.

out is a static final field (ie, variable)in System class which is of the type PrintStream (a built-in class, contains methods to print the different data values).
static fields and methods must be accessed by using the class name, so ( System.out ).

out here denotes the reference variable of the type PrintStream class.

println() is a public method in PrintStream class to print the data values.
Hence to access a method in PrintStream class, we use out.println() (as non static methods and fields can only be accessed by using the refrence varialble)

System.out.println();

eg:

int i = 3;
System.out.println(i);

the above code prints the value of 3 in the screen and brings the control to the next line.

All java programs automatically import java.lang package.This package defines a class called System
standard input,output and error output of the java runtime are stored in in,out,err variable
 
Demo Program:-
class SystemTester 
{
	public static void main(String[] args) 
	{
		int i = 3;
		System.out.println(i);
		System.out.println(System.currentTimeMillis()); 
		//Return the current time in terms of milliseconds.
		System.out.println(System.getProperty("user.dir"));
	}
}

Output:-
E:\Java\Examples>java SystemTester
3
1306662087283
E:\Java\Examples
Categories: J2SE
Follow

Get every new post delivered to your Inbox.