Aug 27, 2010

What is diamond problem with multiple inheritance and how does Java handles it?

The diamond problem with multiple inheritance is that when two classes provide a method with the same name and a single inherits both the classes then it becomes ambigous as to which method should the derived class use since it has inherits two different implementaions of the same method.

C++ handles this problem by allowing the programmar to define the class before invoking such method so as to remove the ambiguity.

Java handles this by disallowing multiple inheritance at all. Since the problem is with the implementation methods and not with methods which don't have any implementation (abstract methods), Java allows a class to implement multiple interfaces. So if a method is declared in two interfaces and a single class implements both the interfaces, there is no ambiguity because there is no code which can be executed in the inherited methods and the sub class will anyway be providing its own implementation (assuming non-abstract sub class)

What is the difference between class level lock and instance level lock in java?

A class level lock is the lock which makes all object of a class to wait until the corresponding lock is not released.

e.g

Class A{
static synchronized void foo(){}
}
Here the method foo is synchronized and hence all the threads on all the objects of the class will wait until the object currently running the foo method completes its execution.

Similarly an instance level lock makes all the threads started using the instance of the class to wait until the lock is not released.

e.g.
Class A{
synchronized void bar(){}
}
Here all the threads started from the object which is currently executing the bar method will wait until the current threads completes its execution. Note that other threads of other objects can execute the bar method while another object's thread is executing the bar method.

What is the difference between concat and append?

The concat function is present in String class but the append functin is present in StringBuffer/StringBuilder class.

The concat function concats the string on which it is invoked with the string passed as parameter to this function. The result returned is a new String with both the strings concatanated.

The append function appends a String to the String represent by the StringBuffer/StringBuilder object on which the append() method is invoked. The result returned is the same StringBuffer/StringBuilder object on which this method was invoked.

Same hashcode for multiple objects

We Already Know About Hashcode
You may be aware that the hash based collections make use of the hashcode of an object for storing as well as retrieving the value objects. This hashcode is decided by the hashcode() method which every object in Java inherits from the Object class.

Though the default implementation sends the hashcode as the memory address of the object, but the hashcode method can always be overridden to maintain the hashcode and equals contract.

Overriding the hashcode method is recommended in order to use the hash based collections in Java. Whatever two objects are equal according to equals() method should  have same hashcode but vice versa may not be true.

Collision and Its Resolution
But the hashcode and equals contract doesn't say that we can't have same hashcode for all objects. When a number of objects have same hashcode then there is a collision in hash based collections like HashMap, Hashtable, HashSet etc.

To resolve this collision, some collision resolution strategy like Bucketing is used in which all the collided objects are stored as an array. Now when retrieving this objects from the collection the same hashcode is used and the compiler finds that there are multiple objects at this place and hence uses the equals() method of the key object to decide the value object to be returned which means extra processing.


One can create collision by overriding the hashcode method as shown below:

public int hashcode() {
    return 1;
}

Advantage of Having Same Hashcode
The use of same hashcode may result into the illusion that it will always make the program slower because of the extra processing for finding the appropriate value object to be returned.

But having same hashcode is helpful in case of searching millions of records. Any kind of search can be optimized if the search algorithm can logically eliminate some particular candidates for result. This elimination results in simply ignoring the eliminated candidates. If we have same hashcode for a particular set of objects then we can search for the value object in the set itself and not all the key objects.
Example:
Suppose our application deals with cars and the car objects are managed by a hashing algorithm. We can have hashcode as 1 for all keys corresponding to Volkswagen car objects and 2 for all Chevrolet car objects. Similarly we have 3 as hashcode for all keys of Ford car objects and 4 for all Honda car objects.


If we want to search for Chevrolet Cars, we have a bucket corresponding to hashcode 1 which has all the Chevrolet objects available with the hashing algorithm and hence it need not look for Chevrolet objects in any other bucket.

But this approach may not be suitable for applications which in addition to searching also perform other operations which do not involve search operations. e.g Updating the value object.

What happens when an exception occurs with a finally block having return statement?

The finally block is used with try/catch block to perform clean up operations.

The finally block is gauranteed to be run irrespective of whether exception is thrown from the try block.

The onbly cases when the finally block is bypassed is when the program/JVM crashes or when System.exit() is used in the try block.

Even if there is a return statement in the try block, the finally block is return before the control returns to the calling function.

finally block syntax:

try{
throw new Exception().
}
catch(Exception e){
}
finally{
cleanup();
}

Aug 26, 2010

What is the difference between final, finally and finialize?

The final keyword means that variable/reference is final.
i.e. the value of final variable can not be changed once it has been constructed and some value should be assigned to these variables before construction of the object.
Final class means that no class can subclass this class
Final method means that the method can't be overriden.


Finally means that the code in this block will always be executed irrespective of whether an exception occurs or not. The only cases wehere the finally block is not executed is System.exit() or if program crashes.


Finalize method is called before an object is marked for garbage collection. Once an object has been marked as being Finalize run, the object can be claimed at any time bvy JVM. We override this method for defining some custom behaviour before an object is being garbage colected.

Why is String class declared as Final?

String objects are so frequently used in java programs that if they were not declared final then all java applications would need too man unnecessary synchronized keywords because we would like to make sure that no one changes the value of String when he is reading/writing a String.

Thus by declaring String class we are maintaining that no String object can be changed once it has been constructed.

What is the difference between cohesion and coupling in java?

cohesion literally means that how much sticky/strong/purposeful an object is
coupling means how much two objects are dependant on each other.

For a better Java App design,
the classes should be highly cohesive and loosly coupled.

If two classes are highly coupled then if one is changed, other also needs a change. To avoid high coupling, many design patterns have been written like Business Delegate, Session Facade etc.

If the purpose of a class is clear and is handling only one purpose then that class is said to be highly cohesive.
e.g. the ArrayList class implements the operations of ArrayList only and does not operations for Map or Set. ArrayList class is highly cohesive in that sense.

What is the difference between JAR, WAR and EAR file?

JAR file: This is a zip file to bundle a number of class files together. A jar file is usually placed on classpath and the corresponding classes are used for performing various operations. e.g. JUNIT has class files TestCase which helps us to write test cases with some prredefined methods. No server is required to use a jar file.

WAR file: This is web arvhive file where we can bundle a web application in a single file and deploy/ship to anyone. A war file can be deployed in packaged deployment and it can be extracted before deployment in exploded deployment. A war file will generally have WEB-INF,META-INF folders along with some top level jsp/html files. You need a web server like Tomcat for deploying a EAR file.

EAR file: This is Enterprise Application Archive file which has the information about web module as well as EJB module. You need an application server like IBM webshphere for deploying a EAR file.

What is the difference between Delegation and Inheritance?

Delegation means passing control to someone else for further action.

Inheritance means using the capabilities of someone to perform the action in hand.

Both of these concepts are used frequently in a java application.

While inheritance helps in code resuse, delegation helps in reducing the coupling.

An example of delegation will be:
CarBuilder c = new CarBauilder();
c.build();

An example of inheritance will be:
Class Car extends Vehicle{}

Aug 11, 2010

When to use interfaces instead of abstract classes?

First we brush up what is interface and what is an abstract class.

An interface does not contain any methods implemented and all methods must be public abstract non-static. All the variables are public static

An abstract class may contain some methods which do not have any implementation in the class itself. But these methods should be declared with abstract keyword. Note that no abstract keyword is required for interface methods.

Most common answer to the question "What is the difference between interface and abstract class" is that we can implement multiple interface but we can extend only one abstract class (or for that matter only one class)


But the subtle difference between the two is from design perspective which also tells us when to use what.
Interface is meant to be used when you don't see any kind of code reuse at the current level. A classic example is the Collection interface. It only has methods to define what all operations may be supported by a collection like add remove etc.
Abstract class is meant to be used when you see some kind of code reuse now or in forseeable future. Again we take example from the AbstractList of the collections API. Now the AbstractList implementes the Collection interface. The AbstractList class adds some member variables and methods on top of what is provided by the Collection interface.

The real difference is that Collection interface is providing a contract for the collections api be it a set or list type of collection. But the AbstractList or AbstractSet abstract classes provide some of the implementation logic and leave the details of implementation on the specific collection class.

Aug 1, 2010

What are the various types of design patterns in Java?

Broadly the design patterns can be classified as:

1) Creational:These patterns deal with the way objects are created in Java
2) Structural:These patterns deal with the composition of classes and objects
3) Behavioral:These patterns deal with the communication between objects

1) Creational
a) Factory : Provides the client objects of particular type e.g. Car objects
b) Abstract Factory :
c) Singleton
d) Prototype

2) Structural
a) Decorator
b) Facade
c) Flyweight
d) Proxy
e) Composite

3) Behavioral
a) Chain of Responsibility
b) Iterator

What is singleton pattern and how to make it threadsafe

Singleton pattern is a solution which comes to help when you want to allow only one instance of the class in your application. Let us understand the concept of single pattern using a program.

Following is a class which allows only one instance of itself to be created:

public final class A{

static A a = new A();

private int b;

public int getB(){return b;}

public void setB(int b){this.b = b;}

private A(){}

public static A newInstance(){

return a;

}

}



The above solution is thread safe as the instance of the class is being created whenever the class is loaded into the memory.

In which situation Arrays and ArrayList should be used?

As we know that array can be declared if we know the size beforehand. But if we don not know the number of elements that we want to store than ArrayList should be used.

Moreover, array can store elements of one type and ArrayList can store elements of different type (Though that is unsafe and generics can be used to enforce that only one type of elements are stored in ArrayList).

Though both provide index based access to elements but array is generally faster in access than ArrayList.

What is the difference between Iterator and ListIterator interface?

1)The Iterator interface is used to iterate over an elements in a collection of type list or set.

But a ListIterator is for list type of collections.


2) An Iterator can only move in the forward direction.
But a ListIterator can move in both directions (using next() and previous() elements)

3) An Iterator can only remove elements from the collection and cannot add elements
But a ListIterator can add as well as remove elements from the collection.

What are the different types of ResultSet in java?

There are following types of resultsets in Java or JDBC namely
TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE
CONCUR_READ_ONLY and CONCUR_UPDATABLE

TYPE_FORWARD_ONLY: This resultset can only move forward

TYPE_SCROLL_INSENSITIVE: This resultset can move forward as well as backward but any changes made to database while the resultset is open will not be reflected in the resultset.

TYPE_SCROLL_SENSITIVE: This resultset can move forward as well as backward and any changes made to database while the resultset is open will be reflected in the resultset.

All of three type of resultset described above can have two more properties listed below:

CONCUR_READ_ONLY: The resultset can not update the database and is read only.

CONCUR_UPDATABLE: The resultset can update the database.

To create the corresponding resultset use the following statements:
1)
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery(strQuery);

Here we will get a only forward moving result set (once you reach the end you can't move back i.e. there is no previous() method). Moreover this resultset will be read only and can't make changes in database. To allow the resultset to update the databsse, use ResultSet.CONCUR_UPDATABLE as the second parameter to createStatement method.

2)
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(strQuery);

Here we will get a both forward and backward moving result set. Moreover this resultset will be able to make changes in database.

How to read properties file using Java?

Use the following program to read properties from a .properties file and display the key and corresponding values.


String key;
BufferedReader bfReader = new BufferedReader(new FileReader(new File("")));
Properties prop = new Properties();
prop.load(bfReader);

Set keys = prop.keySet();
Iterator ite = keys.iterator();
while(ite.hasNext()){
key = (String)ite.next();
System.out.println("key = " + key + " value = " + prop.getProperty(key));
}

What is the API to parse String to int, boolean, long, double, float

The wrapper classes are used to parse String objects carrying the corresponding values and either return the wrapper objects or the primitives.

Let's take up few examples:
String to int
String str = "123";
int a;

a = Integer.parseInt(str);
or
a = Integer.getInteger(str).intValue();
or
a = Integer.valueOf(str).intValue();

String to Integer
String str = "123";
Integer a;

a = Interger.getInteger(str);
or
a = Interger.valueOf(str);

String to boolean
String str = "true";
boolean c;

c = Boolean.getBoolean(str);
c = Boolean.parseBoolean(str);
c = Boolean.valueOf(str).booleanValue();

String to Boolean
String str = "true";
Boolean a = Interger.valueOf(str);

If unparseable, the boolean value returned is false.

String to long
String str = "123";
long e;

e = Long.parseLong(str);
or
e = Long.getLong(str).longValue();
or
e = Long.valueOf(str).longValue();

String to Long
String str = "123";
Long f;

f = Long.getLong(str);
or
f = Long.valueOf(str);

String to double
String str = "1.23";
double g;

g = Double.parseDouble(str);
or
g = Double.valueOf(str).doubleValue();

String to Double
String str = "1.23";
Double h = Double.valueOf(str);

String to float
String str = "1.23";
float i;

i = Float.parseFloat(str);
or
i = Float.valueOf(str).floatValue();

String to Float
String str = "1.23";
Float j = Float.valueOf(str);