Saturday, 20 June 2015

Real difference between an Interface and an Abstract Class

This is one of the most frequently asked questions in a java interview and sadly most of the candidates give the wrong answer(my personal experience).

The first answer is a class can extends only one Abstract class but it can implements more than one interface. But this is not the sufficient answer.

The second answer people give is 'Abstract class can have an implemented method which an Interface can't have'. This is true but this makes Abstract class more desirable than an Interface, so why we use Interface more often(or almost always) for Abstraction than we use an Abstract class? 

The real answer is for defining the 'Contract'.

So what is the 'Contract' in terms of software design?

In a very plain language, contract is something which gives the client(user) code a guarantee of not failing.

For example, if you have designed a system for an ATM machine and have the following methods:

getAccountBalance();
withdrawMoney();
getLastTenTransactions();

The code which is using your ATM machine code will want the guarantee that it doesn't get into trouble any time in the future. This commitment is the contract.

So why Interface can provide it and an Abstract class could fail?

OK, let's find the answer by defining and implementing in the both cases.

Let's first do it by defining by an Abstract Class.


public abstract class ATMMachineAbstract {
public abstract int getAccountBalance();
public abstract int withdrawMoney();
public abstract String[] getLastTenTransactions();

}

The implementation of this class should look like this:

public class ATMMachine extends ATMMachineAbstract{


public int getAccountBalance() {
return 0;
}


public int withdrawMoney() {
return 0;
}


public String[] getLastTenTransactions() {
return null;
}

}

Now let's do the same thing by using an Interface:


public interface ATMMachineInterface {
public int getAccountBalance();
public int withdrawMoney();
public String[] getLastTenTransactions();

}

And the implementation of this should look like:


public class ATMMachineImplementingInterface implements ATMMachineInterface{


public int getAccountBalance() {
return 0;
}


public int withdrawMoney() {
return 0;
}


public String[] getLastTenTransactions() {
return null;
}

}

Now the client code may use these codes something like this:


public class Main {

/**
* @param args
*/
public static void main(String[] args) {
ATMMachineInterface atmi=new ATMMachineImplementingInterface();
atmi.getAccountBalance();
ATMMachineAbstract atmabs=new ATMMachine();
atmabs.getAccountBalance();

}

}

Both of the ways look similar until we some crazy guy do the magic.
So here the magic goes.

One fine day a crazy guy change the abstract class like this:


public abstract class ATMMachineAbstract {
private  int getAccountBalance(){
return 0;
};
public abstract int withdrawMoney();
public abstract String[] getLastTenTransactions();

}

In this situation, the implementation code(class ATMMachine) doesn't complain at all but the client code start giving errors.

But this situation can never arise in case of an Interface.

That is the reason Interface is used to define the contract.

I hope, i have explained the concept.








Tuesday, 25 March 2014

JSP Interview Questions

1. How to create a Thread safe JSP page?
Ans: Theoretically, JSP pages can be indicated as threadsafe via the isThreadSafe page directive attribute

2. How to catch RunTimeException in JSP?

Ans: http://www.tutorialspoint.com/jsp/jsp_exception_handling.htm

2. What is the difference between request.getSession() and request.getSession(true)?

Ans: There is no difference at all.

3. Why we don't define constructor in servlets?

Ans: 1. HttpServlet is a dynamically loaded class so any argument can't be passed in the constructor.
2. Servlet is an interface, we can't define a constructor for that.

Thursday, 27 February 2014

Multithreading example for producer consumer problem for alternate numbers

Problem Statement:

Write a multithreading program which uses 2 threads. One threads prints odd numbers and other prints even numbers. The final output should print the numbers in sequence.

Solution:

1. Main.Java

public class Main {
   
    public static void main(String [] args){
        Monitor m=new Monitor();
        Thread task1=new Thread(new Task1(m));
        Thread task2=new Thread(new Task2(m));
        task1.start();
        task2.start();
      
    }

}

2. Monitor.java

public class Monitor {
    private boolean flag=true;

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
   

}


3. Task1.java

public class Task1 implements Runnable{
    private Monitor monitor;
   
   
    public Task1(Monitor monitor) {
        super();
        this.monitor = monitor;
    }


    @Override
    public void run() {
        for(int i=0; i<=10; i=i+2){          
        synchronized (monitor) {
            while(!monitor.isFlag()){
                try {
                    monitor.wait();
                    } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        System.out.println("Printing :"+i);
        monitor.setFlag(false);
        monitor.notifyAll();

              
                }
        }
      
    }

}

Task2.java

public class Task2 implements Runnable{
    private Monitor monitor;
   
   
    public Task2(Monitor monitor) {
        super();
        this.monitor = monitor;
    }


    @Override
    public void run() {
        for(int i=1; i<=10; i=i+2){           
        synchronized (monitor) {
            while(monitor.isFlag()){
                try {
                    monitor.wait();
                    } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
               
            }
        System.out.println("Printing :"+i);
                monitor.setFlag(true);
                monitor.notifyAll();
        }
        }
       
    }

}





Saturday, 22 June 2013

Database interview questions for java programmers

1. Why do we use index?

Ans: Index are created for the faster data access. One can assume the database index as similar to the indexes found at the starting of the books. As they facilitate the faster access to the content of the books so do the DB indexes.

2. Is there any downside of creating and using indexes?

Ans: Yes, this makes the insert operation costly. Insertion becomes slow as, the index is updated every time, an insertion happens.


3. How does index work?
4. Write an sql query for deleting duplicate records
5. Write an sql query for fetching 2nd or 3rd maximum value of the records of a column of a table.
6. What are the types of index?
7. What is the difference between Statement and PreparedStatement?
8. Is PreparedStatement always faster than Statement?
9. What are clustered and non clustered indexes?
9.

Java Interview Questions

1. What is Serialization?
2. What is an immutable class?

Ans: Immutable class is the one whose object state's can't be changed after the object is created.

3. Does generics information go into byte code?

Ans: No, generics information doesn't go into byte code and this process is called type erasure.

4. What is a volatile variable?
5. How does Hashmap work?
6. What data structure does Hashset use internally?
Ans : HashMap.
7. What is the difference between using start and run in a thread? Why do we call start to use run?
8. What is the time complexity of Hashmap?

Ans: Ideal case O(1), worst case: O(n).

9. Why Spring framework is used?
10. What is AOP?
11. What is IOC?
12. What is ORM?
13. For what we use serialVersionUID?
13. What is Transient Variable?
14. What is the difference between wait and sleep?
15. What is the Lock Interface?
16. What is executer framework?
17. How do we do transaction management in Hibernate?
18. What is the difference between session and global session scope in spring?
19.  How to integrate hibernate with spring?
20. How to define factory in spring?
21.  What is default scope of spring?
Ans : This is Singleton.
22. Difference between load and get method in hibernate?
23.  Have you used filter in hibernate?
24.  How will you make your class immutable?
25.  Difference between save and persist method in hibernate?
26.  Difference between serialization and externalization?
27.  Difference between Callable and runnable interface?
28.  How to define a one to many relationship in hibernate?
29.  How to handle transaction in JDBC?
30.  How to handle a list in an immutable class?
31.  Java is by reference or by value?
Ans: Java is by value.
32.  What is detached object in hibernate?
33. Explain life cycle of a bean in spring?
34. What happens with the static variables during serialization?
35. If i serialize an object in one JVM and deserialize it in another JVM, what will happen to the static variables?
36. How can i serialize a static variable?
37. What is the difference between ArrayList and LinkedList?
38. What is the difference between HashMap, ConcurrentHashMap and HashTable?
39. What are the sections in the Heap?
40. Can we override start method of a thread?
Ans: Yes we can override this method but this thread will act just like an ordinary object rather than a thread of execution. This start method will be run by the current thread of execution.
41. Can we override wait, notify and notifyall methods?
Ans: These all are final methods so we cannot override them.
42. Why wait, notify, notifyall are defined in Object class?
43. What all design patterns do struts and validator framework implement?
44. Design a custom Arraylist.
45. Design a custom LinkedList.
46. How does Hibernate work in distributed environment?
47. What are the factors to be considered before going for multi-threading?
48. How does ConcurrentHashMap implement partial reading internally?
Ans: This uses a pool of Write Locks internally to lock the different set of buckets.
For more information kindly refer: http://www.ibm.com/developerworks/java/library/j-jtp08223/
49. How to run a code while creating an object other than putting it under constructor?
50. What is the Timer?
51. What is Lock interface?
52. How to make a single ApplicationContext with three diffrent files?
53. What is an Atomic class in java. Give an example of atomic class.
54. How to detect deadlock in your application programmatically?
Ans: We can use ThreadMXBean class.
For more info please refer: http://stackoverflow.com/questions/1102359/programmatic-deadlock-detection-in-java
55. I have an Employee class in which i have implemented Hashcode and equals method. The hashcode method returns the employee id and equals method returns false for every object. What will happen if i use this as a key?
56. How does AOP works in Spring internally?
57. Which design pattern does Spring AOP implement?
Ans: AOP implement Proxy Design Pattern.
58. What is the difference when we create a thread by extending a thread and implementing a Runnable interface?
59. Why Java enabled to catch error if there is no use of catching it?
60. How to implement second level cache in Hibernate?
61. How will you design your own Thread Pool?
Ans: This is a good article on Thread pool in Java:
http://www.ibm.com/developerworks/library/j-jtp0730/index.html
62. How many types of ResultSet are there in JDBC?
63. What is the difference between System.gc() and Runtime.gc()?
64. What is the difference between get and load methods in hibernate?
65. Explain Transaction Management in Spring.
66. Which Data Structure HashMap uses internally?

Ans: This uses a LinkedList

67. Explain Inline and Inplace  search.
68. Explain mapping strategies in Hibernate.

Ans: There are four mapping strategies:

■ Table per concrete class with implicit polymorphism—Use no explicit
inheritance mapping, and default runtime polymorphic behavior.
■ Table per concrete class—Discard polymorphism and inheritance relationships
completely from the SQL schema.
■ Table per class hierarchy—Enable polymorphism by denormalizing the SQL
schema, and utilize a type discriminator column that holds type information.
■ Table per subclass—Represent is a (inheritance) relationships as has a (foreign
key) relationships.

69. What is the difference between volatile and atomic class?
Ans: Volatile fixes visibility issue but doesn't fix Race Condition.

70. Give an example of a Collection which doesn't allow duplicates and maintains insertion order:
Ans: LinkedHashSet

71. What is the difference between save and persist in hibernate?