Вы находитесь на странице: 1из 67

1. What is immutable object? Can you write immutable object?

Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. 2. Does all property of immutable object needs to be final? Not necessary as stated above you can achieve same functionality by making member as non final but private and not modifying them except in constructor. 3. What is the difference between creating String as new() and literal? When we create string with new() Operator, its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap. String s = new String("Test"); does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool. 4. How does substring () inside String works? Another good Java interview question, I think answer is not sufficient but here it is Substring creates new object out of source string by taking a portion of original string. see my post How SubString works in Java for detailed answer of this Java question.

5. Which two method you need to implement for key Object in HashMap ? In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. You can also see my post 5 tips to correctly override equals in Java to learn more about equals.

6. Where does these two method comes in picture during get operation? This core Java interview question is follow-up of previous Java question and candidate should know that once you mention hashCode, people are most likely ask How its used in HashMap. See How HashMap works in Java for detailed explanation. 7. How do you handle error condition while writing stored procedure or accessing stored procedure from java? This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice. 8. What is difference between Executor.submit() and Executer.execute() method ? This Java interview question is from my list of Top 15 Java multi-threading question answers, Its getting popular day by day because of huge demand of Java developer with good concurrency skill. Answer of this Java interview question is that former returns an object of Future which can be used to find result from worker thread) By the way @vinit Saini suggested a very good point related to this core Java interview question There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

9. What is the difference between factory and abstract factory pattern? This Java interview question is from my list of 20 Java design pattern interview question and its open for all of you to answer. @Raj suggested Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre. You can also refer What is Factory method design pattern in Java to know more details. 10. What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
2

Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double checked locking which is purpose of this Javainterview question.

11. Can you write critical section code for singleton? This core Java question is followup of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe. check 10 Interview questions on Singleton Pattern in Java for more details and questions answers
12. Can you write code for iterating over hashmap in Java 4 and Java 5 ?

Tricky one but he managed to write using while and for loop. 13. When do you override hashcode and equals() ? Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap. check this for writing equals method correctly 5 tips on equals in Java 14. What will be the problem if you don't override hashcode() method ? You will not be able to recover your object from hash Map if that is used as key in HashMap. See here How HashMap works in Java for detailed explanation. 15. Is it better to synchronize critical section of getInstance() method or whole getInstance() method ? Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object) 16. What is the difference when String is gets created using literal or new() operator ? When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap. 17. Does not overriding hashcode() method has any performance implication ? This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map. 18. Whats wrong using HashMap in multithreaded environment? When get() method go to infinite loop

?
Another good question. His answer was during concurrent access and re-sizing.

Give a simplest way to find out the time a method takes for execution without using any profiling tool? this questions is suggested by @Mohit Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
19.

To put it in code long start = System.currentTimeMillis (); method (); long end = System.currentTimeMillis (); System.out.println (Time taken for execution is + (end start)); Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing
How to use Volatile keyword in Java What is Volatile variable in Java and when to use Volatile variable in Java is famous multi-threading interview question in Java interviews. Though many programmer knows what is a volatile variable but they fail on second part i.e. where to use volatile variable in Java as its not common to have clear understanding and hands-on on volatile in Java. In this tutorial we will address this gap by providing simple example of volatile variable in Java and discussing some when to use Volatile variable in Java. Any way Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like Autoboxing, Enum, Generics and Variable arguments , Java introduces some change in Java Memory Model (JMM), Which guarantees visibility of changes made by one thread to another also as "happensbefore" which solves the problem of memory writes that happen in one thread can " leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatile keyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.

This Java tutorial on Volatile keyword is in continuation of my article How HashMap works in Java and difference between HashMap and Hashtable in Java , How Garbage collection works in Java and How Synchronization works in Java if you havent read already you may find some useful information based on my experience in Java .

Example of volatile keyword in Java: To Understand example of volatile keyword in java lets go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without volatile keyword in java.

/** * Java program to demonstrate where to use Volatile keyword in Java. * In this example Singleton Instance is declared as volatile variable to ensure * every thread see updated value for _instance. * * @author Javin Paul */ public class Singleton{ private static volatile Singleton _instance; //volatile variable public static Singleton getInstance(){ if(_instance == null){ synchronized(Singleton.class){ if(_instance == null) _instance = new Singleton(); } } return _instance; } If you look at the code carefully you will be able to figure out: 1) We are only creating instance one time 2) We are creating instance lazily at the time of first request comes. If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.

Why because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads. So in Summary apart from synchronized keyword in java, volatile keyword is also used to communicate content of memory between threads. Lets see another example of volatile keyword in Java:

most of the time while writing game we use a variable bExist to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread , So if we don't use volatile keyword with this variable , Game Thread might miss update from event handler thread if its not synchronized in java already. volatile keyword in java guarantees that value ofvolatile variable will always be read from main memory and "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads. private boolean bExit; while(!bExit) { checkUserPosition(); updateUserPosition(); }

In this code example One Thread (Game Thread) can cache the value of "bExit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable " bExit" as volatile in java ensures this will not happen.

When to use Volatile variable in Java


One of the most important thing in learning of volatile keyword is understanding when to use volatile variable in Java. Many programmer knows what is volatile variable and How does it work but they never really used volatile for any practical purpose. Here are couple of example to demonstrate when to use Volatile keyword in Java: 1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java. 2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values. 3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like followingexample without volatile variable may result in infinite loop private boolean isActive = thread; public void printMessage(){ while(isActive){ System.out.println("Thread is Active"); } } without volatile modifier its not guaranteed that one Thread see the updated value of isActive from other thread. compiler is also free to cache value of isActive instead of reading it from main memory in every iteration. By making isActive a volatile variable you avoid these issue. 4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment. Important points on Volatile keyword in Java 1. volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal. 2. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache. 3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).

4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable. 5. From Java 5 changes to a volatile variable are always visible to other threads. Whats more it also means that when a thread reads a volatile variable in java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change. 6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without use of volatile keyword in Java. 7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock. 8. Java volatile variable that is an object reference may be null. 9. Java volatile keyword doesn't means atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java. 10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.

Difference between synchronized and volatile keyword in Java Difference between volatile and synchronized is another popular core Java question asked in multi-threading and concurrency interviews. Remember volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java. 1. Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods. 2. Synchronized obtains and releases lock on monitors java volatile keyword doesn't require that. 3. Threads in Java can be blocked for waiting any monitor in case of synchronized, that is not the case with volatile keyword in Java. 4. Synchronized method affects performance more than volatile keyword in Java. 5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory and "main" memory while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile. 6. You can not synchronize on null object but your volatile variable in java could be null. 7. From Java 5 Writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire In Summary volatile keyword in Java is not a replacement of synchronized block or method but in some situation is very handy and can save performance overhead which comes with use of synchronization in Java if you like to know more about volatile I would also suggest to go thorough FAQ on Java Memory Model here which explains happens-before operations quite well.

Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces coupling between Producer and Consumer by separating Identification of work with Execution of Work. In producer consumer design pattern a shared queue is used to control the flow and this separation allows you to code producer and consumer separately. It also addresses the issue of different timing require to produce item or consuming item. by using producer consumer pattern both Producer and Consumer Thread can work with different speed. In this article we will see What is producer consumer problem which is very popular multi-threading interview question, How to solve producer consumer problem using Blocking Queue and Benefits of using Producer Consumer design pattern.

Real World Example of Producer Consumer Design Pattern

Producer consumer pattern is every where in real life and depict coordination and collaboration. Like one person is preparing food (Producer) while other one is serving food (Consumer), both will use shared table for putting food plates and taking food plates. Producer which is the person preparing food will wait if table is full and Consumer (Person who is serving food) will wait if table is empty. table is a shared object here. On Java library Executor framework itself implement Producer Consumer design pattern be separating responsibility of addition and execution of task.

Benefit of Producer Consumer Pattern


Its indeed a useful design pattern and used most commonly while writing multi-threaded or concurrent code. here is few of its benefit: 1) Producer Consumer Pattern simple development. you can Code Producer and Consumer independently and Concurrently, they just need to know shared object. 2) Producer doesn't need to know about who is consumer or how many consumers are there. Same is true with Consumer. 3) Producer and Consumer can work with different speed. There is no risk of Consumer consuming half-baked item. In fact by monitoring consumer speed one can introduce more consumer for better utilization. 4) Separating producer and Consumer functionality result in more clean, readable and manageable code.

Producer Consumer Problem in Multi-threading


Producer-Consumer Problem is also a popular java interview question where interviewer ask to implement producer consumer design pattern so that Producer should wait if Queue or bucket is full and Consumer should wait if queue or bucket is empty. This problem can be implemented or solved by different ways in Java, classical way is using wait and notify method to communicate between Producer and Consumer thread and blocking each of them on individual condition like full queue and empty queue. With introduction of BlockingQueue Data Structure in Java 5 Its now much simpler because BlockingQueue provides this control implicitly by introducing blocking methods put()

and take(). Now you don't require to use wait and notify to communicate between Producer and Consumer. BlockingQueue put() method will block if Queue is full in case of Bounded Queue and take() will block if Queue is empty. In next section we will see a code example of Producer Consumer design pattern.

Using Blocking Queue to implement Producer Consumer Pattern


BlockingQueue amazingly simplifies implementation of Producer-Consumer design pattern by providing outofbox support of blocking on put() and take(). Developer doesn't need to write confusing and critical piece of wait-notify code to implement communication. BlockingQuue is an interface and Java 5 provides different implantation like ArrayBlockingQueue and LinkedBlockingQueue , both implement FIFO order or elements, while ArrayLinkedQueue is bounded in nature LinkedBlockingQueue is optionally bounded. here is a complete code example of Producer Consumer pattern with BlockingQueue. Compare it with classic wait notify code, its much simpler and easy to understand. import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; public class ProducerConsumerPattern { public static void main(String args[]){ //Creating shared object BlockingQueue sharedQueue = new LinkedBlockingQueue(); //Creating Producer and Consumer Thread Thread prodThread = new Thread(new Producer(sharedQueue)); Thread consThread = new Thread(new Consumer(sharedQueue)); //Starting producer and Consumer thread prodThread.start(); consThread.start(); } } //Producer Class in java class Producer implements Runnable { private final BlockingQueue sharedQueue; public Producer(BlockingQueue sharedQueue) { this.sharedQueue = sharedQueue; } @Override public void run() { for(int i=0; i<10; i++){ try { System.out.println("Produced: " + i); sharedQueue.put(i); } catch (InterruptedException ex) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);

} } } } //Consumer Class in Java class Consumer implements Runnable{ private final BlockingQueue sharedQueue; public Consumer (BlockingQueue sharedQueue) { this.sharedQueue = sharedQueue; } @Override public void run() { while(true){ try { System.out.println("Consumed: "+ sharedQueue.take()); } catch (InterruptedException ex) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex); } } }

} Output: Produced: 0 Produced: 1 Consumed: 0 Produced: 2 Consumed: 1 Produced: 3 Consumed: 2 Produced: 4 Consumed: 3 Produced: 5 Consumed: 4 Produced: 6 Consumed: 5 Produced: 7 Consumed: 6 Produced: 8 Consumed: 7 Produced: 9 Consumed: 8 Consumed: 9 You see Producer Thread produced number and Consumer thread consumes it in FIFO order because blocking queue allows elements to be accessed in FIFO. Thats all on How to use Blocking Queue to solve Producer Consumer problem or example of Producer consumer design pattern. I am sure its much better than wait notify example but be prepare with both if you are going for any Java Interview as Interview may ask you both way. 1) You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?

10

This thread interview questions is mostly asked in first round or phone screening round of interview and purpose of this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of this multi-threading questions is simple it can be achieved by using join method of Thread class.

2) What is the advantage of new Lock interface over synchronized block in Java? You need to implement a high performance cache which allows multiple reader but single writer to keep the integrity how will you implement it? The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate lock for reading and writing which enables you to write high performance data structure like ConcurrentHashMap and conditional blocking. This java threads interview question is getting increasingly popular and more and more follow-up questions come based upon answer of interviewee. I would strongly suggest reading Locks before appearing for any java multi-threading interview because now days Its heavily used to build cache for electronic trading system on client and exchange connectivity space.

3) What are differences between wait and sleep method in java? Another frequently asked thread interview question in Java mostly appear in phone interview. Only major difference is wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for interthread communication while sleep is used to introduce pause on execution. See my post wait vs sleep in Java for more differences

4) Write code to implement blocking queue in Java? This is relatively tough java multi-threading interview question which servers many purpose, it checks whether candidate can actually write Java code using thread or not, it sees how good candidate is on understanding concurrent scenarios and you can ask lot of follow-up question based upon his code. If he uses wait() and notify() method to implement blocking queue, Once interviewee successfully writes it you can ask him to write it again using new java 5 concurrent classes etc.

5) Write code to solve the Produce consumer problem in Java? Similar to above questions on thread but more classic in nature, some time interviewer ask follow up questions How do you solve producer consumer problem in Java, well it can be solved in multiple way, I have shared one way to solve producer consumer problem using BlockingQueue in Java , so be prepare for surprises. Some time they even ask to implement solution of dining philosopher problem as well. 6) Write a program which will result in deadlock? How will you fix deadlock in Java? This is my favorite java thread interview question because even though deadlock is quite common while writing multi-threaded concurrent program many candidates not able to write deadlock free code and they simply struggle. Just ask them you have n resources and n thread and to complete an operation you require all resources. Here n can be replace with 2 for simplest case and higher number to make question more intimidating. see How to avoid deadlock in java for more information on deadlock in Java.

7) What is atomic operation? What are atomic operations in Java? Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :) You can read more about java synchronization here.

8) What is volatile keyword in Java? How to use it? How is it different from synchronized method in Java? Thread questions based on volatile keyword in Java has become more popular after changes made on it on Java 5 and Java memory model. Its good to prepare well about how volatile variables ensures visibility, ordering and consistency in concurrent environment.

11

9) What is race condition? How will you find and solve race condition? Another multi-threading question in Java which appear mostly on senior level interviews. Most interviewer grill on recent race condition you have faced and how did you solve it and some time they will write sample code and ask you detect race condition. See my post on Race condition in Java for more information. In my opinion this is one of the best java thread interview question and can really test the candidate's experience on solving race condition or writing code which is free of data race or any other race condition. Best book to get mastery of this topic is " Concurrency practices in Java'".

10) How will you take thread dump in Java? How will you analyze Thread dump? In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather simple and focus thread interview question but can get tricky if he ask how you analyze it. Thread dump can be useful to analyze deadlock situations as well.

11) Why we call start() method which in turns calls run() method, why not we directly call run() method ? Another classic java multi-threading interview question This was my original doubt when I started programming in thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews. Answer to this question is that, when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesnt create any new thread and execute code on same calling thread. Read my post Difference between start and run method in Thread for more details.

12) How will you awake a blocked thread in java? This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of calling wait(), sleep() or join() method you can interrupt the thread and it will awake by throwing InterruptedException. See my post How to deal with blocking methods in Java for more information on handling blocked thread.

13) What is difference between CyclicBarriar and CountdownLatch in Java ? New java thread interview questions mostly to check familiarity with JDK 5 concurrent packages. One difference is that you can reuse CyclicBarrier once barrier is broken but you can not reuse ContdownLatch.

14) What is immutable object? How does it help on writing concurrent application? Another classic interview questions on multi-threading, not directly related to thread but indirectly helps a lot. This java interview question can become more tricky if ask you to write an immutable class or ask you Why String is immutable in Java as follow-up.

15) What are some common problems you have faced in multi-threading environment? How did you resolve it? Memory-interference, race conditions, deadlock, live lock and starvation are example of some problems comes in multi-threading and concurrent programming. There is no end of problem if you get it wrong and they will be hard to detect and debug. This is mostly experienced based interview question on java thread instead of fact based. These were my favorite Java thread interview questions and mostly asked on Investment banks. This list is by no means complete so please contribute some of interesting java thread questions you have faced during interview. Purpose of this article is to collect and share great interview questions on multi-threading concept which not only helps on interview but opens door for learning new threading concept.

12

Update: One of Javarevisited reader, Hemant has contributed some more thread interview questions in Java, though he hasnt provide answer and left that job for me, I will certainly do when time allows, just like I hav e recently updated 10 Singleton interview question in Java with answers. If you guys know answers of this java concurrency questions than please post as comment: Here is his comment Good questions on multi-threading though you may need to prepare more in order to clear any multi-threading interview, you need to be familiar with concept of immutability, thread-safety, race condition and many more. 10 or 15 question is good for quick recap but you at-least need to prepare more than 50 questions on threading and concurrency to perform better on Java interview. You can find some interesting thread question below which is no doubt highly popular 1) 2) 3) 4) 5) 6) 7) 8) 9) ? 10) 10) Difference between green thread and native thread in Java? Difference between thread and process? What is context switching in multi-threading? Difference between deadlock and livelock, deadlock and starvation? What thread-scheduling algorithm is used in Java? What is thread-scheduler in Java? How do you handle un-handled exception in thread? What is thread-group, why its advised not to use thread-group in Java? Why Executor framework is better than creating and managing thread by application Difference between Executor and Executors in Java? How to find which thread is taking maximum cpu in windows and Linux server?

Apart from practicing these question answers, more important is to understand the concept behind these multithreading questions simply mugging the answers of these thread interview questions is not going to help because there would be a lot of follow-ups based upon your answer and if you haven't master the particular thread topic it would be difficult to answer them.

Singleton pattern in Java is one of the most common patterns available and its also used heavily in core Java libraries. Questions from Singleton pattern is very common in Java interviews and good knowledge of how to implement Singleton pattern certainly help.This is also one of my favorite design pattern interview question and has lots of interesting follow-up to dig into details , this not only check the knowledge of design pattern but also check coding, multithreading aspect which is very important while working for a real life application. In this post have listed some of the most common question asked on Singleton pattern during a Java Interview. I have not provided the answers of these questions as they are easily available via google search but if you guys need I can try to modify this tutorial to include answers as well. As promised earlier and having received lot of request for providing answers of these question, I have decided to update this post along with answers. By the way if you are preparing for interview on Java technology than you can check my collection on Java interview questions and multi-threading interview questions. There are lot of resources in Javarevisited which can help you in your interview preparation. On the other hand if you are more interested on design pattern tutorials than you can check my post on builder design pattern and decorator pattern.

10 interview question on Singleton Pattern in Java


Question starts with What is Singleton class? Have you used Singleton before? Singleton is a class which has only one instance in whole application and provides a getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.

13

1) Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java? Here they will check whether candidate has enough experience on usage of singleton or not. Does he is familiar of advantage/disadvantage or alternatives available for singleton in Java or not. Answer: Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class , since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application, if you want to show popup with message you can have one PopUp class on whole GUI application and anytime just get its instance, and call show() with message. 2) Can you write code for getInstance() method of a Singleton class in Java? Most of the java programmer fail here if they have mugged up the singleton code because you can ask lots of followup question based upon the code they have written. I have seen many programmer write Singleton getInstance() method with double checked locking but they are not really familiar with the caveat associated with double checking of singleton prior to Java 5. Answer: Until asked dont write code using double checked locking as it is more complex and chances of errors are more but if you have deep knowledge of double checked locking, volatile variable and lazy loading than this is your chance to shine. I have shared code examples of writing singleton classes using enum, using static factory and with double checked locking in my recent post Why Enum Singletons are better in Java, please see there.

3) Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer? This is really nice question and I mostly asked to just quickly check whether candidate is aware of performance trade off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the time its just read only access so locking of critical section is always better option. read more about synchronization on How Synchronization works in Java Answer: This is again related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to getInstance() will be synchronized and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton, Its better to only synchronize critical section and not whole method. Singletonpattern is also closely related to factory design pattern where getInstance() serves as static factory method. 4) What is lazy and early loading of Singleton and how will you implement it? This is another great Singleton interview question in terms of understanding of concept of loading and cost associated with class loading in Java. Many of which I have interviewed not really familiar with this but its good to know concept. Answer: As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory. 5) Example of Singleton in standard Java Development Kit? This is open question to all, please share which classes are Singleton in JDK. Answer to this question is java.lang.Runtime Answer: There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:

Java.lang.Runtime with getRuntime() method Java.awt.Toolkit with getDefaultToolkit() Java.awt.Desktop with getDesktop()

6) What is double checked locking in Singleton? One of the most hyped question on Singleton pattern and really demands complete understanding to get it right because of Java Memory model caveat prior to Java 5. If a guy comes up with a solution of using volatile keyword with Singleton instance and explains it then it really shows it has in depth knowledge of Java memory model and he is constantly updating his Java knowledge.

14

Answer: Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization. public static Singleton getInstance(){ if(_INSTANCE == null){ synchronized(Singleton.class){ //double checked locking - because second check of Singleton instance with lock if(_INSTANCE == null){ _INSTANCE = new Singleton(); } } } return _INSTANCE; } Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable. 7) How do you prevent for creating another instance of Singleton using clone() method? This type of questions generally comes some time by asking how to break singleton or when Singleton is not Singleton in Java. Answer: Preferred way is not to implement Clonnable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as Can not create clone of Singleton class. 8) How do you prevent for creating another instance of Singleton using reflection? Open to all. In my opinion throwing exception from constructor is an option. Answer: This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as Singleton already initialized

9) How do you prevent for creating another instance of Singleton during serialization? Another great question which requires knowledge of Serialization in Java and how to use it for persisting Singleton classes. This is open to you all but in my opinion use of readResolve() method can sort this out for you. Answer: You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance. I have shared code on how to do it in my post Enum as Singleton in Java. This is also one of the reason I have said that use Enum to create Singleton because serialization of enum is taken care by JVM and it provides guaranteed of that. 10) When is Singleton not a Singleton in Java? There is a very good article present in Sun's Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible. Here is the link of that article http://java.sun.com/developer/technicalArticles/Programming/singletons/

Apart from these questions on Singleton pattern, some of my reader contribute few more questions, which I included here. Thank you guys for your contribution. 11) Why you should avoid the singleton anti-pattern at all and replace it with DI? Answer: Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container. Singleton Anti-Pattern: with more and more classes calling getInstance the code gets more and more tightly coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden

15

dependencies. Also, there would be no need for this clumsy double checked locking if you call getInstance less often (i.e. once). 12) How many ways you can write Singleton Class in Java? Answer: I know at least four ways to implement Singleton pattern in Java 1) Singleton by synchronizing getInstance() method 2) Singleton with public static final field initialized during class loading. 3) Singleton generated by static nested class, also referred as Singleton holder pattern. 4) From Java 5 on-wards using Enums 13) How to write thread-safe Singleton in Java? Answer: Thread safe Singleton usually refers to write thread safe code which creates one and only one instance of Singleton if called by multiple thread at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using Enum or Singleton initialized by class loader. At last few more questions for your practice, contributed by Mansi: 14) Singleton vs Static Class? 15) When to choose Singleton over Static Class? 16) Can you replace Singleton with Static Class in Java? 17) Difference between Singleton and Static Class in java? 18) Advantage of Singleton over Static Class?

How to avoid deadlock in Java Threads


How to avoid deadlock in Java is one of the question which is flavor of the season for multithreading , asked more at a senior level and with lots of follow up questions , though question looks very basic but most of developer get stuck once you start going deep. questions starts with "What is deadlock ?" answer is simple , when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multitasking. How do you detect deadlock in Java ? though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful. other way is to find it when you actually get locked while running the application , try to take thread dump , in Linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object. other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object. once you answer this , they may ask you to write code which will result in deadlock ? here is one of my version
public void method1(){

16

synchronized(String.class){ System.out.println("Aquired lock on String.class object"); synchronized (Integer.class) { System.out.println("Aquired lock on Integer.class object"); } } } public void method2(){ synchronized(Integer.class){ System.out.println("Aquired lock on Integer.class object"); synchronized (String.class) { System.out.println("Aquired lock on String.class object"); } } } If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock because if thead 1 aquires lock on Sting object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen. now interviewer comes to final part , one of the most important in my view , How to fix deadlock ? or How to avoid deadlock in Java ? if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is the fixed version.

public void method1(){ synchronized(Integer.class){ System.out.println("Aquired lock on Integer.class object"); synchronized (String.class) { System.out.println("Aquired lock on String.class object"); } } } public void method2(){ synchronized(Integer.class){ System.out.println("Aquired lock on Integer.class object"); synchronized (String.class) { System.out.println("Aquired lock on String.class object"); } } }

17

Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thread A acquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further. hope this would be useful.

Difference between Singleton Pattern vs Static Class in Java


Singleton pattern vs Static Class (a class, having all static methods) is another interesting questions, which I missed while blogging about Interview questions on Singleton pattern in Java. Since both Singleton pattern and static class provides good accessibility, and they share some similarities e.g. both can be used without creating object and both provide only one instance, at very high level it looks that they both are intended for same task. Because of high level similarities, interviewer normally ask questions like, Why you use Singleton instead of Static Methods, or Can you replace Singleton with static class, and what are differences between Singleton pattern and static in Java. In order to answerthese question, its important to remember fundamental difference between Singleton pattern and static class, former gives you an Object, while later just provide static methods. Since an object is always much more capable than a method, it can guide you when to use Singleton pattern vs static methods.

In this Java article we will learn, where to use Singleton pattern in Java, and when static class is better alternative. By the way, JDK has examples of both singleton and static, and that too very intelligently e.g. java.lang.Math is a final class with full of static methods, on the other hand java.lang.Runtime is a Singleton class in Java. For those who are not familiar with Singleton design pattern or static class, static class is a Java class, which only contains static methods, good examples of static class is java.lang.Math,which contains lots of utility methods for various maths function e.g. sqrt(). While Singleton classes are those, which has only one instance during application life cycle likejava.lang.Runtime.

When to use Static Class in place of Singleton in Java


Indeed there are some situations, where static classes makes sense than Singleton. Prime example of this is java.lang.Math which is not Singleton, instead a class with all static methods. Here are few situation where I think using static class over Singleton pattern make sense:

1) If your Singleton is not maintaining any state, and just providing global access to methods, than consider using static class, as static methods are much faster than Singleton, because of static binding during compile time. But remember its not advised to maintain state inside static class, especially in concurrent environment, where it could lead subtle race conditions when modified parallel by multiple threads without adequate synchronization.

18

You can also choose to use static method, if you need to combine bunch of utility method together. Anything else, which requires singles access to some resource, should use Singleton design pattern.

Difference between Singleton vs Static in Java


This is answer of our second interview question about Singleton over static. As I said earlier, fundamental difference between them is, one represent object while other represent a method. Here are few more differences between static and singleton in Java.

1) Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.

2) One more difference between Singleton and static is, ability to override. Since static methods in Java cannot be overridden, they leads to inflexibility. On the other hand, you can override methods defined in Singleton class by extending it.

3) Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to mock and thus easy to test. Its easier to write JUnit test for Singleton than static classes, because you can pass mock object whenever Singleton is expected, e.g. into constructor or as method arguments.

4) If your requirements needs to maintain state than Singleton pattern is better choice than static class, because maintaining state in later case is nightmare and leads to subtle bugs.

5) Singleton classes can be lazy loaded if its an heavy object, but static class doesn't have such advantages and always eagerly loaded.

6) Many Dependency Injection framework manages Singleton quite well e.g. Spring, which makes using them very easy.

These are some differences between static class and singleton pattern, this will help to decide between two, which situation arises. In next section we will when to choose Singleton pattern over static class in Java.

Advantage of Singleton Pattern over Static Class in Java


Main advantage of Singleton over static is that former is more object oriented than later. With Singleton, you can use Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different

19

implementations. If we talk about java.lang.Runtime, which is a Singleton in Java, call to getRuntime() method return different implementations based on different JVM, but guarantees only one instance per JVM, had java.lang.Runtime an static class, its not possible to return different implementation for different JVM.

Thats all on difference between Singleton and static class in Java. When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.

How to create thread safe Singleton in Java - Java Singleton Example


Thread safe Singleton means a Singleton class which returns exactly same instance even if exposed to multiple threads. Singleton in Java has been a classical design pattern like Factory method pattern or Decorator design pattern and has been used a lot even inside JDK like java.lang.Runtime is an example of Singleton class. Singleton patternensures that exactly one instance of class will remain in Java program at any time. In our last post 10 Interview questions on Singleton in Java we have discussed many different questions asked on Singleton pattern, One of them was writing Thread safe singleton in Java. Prior to Java 5 double checked locking mechanism is used to create thread-safe singleton in Java which breaks if one Thread doesn't see instance created by other thread at same time and eventually you will end up with more than one instance of Singleton class. From Java 5 onwards volatile variable guarantee can be used to write thread safe singleton by using double checked locking pattern. I personally don't prefer that way as there are many other simpler alternatives to write thread-safe singleton is available available like using static field to initialize Singleton instance or using Enum as Singleton in Java. Lets see example of both ways to create thread-safe Singleton in Java.

Java Singleton Example Thread safe Singleton in Java using Enum

This is one of the example of Enum which I missed while writing 10 Examples of Enum in Java. Using Enum to create Singleton is by far most simple and effective way to create thread-safe Singleton in Java, as threadsafety guarantee is provided by Java programming language itself. You don't need to bother about thread-safety issue. Since Enum instances are by default final in Java, it also provides safety against multiple instance due to serialization. One point worth remembering is that, when we talk about thread-safe Singleton, we are talking about thread-safety during instance creation of Singleton class and not when we call any method of Singleton class. If your Singleton class maintain any state and contains method to modify that state, you need to write code to avoid and thread-safety and synchronization issues. Any way here is code example of creating thread safe Singleton in Java using Enum.

public enum Singleton{ INSTANCE; public void show(){

20

System.out.println("Singleton using Enum in Java"); } }

//You can access this Singleton as Singleton.INSTANCE and call any method like below Singleton.INSTANCE.show();

If this suits your need than this is the most easy way of writing thread-safe Singleton in Java. Using Enum as Singleton also provide couple of more benefits which you can find out on Why Enum Singleton are better in Java.

Java Singleton Example - Thread Safe Singleton using Static field Initialization
You can also create thread safe Singleton in Java by creating Singleton instance during class loading. static fields are initialized during class loading and Classloader will guarantee that instance will not be visible until its fully created. Here is example of creating thread safe singleton in Java using static factory method. Only disadvantage of this implementing Singleton patter using static field is that this is not a lazy initialization and Singleton is initialized even before any clients call there getInstance() method.

public class Singleton{ private static final Singleton INSTANCE = new Singleton(); private Singleton(){ } public static Singleton getInstance(){ return INSTANCE; } public void show(){ System.out.println("Singleon using static initialization in Java"); } }

//Here is how to access this Singleton class Singleton.getInstance().show();

here we are not creating Singleton instance inside getInstance() method instead it will be created by ClassLoader. Also private constructor makes impossible to create another instance , except one case. You can still

21

access private constructor by reflection and calling setAccessible(true). By the way You can still prevent creating another instance of Singleton by this way by throwing Exception fromconstructor.

That's all on how to create thread safe Singleton in Java. Both the approach are safe with thread-safety issue but my personal favorite is using Enum because of its simplicity, prevention of multiple instance against Serialization attack and concise code.

Interview Question on Hibernate Framework

Here is my list of Hibernate interview question, which I have collected from friends and colleagues. Hibernate is a popular Object Relational Mapping framework and good knowledge of advantages offered by Hibernate along with Hibernate Session API is key to do well in any Hibernate Interview. Difference between get and load in Hibernate? get vs load is one of the most frequently asked Hibernate Interview question, since correct understanding of both get() and load() is require to effectively using Hibernate. Main difference between get and load is that, get will hit the database if object is not found in the cache and returned completely initialized object, which may involve several database call while load() method can return proxy, if object is not found in cache and only hit database if any method other than getId() is called. This can save lot of performance in some cases. You can also see difference between get and load in Hibernate for more differences and detailed discussion on this question.

Difference between save, persist and saveOrUpdate methods in Hibernate? After get vs load, this is another Hibernate Interview question which appears quite often. All three methods i.e. save(), saveOrUpdate() and persist() is used to save objects into database, but has subtle differences e.g. save() can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records. Also, return type of save() is a Serializable object, while return type of persist() method is void. You can also check save vs persist vs saveOrUpdate for complete differences between them in hibernate.

What is named SQL query in Hibernate? This Hibernate Interview question is related to query functionality provided by Hibernate. Named queries are SQL queries which are defined in mapping document using <sql-query> tag and called using Session.getNamedQuery() method. Named query allows you to refer a particular query by the name you provided, by the way you can define named query in hibernate either by using annotations or xml mapping file, as I said above. @NameQuery is used to define single named query and @NameQueries is used to define multiple named query in hibernate.

What is SessionFactory in Hibernate? is SessionFactory thread-safe? Another common Interview questions related to Hibernate framework. SessionFactory as name suggest is a factory to create hibernate Session objects. SessionFactory is often built during start-up and used by application code to get session object. It acts as single data store and its also thread-safe so that multiple thread can use same SessionFactory. Usually a Java JEE application has just one SessionFactory, and individual threads, which are servicing clients request obtain hibernate Session instances from this factory, thats why any implementation of SessionFactory interface must be thread-safe. Also internal state of SessionFactory, which contains all meta data about Object/Relational mapping is Immutable and can not be changed once created.

22

What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate? This is usually asked as follow-up question of previous Hibernate Interview question. After SessionFactory its time for Session. Session represent a small unit of work in Hibernate, they maintain connection with database and they are not thread-safe, it means you can not share Hibernate Session between multiple threads. Though Session obtains database connection lazily it's good to close session as soon as you are done with it.

What is difference between sorted and ordered collection in hibernate? This is one of the easy Hibernate interview question you ever face. A sorted collection is sorted in memory by using Java Comparator, while a ordered collection uses database's order by clause for ordering. For large data set it's better to use ordered collection to avoid any OutOfMemoryError in Java, by trying to sort them in memory.

What is difference between transient, persistent and detached object in Hibernate? In Hibernate, Object can remain in three state transient, persistent or detached. An object which is associated with Hibernate session is called persistent object. Any change in this object will reflect in database based upon your flush strategy i.e. automatic flush whenever any property of object change or explicit flushing by calling Session.flush() method. On the other hand if an object which is earlier associated with Session, but currently not associated with it are called detached object. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session. Transient objects are newly created instance of persistence class, which is never associated with any Hibernate Session. Similarly you can call persist() or save() methods to make transient object persistent. Just remember, here transient doesnt represent transient keyword in Java, which is altogether different thing. What does Session lock() method do in Hibernate? This one is one of the tricky Hibernate Interview question, because Session's lock() method reattach object without synchronizing or updating with database. So you need to be very careful while using lock() method. By the way you can always use Session's update() method to sync with database during reattachment. Some time this Hibernate question is also asked as what is difference between Session's lock() and update() method. You can use this key point to answer that question as well. What is Second level Cache in Hibernate? This is one of the first interview question related to caching in Hibernate, you can expect few more. Second level Cache is maintained at SessionFactory level and can improve performance by saving few database round trip. Another worth noting point is that second level cache is available to whole application rather than any particular session. What is query cache in Hibernate ? This question, Some times asked as a follow-up of last Hibernate Interview question, QueryCache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. Hibernate support various open source caching solution to implement Query cache e.g. EhCache.

Why it's important to provide no argument constructor in Hibernate Entities? Every Hibernate Entity class must contain a no argument constructor, because Hibernate framework creates instance of them using Reflection API, by calling Class.newInstance() method. This method will throw InstantiationException if it doesn't found no argument constructor inside Entity class. Can we make an Hibernate Entity Class final? Yes, you can make an Hibernate Entity class final, but that's not a good practice. Since Hibernate uses proxy pattern for performance improvement in case of lazy
23

association, by making an entity final, Hibernate will no longer be able to use proxy, because Java doesn't allow extension of final class, thus limiting your performance improvement options. Though, you can avoid this penalty, if your persistent class is an implementation of interface, which declares all public methods defined in Entity class.

Design pattern interview questions for Senior and experienced level


These are questions which not only relates to design patterns but also related to software design. These questions requires some amount of thinking and experience to answer. In most of the cases interviewer is not looking for absolute answers but looking for your approach, how do you think about a problem, do you able to think through, do you able to bring out things which are not told to you. This is where experience come in picture, What are things you consider while solving a problem etc. overall these design questions kicks off your thought process. Some time interviewer ask you to write code as well so be prepare for that. you can excel in these questions if you know the concept, example and application of your programming and design skill. 1. Give an example where you prefer abstract class over interface ? This is common but yet tricky design interview question. both interface and abstract class follow "writing code for interface than implementation" design principle which adds flexibility in code, quite important to tackle with changing requirement. here are some pointers which help you to answer this question: 1. In Java you can only extend one class but implement multiple interface. So if you extend a class you lost your chance of extending another class. 2. Interface are used to represent adjective or behavior e.g. Runnable, Clonable, Serializable etc, so if you use an abstract class to represent behavior your class can not be Runnable and Clonable at same time because you can not extend two class in Java but if you use interface your class can have multiple behavior at same time. 3. On time critical application prefer abstract class is slightly faster than interface. 4. If there is a genuine common behavior across the inheritance hierarchy which can be coded better at one place than abstract class is preferred choice. Some time interface and abstract class can work together also where defining function in interface and default functionality on abstract class. To learn more about interface in Java check my post 10 things to know about Java interfaces 2. Design a Vending Machine which can accept different coins, deliver different products? This is an open design question which you can use as exercise, try producing design document, code and Junit test rather just solving the problem and check how much time it take you to come to solution and produce require artifacts, Ideally this question should be solve in 3 hours, at least a working version. 3. You have a Smartphone class and will have derived classes like IPhone, AndroidPhone,WindowsMobilePhone can be even phone names with brand, how would you design this system of Classes . This is another design pattern exercise where you need to apply your object oriented design skill to come with a design which is flexible enough to support future products and stable enough to support changes in existing model. 4. When do you overload a method in Java and when do you override it ?

24

Rather a simple question for experienced designer in Java. if you see different implementation of a class has different way of doing certain thing than overriding is the way to go while overloading is doing same thing but with different input. method signature varies in case of overloading but not in case of overriding in java. 5. Design ATM Machine ? We all use ATM (Automated Teller Machine) , Just think how will you design an ATM ? for designing financial system one must requirement is that they should work as expected in all situation. so no matter whether its power outage ATM should maintain correct state (transactions), think about locking, transaction, error condition, boundary condition etc. even if you not able to come up exact design but if you be able to point out non functional requirement, raise some question , think about boundary condition will be good progress.

6. You are writing classes to provide Market Data and you know that you can switch to different vendors overtime like Reuters, wombat and may be even to direct exchange feed , how do you design your Market Data system. This is very interesting design interview question and actually asked in one of big investment bank and rather common scenario if you have been writing code in Java. Key point is you will have a MarketData interface which will have methods required by client e.g. getBid(), getPrice(), getLevel() etc and MarketData should be composed with a MarketDataProvider by using dependency injection. So when you change your MarketData provider Client won't get affected because they access method form MarketData interface or class. 7. Why is access to non-static variables not allowed from static methods in Java You can not access non-static data from static context in Java simply because non-static variables are associated with a particular instance of object while Static is not associated with any instance. You can also see my post why non static variable are not accessible in static context for more detailed discussion. 8. Design a Concurrent Rule pipeline in Java? Concurrent programming or concurrent design is very hot now days to leverage power of ever increasing cores in advanced processor and Java being a multi-threaded language has benefit over others. Do design a concurrent system key point to note is thread-safety, immutability, local variables and avoid using static or instance variables. you just to think that one class can be executed by multiple thread a same time, So best approach is that every thread work on its own data, doesn't interfere on other data and have minimal synchronization preferred at start of pipeline. This question can lead from initial discussion to full coding of classes and interface but if you remember key points and issues around concurrency e.g. race condition, deadlock, memory interference, atomicity, ThreadLocal variables etc you can get around it.

Beginners UNIX Interview Questions Answers


1. Write command to list all the links from a directory? In this UNIX command interview questions interviewer is generally checking whether user knows basic use of "ls" "grep" and regular expression etc You can write command like: ls -lrt | grep "^l"

2. Create a read-only file in your home directory? This is a simple UNIX command interview questions where you need to create a file and change its parameter to read-only by using chmod command you can also change your umask to create read only file.

25

touch file chmod 400 file

read more about file and directory permission in unix and linux here.
3. How will you find which operating system your system is running on in UNIX? By using command "uname -a" in UNIX

4. How will you run a process in background? How will you bring that into foreground and how will you kill that process? For running a process in background use "&" in command line. For bringing it back in foreground use command "fg jobid" and for getting job id you use command "jobs", for killing that process find PID and use kill -9 PID command. This is indeed a good Unix Command interview questions because many of programmer not familiar with background

process in UNIX.

5. How do you know if a remote host is alive or not? You can check these by using either ping or telnet command in UNIX. This question is most asked in various Unix command Interview because its most basic networking test anybody wants to do it.

6. How do you see command line history in UNIX? Very useful indeed, use history command along with grep command in unix to find any relevant command you have already executed. Purpose of this Unix Command Interview Questions is probably to check how familiar candidate is from available tools in UNIX operation system.

7. How do you copy

file from one host to other?

Many options but you can say by using "scp" command. You can also use rsync command to answer this UNIX interview question or even sftp would be ok.

8. How do you find which process is taking how much CPU? By using "top" command in UNIX, there could be multiple follow-up UNIX command interview questions based upon response of this because TOP command has various interactive options to sort result based upon various parameter.

9. How do you check how much space left in current drive ?

26

By using "df" command in UNIX. For example "df -h ." will list how full your current drive is. This is part of anyone day to day activity so I think this Unix Interview question will be to check anyone who claims to working in UNIX but not really working on it.

10. What is the difference between Swapping and Paging? Swapping: Whole process is moved from the swap device to the main memory for execution. Process size must be less than or equal to the available main memory. It is easier to implementation and overhead to the system. Swapping systems does not handle the memory more flexibly as compared to the paging systems. Paging: Only the required memory pages are moved to main memory from the swap device for execution. Process

size

does not matter. Gives the concept of the virtual memory. It provides greater flexibility in mapping the virtual
address space into the physical memory of the machine. Allows more number of processes to fit in the main memory simultaneously. Allows the greater process size than the available physical memory. Demand paging systems handle the memory more flexibly.

Intermediate UNIX Interview Questions Answers


1. What is difference between ps -ef and ps -auxwww?

This is indeed a good Unix Interview Command Question and I have faced this issue while ago where one culprit process was not visible by execute ps ef command and we are wondering which process is holding the file. ps -ef will omit process with very long command line while ps -auxwww will list those process as well.

2. How do you find how many cpu are in your system and there details? By looking into file /etc/cpuinfo for example you can use below command: cat /proc/cpuinfo

3. What is difference between HardLink and SoftLink in UNIX?

27

I have discussed this Unix Command Interview questions in my blog post difference between Soft link and Hard link in Unix

4. What is Zombie process in UNIX? How do you find Zombie process in UNIX? When a program forks and the child finishes before the parent, the kernel still keeps some of its information about the child in case the parent might need it - for example, the parent may need to check the child's exit status. To be able to get this information, the parent calls 'wait()'; In the interval between the child terminating and the parent calling 'wait()', the child is said to be a 'zombie' (If you do 'ps', the child will have a 'Z' in its status field to indicate this.) Zombie : The process is dead but have not been removed from the process table.

5. What is "chmod" command? What do you understand by this line r-- -w- --x?

6. There is a file some where in your system which contains word "UnixCommandInterviewQuestions How will find that file in Unix? By using find command in UNIX for details see here 10 example of using find command in Unix

7. In a file word UNIX is appearing many times? How will you count number? grep -c "Unix" filename

8. How do you set environment variable which will be accessible form sub shell? By using export for example export count=1 will be available on all sub shell.

9. How do you check if a particular process is listening on a particular port on remote host? By using telnet command for example telnet hostname port, if it able to successfully connect then some process is listening on that port. To read more about telnet read networking command in UNIX

10. How do you find whether your system is 32 bit or 64 bit ? Either by using "uname -a" command or by using "arch" command.

10 Interview questions on Serialization in Java


28

Most commercial project uses either database or memory mapped file or simply flat file for there persistence requirement and only few of them rely on serialization process in Java. Anyway this post is not a Java serialization tutorial or how to serialize object in java but about interview questions around serialization mechanism and Serialization API, Which is worth to have a look before going for any Java or J2EE interview and surprising yourself with some unknown contents. for those who are not familiar about java Serialization "Java serialization is the process which is used to serialize object in java by storing obj ects state into a file with extension .ser and recreating object's state from that file, this reverse process is called deserialization. The Java Serialization API provides a standard mechanism for developers to handle object serialization using Serializable and Externalizable interface. By the way this article is in continuation of my previous article Top 20 design pattern interview questions, Top 15 multi-threading interview question in Java and 10 Interview questions on Singleton Pattern in Java So here we go. What is Serialization in Java

Object Serialization in Java is a process used to convert Object into a binary format which can be persisted into disk or sent over network to any other running Java virtual machine; the reverse process of creating object from binary stream is called deserialization in Java. Java provides Serialization API for serializing and deserializing object which includesjava.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStr eam etc. Java programmers are free to use default Serialization mechanism which Java uses based upon structure of class but they are also free to use there own custom binary format, which is often advised as Serialization best practice, Because serialized binary format becomes part of Class's exported API and it can potentially break Encapsulation in Java provided by private and package-private fields. This pretty much answer the question What is Serialization in Java. How to make a Java class Serializable? Making a class Serializable in Java is very easy, Your Java class just needs to implements java.io.Serializable interface and JVM will take care of serializing object in default format. Decision to making a Class Serializable should be taken concisely because though near term cost of making a Class Serializable is low, long term cost is substantial and it can potentially limit your ability to further modify and change its implementation because like any public API, serialized form of an object becomes part of public API and when you change structure of your class by implementing addition interface, adding or removing any field can potentially break default serialization, this can be minimized by using a custom binary format but still requires lot of effort to ensure backward compatibility. One example of How Serialization can put constraints on your ability to change class is SerialVersionUID. If you don't explicitly declare SerialVersionUID then JVM generates its based upon structure of class which depends upon interfaces a class implements and several other factors which is subject to change. Suppose you implement another interface than JVM will generate a different SerialVersionUID for new version of class files and when you try to load old object object serialized by old version of your program you will get InvalidClassException.

1) What is the difference between Serializable and Externalizable interface in Java? This is most frequently asked question in Java serialization interview. Here is my version Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically. 2) How many methods Serializable has? If no method then what is the purpose of Serializable interface?

29

Serializable interface exists in java.io package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface in Java. When your class implements java.io.Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.

3) What is serialVersionUID? What would happen if you don't define this? One of my favorite question interview question on Java serialization. SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . SerialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.

4) While serializing you want some of the members not to serialize? How do you achieve it? Another frequently asked Serialization interview question. This is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during Java serialization process. 5) What will happen if one of the members in the class doesn't implement Serializable interface? One of the easy question about Serialization process in Java. If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a NotSerializableException will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) , one of the code comment best practices, to instruct developer to remember this fact while adding a new field in a Serializable class.

6) If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization? Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java and values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. Once the constructor chaining will started it wouldn't be possible to stop that , hence even if classes higher in hierarchy implements Serializable interface , there constructor will be executed. As you see from the statement this Serialization interview question looks very tricky and tough but if you are familiar with key concepts its not that difficult. 7) Can you Customize Serialization process or can you override default Serialization process in Java? The answer is yes you can. We all know that for serializing an object ObjectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject() is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization and deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal. In my opinion this is one of the best question one can ask in any Java Serialization interview, a good follow-up question is why should you provide custom serialized form for your object? 8) Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized? One of the tricky interview question in Serialization in Java. If Super Class of a Class already implements Serializable interface in Java then its already Serializable in Java, since you can not

30

unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject()and readObject() method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above Serialization interview question and normally it asked as follow-up question as interview progresses. 9) Which methods are used during Serialization and DeSerialization process in java? This is very common interview question in Serialization basically interviewer is trying to know; Whether you are familiar with usage of readObject(), writeObject(), readExternal() and writeExternal () or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call ObjectOutputStream.writeObject(saveThisobject) and to deserialize that object we call ObjectInputStream.readObject() method. Call to writeObject() method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be casted on correct type. 10) Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized? It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally its equal to hashCode of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.

11) What are the compatible changes and incompatible changes in Java Serialization Mechanism? The real challenge lies with change in class structure by adding any field, method or removing any field or method is that with already serialized object. As per Java Serialization specification adding any field or method comes under compatible change and changing class hierarchy or UN-implementing Serializable interfaces some under non compatible changes. For complete list of compatible and non compatible changes I would advise reading Java serialization specification. 12) Can we transfer a Serialized object vie network? Yes you can transfer a Serialized object via network because java serialized object remains in form of bytes which can be transmitter via network. You can also store serialized object in Disk or database as Blob. 13) Which kind of variables is not serialized during Java Serialization? This question asked sometime differently but the purpose is same whether Java developer knows specifics about static and transient variable or not. Since static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process. As Java Serialization only persist state of object and not object itself. Transient variables are also not included in java serialization process and are not the part of the objects serialized state. After this question sometime interviewer ask a follow -up if you don't store values of these variables then what would be value of these variable once you deserialize and recreate those object? This is for you guys to think about :)

Java Collection Interview Questions Answers


How HashMap works in Java? This is Classical Java Collection interview questions which I have also discussed in How HashMap works in Java. This collection interview questions is mostly asked during AVP Role interviews on Investment-Banks and has lot of followup questions based on response of interviewee e.g. Why

31

HashMap keys needs to be immutable, what is race conditions on HashMap and how HashMap resize in Java. For explanation and answers of these questions Please see earlier link. What is difference between fail-fast and fail-safe Iterators? This is relatively new collection interview questions and can become trick if you hear the term fail-fast and fail-safe first time. Fail-fast Iterators throws ConcurrentModificationException when one Thread is iterating over collection object and other thread structurally modify Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because they try to immediately throw Exception when they encounter failure. On the other hand fail-safe Iterators works on copy of collection instead of original collection

What is difference between Synchronized Collection and ConcurrentCollection? Java5 has added several new ConcurrentCollection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue etc, which has made Interview questions on Java Collection even trickier. Java Also provided way to get Synchronized copy of collection e.g. ArrayList, HashMap by using Collections.synchronizedMap() Utility function.One Significant difference is that ConccurentCollections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization. See Difference between SynchronizedCollection and ConcurrentCollection in Java for more details.

What is difference between Iterator and Enumeration? This is a beginner level collection interview questions and mostly asked during interviews of Junior Java developer up to experience of 2 to 3 years Iterator duplicate functionality of Enumeration with one addition of remove() method and both provide navigation functionally on objects of Collection.Another difference is that Iterator is more safe than Enumeration and doesn't allow another thread to modify collection object during iteration except remove() method and throws ConcurrentModificaitonException. See Iterator vs Enumeraiton in Java for more differences.

Difference between HashMap and Hashtable? This is another Classical Java Collection interview asked on beginners level and most of Java developer has a predefined answer for this interview questions e.g. HashMap is not synchronized while hashtalbe is not or hashmap is faster than hashtable etc. What could go wrong is that if he placed another followup question like how hashMap works in Java orcan you replace Hashtable with ConcurrenthashMap etc. See HashTable vs HashMap in Java for detailed answer of this interview question. When do you use ConcurrentHashMap in Java? This is another advanced level collection interview questions in Java which normally asked to check whether interviewer is familiar with optimization done on ConcurrentHashMap or not. ConcurrentHashMap is better suited for situation where you have multiple readers and one Writer or fewer writers since Map gets locked only during write operation. If you have equaled number of reader and writer than ConcurrentHashMap will perform in line of hashtable or synchronized hashMap. What is difference between Set and List in Java? Another classical Java Collection interview popular on telephonic round or first round of interview. Most of Java programmer knows that Set doesn't allowed duplicate while List does and List maintains insertion order while Set doesn't. What is key here is to show interviewer that you can decide which collection is more suited based on requirements. How do you Sort objects on collection?

32

This Collection interview question serves two purpose it not only test an important programming concept Sorting but Also utilty class like Collections which provide several methods for creating synchronized collection and sorting. Sorting is implemented using Comparable and Comparator in Java and when you call Collections.sort() it gets sorted based on natural order specified in CompareTo method while Collections.sort(Comparator) will sort objects based on compare() method of Comparator. See Sorting in Java using Comparator and Comparable for more details.

What is difference between Vector and ArrayList? One more beginner level collection interview questions, this is still very popular and mostly asked in telephonic round. ArrayList in Java is one of the most used Collection class and most interviewer asked questions on ArrayList.See Difference between Vector and ArrayList for answer of this interview question.

What is difference between HashMap and HashSet? This collection interview questions is asked in conjunction with hashmap vs hashtable. See HashMap vs HashSet for detail Answer.

Question 1: What is Struts? Why you have used struts in your application or project.

Ans: This is the first interview questions anyone asks in Struts to get the interview rolling. Most commonly asked during less senior level. Struts is nothing but open source framework mostly used for making web application whenever we use the term framework means it comprises JSP ,servlet ,custom tags message resources all in one bundle which makes developer task very easy. Its is based on MVC pattern which is model view Controller pattern.

Now why we use Struts? So main reason is if we go with servlet all HTML code which is related with design part mostly will come inside java code which makes code unmaintainable and complex similarly if use JSP, all java code related with business come inside design part which again make code complex, thats why MVC pattern come into existence and which separate the business, design and controller and struts was made based upon this pattern and easy to develop web application. The keyword to answer this Struts interview questions is MVC design pattern, Front Controller Pattern and better flow management which mostly interviewer are looking to hear. You can read more design pattern interview question on my post 10 Interview question on Singleton Pattern in Java

Question 2: What are the main classes which are used in struts application? Ans 2: This is another beginners level Struts interview question which is used to check how familiar candidate is with Struts framework and API. Main classes in Struts Framework are:

33

Action servlet: its a back-bone of web application its a controller class responsible for handling the entire request. Action class: using Action classes all the business logic is developed us call model of the application also. Action Form: its a java bean which represents our forms and associated with action mapping. And it also maintains the session state its object is automatically populated on the server side with data entered from a form on the client side. Action Mapping: using this class we do the mapping between object and Action. ActionForward: this class in Struts is used to forward the result from controller to destination.

Question 3: How exceptions are handled in Struts application?

Ans: This is little tough Struts interview question though looks quite basic not every candidate knows about it. Below is my answer of this interview questions on Struts:

There are two ways of handling exception in Struts:

Programmatically handling: using try {} catch block in code where exception can come and flow of code is also decided by programmer .its a normal java language concept.

Declarative handling: There are two ways again either we define <global-Exception> tag inside struts config.xml file

<exception key="stockdataBase.error.invalidCurrencyType" path="/AvailbleCurrency.jsp" type="Stock.account.illegalCurrencyTypeException"> </exception>

Programmatic and Declarative way is some time also asked as followup questions given candidates response on knowledge on Struts.

34

Key: The key represent the key present in MessageResource.properties file to describe the exception. Type: The class of the exception occurred. Path: The page where the controls are to be followed is case exception occurred.

Question 4: How validation is performed in struts application?

Ans: Another classic Struts interview question its higher on level than previous interview questions because its related to important validation concept on web application. In struts validation is performed using validator framework, Validator Framework in Struts consist of two XML configuration files.

1. validator-rules.xml file: which contains the default struts pluggable validator definitions. You can add new validation rules by adding an entry in this file. This was the original beauty of struts which makes it highly configurable. 2. Validation.xml files which contain details regarding the validation routines that are applied to the different Form Beans.

These two configuration file in Struts should be place somewhere inside the /WEB-INF folder of the application to keep it safe from client and make it available in Classpath.

<!-- Validator plugin --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/> </plug-in> Now the next step towards validation is create error messages inside the message resource property file which is used by validator framework. Message resource Contain: 1. CurrencyConverterForm.fromCurrency = From Currency 2. CurrencyConverterForm.toCurrency=To currency 3. errors.required={0} is required.

35

Then validation rules are defined in validation.xml for the fields of form on which we want desire validation

Form bean code that extend DynaValidatorForm Eg; <form-beans> <form-bean name="CurrencyConverterForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="fromCurrency" type="java.lang.double" /> <form-property name="toCurrecny" type="java.lang.double" /> </form-bean> </form-beans>

Validation.xml file contains

<form-validation> <formset> <form name=" CurrencyConverterForm "> <field property=" fromCurrency " depends="required"> <arg key=" CurrencyConverterForm. fromCurrency "/> </field> <field property=" toCurrecny " depends="required "> <arg key=" CurrencyConverterForm.toCurrency "/> </field> </form> </formset> </form-validation>

To associate more than one validation rule to the property we can specify a comma-delimited list of values. The first rule in the list will be checked first and then the next rule and so on. Answer of this Struts questions gets bit longer but its important to touch these important concept to make it useful.

36

Top 10 Interview Questions asked in Struts


Question 5: What is the Difference between DispatchAction and LookupDispatchAction in Struts Framework?

This Struts interview questions is pretty straight forward and I have put the differences in tabular format to make it easy to read.

Dispatch Action

LookupDispatchAction

Its a parent class of LookupDispatchAction DispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create separate actions for each function.

Subclass of Dispatch Action An abstract Action that dispatches to the subclass mapped executes method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. Lookup Dispatch Action is useful when we are using Internalization functionality

If not using Internalization functionality then dispatch action is more useful.

DispatchAction selects the method to execute depending on the request parameter value which is configured in the xml file.

LookupDispatchAction looks into the resource bundle file and find out the corresponding key name. We can map this key name to a method name by overriding the getKeyMethodMap() method. LookupDispatchAction is used for I18N

DispatchAction is not useful for I18N

Question 6: How you can retrieve the value which is set in the JSP Page in case of DynaActionForm?

37

Ans: DynaActionForm is a popular topic in Struts interview questions. DynaActionForm is subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time.

For Example: we have a CurrencyConverterForm and we don't want a java class. CurrencyConverterForm has properties fromCurrency, toCurrency in the struts-config.xml file, declare the form bean <form-bean name=" CurrencyConverterForm " type="org.apache.struts.action.DynaActionForm"> <form-property name=" fromCurrency " type="java.lang.String"/> <form-property name=" toCurrency " type="java.lang. String "/> </form-bean> Add action mapping in the struts-config.xml file: <action path="/convertCurrency" type="com.techfaq.action.ConvertCurrencyAction" name=" CurrencyConverterForm " scope="request" validate="true" input="/pages/ currencyConverterform.jsp"> <forward name="success" path="/jsp/success.jsp"/> <forward name="failure" path="/jsp/error.jsp" /> </action> In the Action class. public class ConvertCurrencyAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ DynaActionForm currencyConverterForm = (DynaActionForm)form;

// by this way we can retrieve the value which is set in the JSP Page

String fromCurrency = (String) currencyConverterForm.get("fromCurrency "); String toCurrency = (String) currencyConverterForm.get("toCurrency "); return mapping.findForward("success"); } }

38

} In the JSP page

<html:text property=" fromCurrency " size="30" maxlength="30"/> <html:text property=" toCurrency " size="30" maxlength="30"/>

Question 7: what the Validate () and reset () method does?

Ans: This is one of my personal favorite Struts interview questions. validate() : validate method is Used to validate properties after they have been populated, and this ,method is Called before FormBean is passed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method. public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if ( StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)){ errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.usernamepassword.required")); } return errors; }

reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set. Example : public void reset(ActionMapping mapping, HttpServletRequest request) { this.password = null; this.username = null; } Set null for every request.

Question 8: How you will make available any Message Resources Definitions file to the Struts Framework Environment?

Ans: Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to

39

the struts-config.xml file through < message-resources / > tag. Example: < message-resources parameter= MessageResources / >

Message resource definition files can available to the struts environment in two ways 1. using web.xml as <servlet> <servlet-name>action<servlet-name> servlet-class>org.apache.struts.action.ActionServlet<servlet-class> <init-param> <param-name>application<param-name> <param-value>resource.Application<param-value> </servlet> 2. <message-resource key="myResorce" parameter="resource.Application" null="false">

Question 9: What configuration files are used in Struts? Ans: ApplicationResources.properties and struts-config.xml these two files are used to between the Controller and the Model.

Question 10: Explain Struts work Flow? Ans: Some time this Struts interview questions asked as first questions but I recall this now . Here is the answer of this Struts interview questions 1) A request comes in from a Java Server Page into the ActionServlet. 2) The ActionServlet having already read the struts-config.xml file, knows which form bean relates to this JSP, and delegates work to the validate method of that form bean.

3) The form bean performs the validate method to determine if all required fields have been entered, and performs whatever other types of field validations that need to be performed.

4) If any required field has not been entered, or any field does not pass validation, the form bean generates ActionErrors, and after checking all fields returns back to the ActionServlet.

5) The ActionServlet checks the ActionErrors that were returned from the form beans validate method to determine if any errors have occurred. If errors have occurred, it returns to the originating JSP displaying the appropriate errors.

40

6) If no errors occurred in the validate method of the form bean, the ActionServlet passes control to the appropriate Action class.

7) The Action class performs any necessary business logic, and then forwards to the next appropriate action (probably another JSP).

Java Exception and Error Interview Questions


Here is my list of frequently asked questions from Java Error and Exception topics in various programming interviews to Java and J2EE developers. I have also shared my answers for these questions for quick revision, and provided source for more in depth understanding. I have tried to include questions of various difficulty level, including simplest of simple for freshers and some tricky questions for senior Java developers. If you think, there is a good question, which is not included in this list, please feel free to share it via comment. You can also share error handling questions asked to you on interviews or any question, for which you dont know the answer.

1) What is Exception in Java? This is always been first interview question on Exception and mostly asked on fresher level interviews. I haven't seen anybody asking about what is Exception in senior and experienced level interviews, but this is quite popular at entry level. In simple word Exception is Javas way to convey both system and programming errors. In Java Exception feature is implemented by using class like Throwable, Exception,RuntimeException and keywords like throw, throws, try, catch and finally. All Exception are derived form Throwable class. Throwable further divides errors in too category one is java.lang.Exception and other is java.lang.Error. java.lang.Error deals with system errors like java.lang.StackOverFlowError or Java.lang.OutOfMemoryError while Exception is mostly used to deal with programming mistakes, non availability of requested resource etc. 2) What is difference between Checked and Unchecked Exception in Java ? This is another popular Java Exception interview question appears in almost all level of Java interviews. Main difference between Checked and Unchecked Exception lies in there handling. Checked Exception requires to be handled at compile time using try, catch and finally keywords or else compiler will flag error. This is not a requirement for Unchecked Exceptions. Also all exceptions derived from java.lang.Exception classes are checked exception, exception those which extends RuntimeException, these are known as unchecked exception in Java. You can also check next article for more differences between Checked and Unchecked Exception. 3) What is similarity between NullPointerException and ArrayIndexOutOfBoundException in Java? This is Java Exception interview question was not very popular, but appears in various fresher level interviews, to see whether candidate is familiar with concept of checked and unchecked exception or not. By the way answer of this interview question is both of them are example of unchecked exception and derived form RuntimeException. This question also opens door for difference of array in Java and C programming language, as arrays in C are unbounded and never throw ArrayIndexOutOfBoundException. 4) What best practices you follow while doing Exception handling in Java ? This Exception interview question in Java is very popular while hiring senior java developer of Technical Lead. Since exception handling is crucial part of project design and good knowledge of this is desirable. There are lot of best practices, which can help to make your code robust and flexible at same time, here are few of them:

41

1) Returning boolean instead of returning null to avoid NullPointerException at callers end. Since NPE is most infamous of all Java exceptions, there are lot of techniques and coding best practices to minimize NullPointerException. You can check that link for some specific examples. 2) Non empty catch blocks. Empty catch blocks are considered as one of the bad practices in Exception handling because they just ate Exception without any clue, at bare minimum print stack trace but you should do alternative operation which make sense or defined by requirements. 3) Prefer Unchecked exception over checked until you have a very good reason of not to do so. it improves readability of code by removing boiler plate exception handling code . 4) Never let your database Exception flowing till client error. since most of application deal with database and SQLException is a checked Exception in Java you should consider handling any database related errors in DAO layer of your application and only returning alternative value or something meaningful RuntimeException which client can understand and take action. 5) calling close() methods for connections, statements, and streams on finally block in Java. I have already shared lot of these in my post Top 10 Java exception handling best practices, you can also refer that for more knowledge on this topic. 5) Why do you think Checked Exception exists in Java, since we can also convey error using RuntimeException ? This is a controversial question and you need to be careful while answering this interview question. Though they will definitely like to hear your opinion, what they are mostly interested in convincing reason. One of the reason I see is that its a design decision, which is influenced by experience in programming language prior to Java e.g. C++. Most of checked exceptions are in java.io package, which make sense because if you request any system resource and its not available, than a robust program must be able to handle that situation gracefully. By declaring IOException as checked Exception, Java ensures that your provide that gracefully exception handling. Another possible reason could be to ensuring that system resources like file descriptors, which are limited in numbers, should be released as soon as you are done with that using catch or finally block. Effective Java book from Joshua Bloch has couple of items in this topic, which is again worth reading. 6) What is difference between throw and throws keyword in Java? One more Java Exception interview questions from beginners kitty. throw and throws keyword may look quite similar, especially if you are new to Java programming and haven't seen much of it. Though they are similar in terms that both are used in Exception handling, they are different on how and where they are used in code. throws keyword is used in method signature to declare which checked exception method can throw, you can also declare unchecked exception, but that is not mandatory by compiler. This signifies lot of things like method is not going to handle Exception instead its throwing it, if method throws checked Exception then caller should provide compile time exception handling etc. On the other hand throw keyword is actually used to throw any Exception. Syntactically you can throw any Throwable (i.e.Throwable or any class derived from Throwable) , throw keyword transfers control of execution to caller so it can be used in place of return keyword. Most common example of using throw in place of return is throwing UnSupportedOperationException from an empty method as shown below : private static void show() { throw new UnsupportedOperationException("Not yet implemented"); } See this article for more differences between these two keywords in Java. 7) What is Exception chaining in Java? Exception chaining is a popular exception handling concept in Java, where another exception is thrown in response of an exception and creating a chain of Exceptions. This technique mostly used to wrap a checked exception into an unchecked or RuntimeException. By the way if you are throwing new exception due to another exception then

42

always include original exception so that handler code can access root cause by using methods like getCause() and initCause(). 8) Have you written your own custom Exception in Java? How do you do that? Ofcourse most of us has written custom or business Exceptions like AccountNotFoundExcepiton. Main purpose of asking this Java Exception interview question is to find out how you use this feature. This can be used for sophisticated and precise exception handling with tweak involved in whether you would choose a checked or unchecked exception. By creating a specific exception for specific case, you also gives lot of options to caller to deal with them elegantly. I always prefer to have a precise exception than a general exception. Though creating lots of specific exceptions quickly increase number of classes in your project, maintaining a practical balance between specific and general exceptions are key to success.

9) What changes has been introduced in JDK7 related to Exception handling in Java ? A relatively new and recent Exception interview question in Java. JDK7 has introduced two major feature which is related to Error and Exception handling, one is ability to handle multiple exception in one catch block, popularly known as multi cache block and other is ARM blocks in Java 7 for automatic resource management, also known as try with resource. Both of these feature can certainly help to reduce boiler plate code required for handling checked exceptions in Java and significantly improves readability of code. Knowledge of this feature, not only helps to write better error and exception code in Java, but also helps to do well during interviews. I also recommend reading Java 7 Recipes book to get more insight on useful features introduced in Java 7, including these two. 10) Have you faced OutOfMemoryError in Java? How did you solved that? This Java Error interview questions is mostly asked on senior level Java interviews and here interviewer is interested on your approach to tackle dangerous OutOfMemoryError. Admit it we always face this error no matter which kind of project you are working so if you say no it doesn't go very well with interviewer. I suggest even if you are not familiar or not faced it in reality but have 3 to 4 years of experience in Java, be prepare for it. At the same time, this is also a chance to impress interviewer by showing your advanced technical knowledge related to finding memory leaks, profiling and debugging. I have noticed that these skills almost always creates a positive impression. You can also see my post on how to fix java.lang.OutOfMemoryError for more detail on this topic. 11) Does code form finally executes if method returns before finally block or JVM exits ? This Java exception interview question can also be asked in code format, where given a code with System.exit() in try block and something in finally block. Its worth knowing that, finally block in Java executes even when return keyword is used in try block. Only time they dont execute is when you call JVM to exit by executing System.exit(0)from try block in Java.

12) What is difference in final, finalize and finally keyword in Java? Another classic interview question in core Java, this was asked to one of my friend on his telephonic interview for core Java developer with Morgan Stanley. final and finally are keyword, while finalize is method. final keyword is very useful for creating ad Immutable class in Java By making a class final, we prevent it from being extended, similarly by making a method final, we prevent it from being overridden,. On the other hand, finalize() method is called by garbage collector, before that object is collected, but this is not guaranteed by Java specification. finally keyword is the only one which is related to error and exception handling and you should always have finally block in production code for closing connection and resources. See here for more detailed answer of this question.

13) What is wrong with following code : public static void start() throws IOException, RuntimeException{ throw new RuntimeException("Not able to Start"); } public static void main(String args[]) {

43

try { start(); } catch (Exception ex) { ex.printStackTrace(); } catch (RuntimeException re) { re.printStackTrace(); } }

This code will throw compiler error on line where RuntimeException variable re is written on catch block. since Exception is super class of RuntimeException, all RuntimeException thrown by start() method will be captured by first catch block and code will never reach second catch block and that's the reason compiler will flag error as exception java.lang.RuntimeException has already been caught".

14) What is wrong with following code in Java: public class SuperClass { public void start() throws IOException{ throw new IOException("Not able to open file"); } } public class SubClass extends SuperClass{ public void start() throws Exception{ throw new Exception("Not able to start"); } } In this code compiler will complain on sub class where start() method gets overridden. As per rules of method overriding in Java, an overridden method can not throw Checked Exception which is higher in hierarchy than original method. Since here start() is throwing IOException in super class, start() in sub class can only throw either IOException or any sub class of IOException but not super class ofIOException e.g. Exception. 15) What is wrong with following Java Exception code: public static void start(){ System.out.println("Java Exception interivew question Answers for Programmers"); } public static void main(String args[]) { try{ start(); }catch(IOException ioe){ ioe.printStackTrace(); } } In this Java Exception example code, compiler will complain on line where we are handling IOException, since IOException is a checked Exception and start() method doesn't throw IOException, so compiler will flag error as "exception java.io.IOException is never thrown in body of corresponding try statement", but if you change IOException to Exception compiler error will disappear because Exception can be used to catch all RuntimeException which doesn't require declaration in throws clause. I like this little tricky Java Exception interview question because its not easy to figure out result by chaining IOException to Exception. You can also check Java Puzzlers by Joshua Bloch and Neil Gafter for some tricky questions based on Java Errors and Exceptions.

44

These are some of Java Error and Exception interview questions, I have mostly seen in both fresher and experienced level of Java interviews. There are a lot more questions on Exception which I haven't included and if you think you have a good question missed out than let me know and I will make effort to include it on this list of java exceptions question and answers. One last question of Java Exception I am leaving for you guys is "Why Java Exception considered to be better alternative of returning error codes" , let me know what is your thought on this list of Java Exception interview questions and answers.

Java program to find middle element of LinkedList in one pass

Here is complete Java program to find middle node of Linked List in Java. Remember LinkedList class here is our custom class and dont confuse this class with java.util.LinkedList which is a popular Collection class in Java. In this Java program, our class LinkedList represent a linked list data structure which contains collection of node and has head and tail. Each Node contains data and address part. Main method of LinkedListTest class is used to simulate the problem, where we created Linked List and added few elements on it and then iterate over them to find middle element of Linked List in one pass in Java. import test.LinkedList.Node; /** * Java program to find middle element of linked list in one pass. * In order to find middle element of linked list we need to find length first * but since we can only traverse linked list one time, we will use two pointers * one which we will increment on each iteration while other which will be * incremented every second iteration. so when first pointer will point to the * end of linked list, second will be pointing to the middle element of linked list * @author */ public class LinkedListTest { public static void main(String args[]) { //creating LinkedList with 5 elements including head LinkedList linkedList = new LinkedList(); LinkedList.Node head = linkedList.head(); linkedList.add( new LinkedList.Node("1")); linkedList.add( new LinkedList.Node("2")); linkedList.add( new LinkedList.Node("3")); linkedList.add( new LinkedList.Node("4")); //finding middle element of LinkedList in single pass LinkedList.Node current = head; int length = 0; LinkedList.Node middle = head; while(current.next() != null){ length++; if(length%2 ==0){ middle = middle.next(); } current = current.next(); } if(length%2 == 1){

45

middle = middle.next(); } System.out.println("length of LinkedList: " + length); System.out.println("middle element of LinkedList : " + middle); } } class LinkedList{ private Node head; private Node tail; public LinkedList(){ this.head = new Node("head"); tail = head; } public Node head(){ return head; } public void add(Node node){ tail.next = node; tail = node; } public static class Node{ private Node next; private String data; public Node(String data){ this.data = data; } public String data() { return data; } public void setData(String data) { this.data = data; } public Node next() { return next; } public void setNext(Node next) { this.next = next; } public String toString(){ return this.data; } } } Output: length of LinkedList: 4 middle element of LinkedList : 2

46

Thats all on How to find middle element of LinkedList in one pass. As I said this is a good interview question to separate programmers from non programmers. Also technique mentioned here to find middle node of LinkedList can be used to find 3rd element from Last or nth element from last in a LinkedList as well.

How to check or detect duplicate elements in Array in Java


Detecting duplicate elements in Java array is another programming interview question I like. There could be lot of way you can check if your array contains duplicate elements or not and sometime you discover a unique way of checking duplicates by asking this question on Java interview. Beauty of this question is that it has endless number of follow-up question so if interviewee get through this question you can ask to him about time complexity and space or to improve his algorithm to make it fast .you can even ask to find those duplicate elements in Array which even can go from one duplicate to many repeating elements in Array. As I said you can really test programming skill around array of a Java programmer.

Checking Array for duplicate elements Java


In this Java tutorial we will see couple of ways to find if array contains duplicates or not in Java. We will use unique property of Java collection class Set which doesnt allow duplicates to check java array for duplicate elements. Here are five ways we can check if an array has duplicates or not:

1) brute force method which compares each element of Array to all other elements and return true if it founds duplicates. Though this is not an efficient choice it is the one which first comes in mind.

2) Another quick way of checking if a Java array contains duplicates or not is to convert that array into Set. Since Set doesnt allow duplicates size of corresponding Set will be smaller than original Array if Array contains duplicates otherwise size of both Array and Set will be same.

3) One more way to detect duplication in java array is adding every element of array into HashSet which is a Set implementation. Since add(Object obj) method of Set returns false if Set already contains element to be added, it can be used to find out if array contains duplicates in Java or not.

In next section we will complete code example of all three ways of duplicate detection on Array in java. Remember this discussion is just confirming whether array contains duplicate or not , its not finding out actual duplicate elements from Array, though you can easily extend example Java program to accomplish that task based on your requirement.

47

Code Example of checking duplicate on Array in Java


Here is complete code sample of all above methods to check if your array contains duplicates or not.

import

java.util.Arrays;

import java.util.HashSet; import java.util.List; import java.util.Set;

public class CheckDuplicatesInJavaArray {

public static void main(String args[])

String[] withDuplicates = new String[] {"one","two","three","one"}; String[] withoutDuplicates = new String[] {"one","two","three"};

System.out.println("Checking array with duplicate using brute force: " + bruteforce(withDuplicates)); System.out.println("Checking array without any duplicate using brute force: " + bruteforce(withoutDuplicates));

System.out.println("Checking array with duplicate using Set and List: " + checkDuplicateUsingSet(withDuplicates)); System.out.println("Checking array without any duplicate using Set and List: " + checkDuplicateUsingSet(withoutDuplicates));

System.out.println("Checking array with duplicate using Set and List: " + checkDuplicateUsingAdd(withDuplicates)); System.out.println("Checking array without any duplicate using Set and List: " + checkDuplicateUsingAdd(withoutDuplicates));

48

/* * brute force way of checking if array contains duplicates in Java * comparing each elements to all other elements of array * complexity on order of O(n^2) not advised in production */ public static boolean bruteforce(String[] input) { for (int i = 0; i < input.length; i++) { for (int j = 0; j < input.length; j++) { if (input[i].equals(input[j]) && i != j) { return true; } } } return false; } /* * detect duplicate in array by comparing size of List and Set * since Set doesn't contain duplicate, size must be less for an array which contains duplicates */ public static boolean checkDuplicateUsingSet(String[] input){ List inputList = Arrays.asList(input); Set inputSet = new HashSet(inputList); if(inputSet.size()< inputList.size()) return true; } return false; }

/*

49

* Since Set doesn't allow duplicates add() return false * if we try to add duplicates into Set and this property * can be used to check if array contains duplicates in Java */ public static boolean checkDuplicateUsingAdd(String[] input) { Set tempSet = new HashSet(); for (String str : input) { if (!tempSet.add(str)) { return true; } } return false; } }

Output: Checking array with duplicate using brute force: true Checking array without any duplicate using brute force: false Checking array with duplicate using Set and List: true Checking array without any duplicate using Set and List: false Checking array with duplicate using Set and List: true Checking array without any duplicate using Set and List: false

How to reverse String in Java using Iteration and Recursion


How to reverse string in java is popular core java interview question and asked on all levels from junior to senior java programming job. since Java has rich API most java programmer answer this question by using StringBuffer reverse() method which easily reverses an String in Java and its right way if you are programming in Java but mostinterview doesn't stop there and they ask interviewee to reverse String in Java without using StringBuffer or they will ask you to write an iterative reverse function which reverses string in Java. In this tutorial we will see how to reverse string in both iterative and recursive fashion. This example will help you to prepare better for using recursion in java which is often a weak area of Java programmer and exposed during a programming interview.

50

Reverse String in Java using Iteration and Recursion

if you are from C background and new to Java then you get surprise that java Strings are not character array instead they are object and Strings in Java are not null terminated but still you can use your C skill to write iterative reverse function for string by getting character array by calling String.toCharArray() and getting length of String by calling String.length(). Now if you succeed in writing String reverse function, an iterative version without using StringBuffer reverse than they finally ask you to write a recursive one. Since recursion is a tricky concept and not many Java developer think recursive as compared to C++ dudes, you may see many of Java programmer stuck here by doing doodling around subString, indexOf etc. So its better to prepare in advance. here I have given example of reversing string using StringBuffer, iterative version of String reversal and reversing string in Java using recursion. As I said recursive solution is always tricky to come up you need to found a suitable base case and than repetive call recursive method with each call reducing length of argument. anyway mine way is just one way of reversing string using recursion, there are many so lution out there. so dont forget to try out yourself.

String Reverse Example using Iteration and Recursion in Java


Here is code example String reverse using iterative and recursive function written in Java. Recursive solution is just for demonstrative and education purpose, dont use recursive solution in production code as it may result in StackOverFlowError if String to be reversed is very long String or if you have any bug in your reverse function, anyway its good test to make yourself comfortable with recursive functions in java.

import java.io.FileNotFoundException; import java.io.IOException;

/** * *@author Javin / public class StringReverseExample {

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

//original string String str = "Sony is going to introduce Internet TV soon"; System.out.println("Original String: " + str);

51

//reversed string using Stringbuffer String reverseStr = new StringBuffer(str).reverse().toString(); System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);

//iterative method to reverse String in Java reverseStr = reverse(str); System.out.println("Reverse String in Java using Iteration: " + reverseStr);

//recursive method to reverse String in Java reverseStr = reverseRecursively(str); System.out.println("Reverse String in Java using Recursion: " + reverseStr);

public static String reverse(String str) { StringBuilder strBuilder = new StringBuilder(); char[] strChars = str.toCharArray();

for (int i = strChars.length - 1; i >= 0; i--) { strBuilder.append(strChars[i]); }

return strBuilder.toString(); }

public static String reverseRecursively(String str) {

52

//base case to handle one char string and empty string if (str.length() < 2) { return str; }

return reverseRecursively(str.substring(1)) + str.charAt(0);

} }

Thats all on how to reverse String in Java using Recursion, Iteration and without using StringBuffer. This is one of my favorite interview question and I mostly ask to write recursive solution just to know whether programmer has ability to comprehend recursive problem or not.

Java program - Fibonacci series with recursion example


Write a Java program to print Fibonacci series up to a given number or create simple Java program to calculate Fibonacci number is common Java questions on fresher interview and homework. Fibonacci series is also a popular topic on various programming exercises in school and colleges. Fibonacci series is series of natural number where next number is equivalent to sum of previous two number e.g. fn = fn-1 + fn-2. First two numbers of Fibonacci series is always 1, 1. In this Java program example for Fibonacci series we create function to calculate Fibonacci number and then print those numbers on Java console. Another twist in this questions is that some time interviewer ask to write Java program for Fibonacci numbers using recursion, so its better you prepare for both iterative and recursive version of Fibonacci number. One more coding question which is quite popular is printing prime numbers in Java which I have discussed earlier. In this tutorial we will see example of both recursive and iterative algorithm for Fibonacci numbers:

Code Example to calculate and print Fibonacci numbers in Java

Here is complete code example of printing Fibonacci Series in Java . Fibonacci series is printed using both Iterative method and recursive method implemented using Java programming language.
import java.util.Scanner; /**

53

* Java program to calculate and print Fibonacci number using both recursion and Iteration. * Fibonacci number is sum of previous two Fibonacci numbers fn= fn-1+ fn-2 * first 10 Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 * @author */ public class FibonacciCalculator { public static void main(String args[]) { //input to print Fibonacci series upto how many numbers System.out.println("Enter number upto which Fibonacci series to print: "); int number = new Scanner(System.in).nextInt(); System.out.println("Fibonacci series upto " + number +" numbers : "); //printing Fibonacci series upto number for(int i=1; i<=number; i++){ System.out.print(fibonacci2(i) +" "); }

} /* * Java program for Fibonacci number using recursion. * This program uses tail recursion to calculate Fibonacci number for a given number * @return Fibonacci number */ public static int fibonacci(int number){ if(number == 1 || number == 2){ return 1; } return fibonacci(number-1) + fibonacci(number -2); //tail recursion } /* * Java program to calculate Fibonacci number using loop or Iteration. * @return Fibonacci number */ public static int fibonacci2(int number){ if(number == 1 || number == 2){ return 1; } int fibo1=1, fibo2=1, fibonacci=1; for(int i= 3; i<= number; i++){ fibonacci = fibo1 + fibo2; //Fibonacci number is sum of previous two Fibonacci number fibo1 = fibo2; fibo2 = fibonacci; } return fibonacci; //Fibonacci number

54

} } Output: Enter number upto which Fibonacci series to print: 12 Fibonacci series upto 12 numbers : 1 1 2 3 5 8 13 21 34 55 89 144

After asking to write simple Java program to print Fibonacci series and later asking for Fibonacci series using recursion, another important question interviewer ask is how do you improve your Fibonacci function both iterative and recursive one? A technique called memorization can be used to drastically improve performance of method which calculates Fibonacci number. if you look at the method it repetitive creates same Fibonacci number e.g. In order to calculate 10th Fibonacci number function first create first 9 Fibonacci number, this could be very time consuming if you just increase the upper limit from 10 to 10K. In memorization programming technique result of earlier calculation is cached and reused. So you don't need to create same Fibonacci number if you already have calculated it. You can write code for Fibonacci series with memorization by just using a HashMap and checking if Fibonacci number for a corresponding number is already exits or not and calculate only if it doesn't exist.

Fibonacci number in Java with memorization

Here is the code example of printing Fibonacci number with memorization technique : /* * Java Program to calculate Fibonacci numbers with memorization * This is quite fast as compared to previous Fibonacci function especially for * calculating factorial of large numbers. */ public static int improvedFibo(int number){ Integer fibonacci = cache.get(number); if(fibonacci != null){ return fibonacci; //fibonacci number from cache } fibonacci = fibonacci2(number); //fibonacci number not in cache, calculating it cache.put(number, fibonacci); //putting fibonacci number in cache for future request return fibonacci; } Comparison //comparison of performance of Fibonacci number with memorization int number = 100000000; long startTime = System.nanoTime(); int result = fibonacci2(number); //fibonacci number with memorization long elapsedTime = System.nanoTime() - startTime; System.out.println("Time taken to calculate Fibonacci number upto 100M without memorization:"+ elapsedTime);

55

startTime = System.nanoTime(); result = improvedFibo(number); //Fibonacci number with memorization elapsedTime = System.nanoTime() - startTime; System.out.println("Time taken to calculate Fibonacci number upto 100M with memorization:" + elapsedTime); Output: Time taken to calculate Fibonacci number upto 100M without memorization:149479613 Time taken to calculate Fibonacci number upto 100M with memorization:118972384

Interesting point is that improved method only shows better performance for large numbers like 100M otherwise iterative version of Fibonacci method is faster. That could be explained by extra work done by improved method in terms of storing value in cache and getting it from there or am I missing something?

That's all on writing Java program to calculate and print Fibonacci number. Fibonacci number is good question for programming exercise but when asked as question in Java interview you just need to be more detailed and precise about what you are doing.

How to check if a number is a palindrome or not in Java Example


How to check if a number is a palindrome or not is a variant of popular String interview question how to check if a String is a palindrome or not. A number is said to be a palindrome if number itself is equal to reverse of number e.g. 313 is a palindrome because reverse of this number is also 313. On the other hand 123 is not a palindrome becausereverse of 123 is 321 which is not equal to 123, i.e. original number. In order to check if a number is a palindrome or not we can reuse the logic of How to reverse number in Java. Since in most of interview, you are supposed to solve this question without taking help from API i.e. only using basic programming construct e.g. loop, conditional statement, variables, operators and logic. I have also seen programmer solving this question by first converting integer to String and than reversing String using reverse() method of StringBuffer and than converting String back to Integer, which is not a correct way because you are using Java API. Some programmer may think that this is just a trivialprogramming exercise but its not. Questions like this or Fibonacci series using recursion can easily separate programmers who can code and who cant. So its always in best interest to keep doing programing exercise and developing logic.

Java program to check if number is palindrome or not


Here is a simple Java program which finds if a number is a palindrome or not. This program does not use any API method instead it uses division and remainder operator of Java programming language to determine if number is palindrome or not. Programming logic to reverse a number is encapsulate in reverse() method andisPalindrome(int number) reuse that logic to test if a number is palindrome or not.

56

import java.util.Scanner; /** * This Java program takes an input number from command line and integer array * and check if number is palindrome or not. A number is called palindrome * if number is equal to reverse of number itself. * * @author Javin Paul */ public class PalindromeTest {

public static void main(String args[]){ Scanner scanner = new Scanner(System.in); //int number = scanner.nextInt(); int[] numbers = {1, 20, 22, 102, 101, 1221, 13321, 13331, 0, 11}; for(int number: numbers){ System.out.println("Does number : " + number +" is a palindrome? " + isPalindrome(number)); } } private static boolean isPalindrome(int number) { if(number == reverse(number)){ return true; } return false; }

private static int reverse(int number){ int reverse = 0; while(number != 0){ reverse = reverse*10 + number%10; number = number/10; } return reverse; } } Output Does number Does number Does number Does number Does number Does number Does number

: : : : : : :

1 is a palindrome? true 20 is a palindrome? false 22 is a palindrome? true 102 is a palindrome? false 101 is a palindrome? true 1221 is a palindrome? true 13321 is a palindrome? false

57

Does number : 13331 is a palindrome? true Does number : 0 is a palindrome? true Does number : 11 is a palindrome? true

That's all on how to check if a number is a palindrome or not. As I said this is a good programming exercise particularly for beginners who have just started learning Java programming language, as it teaches how to use division and remainder operator in Java. Once again Fibonacci series, Palindrome are classical coding question and should not be missed during preparation.

Read more: http://javarevisited.blogspot.com/2012/12/howto-check-if-number-is-palindrome-or-notexample.html#ixzz2YlK8K6XQ 10 JDBC Interview question answer in Java

Here is my list of frequently asked JDBC question in Java, I have tried to provide answer to most of question. If you have any interesting JDBC question which you have faced and not in this list then please share with us.

Question 1: What is JDBC? Answer : One of the first JDBC interview question in most of interviews. JDBC is java database connectivity as name implies its a java API for communicating to relational database, API has java classes and interfaces using that developer can easily interact with database. For this we need database specific JDBC drivers. Some time this also result in followup questions like Difference between type 2 and type 4 JDBC drivers. See the link for answer.

Question 2: What are the main steps in java to make JDBC connectivity? Answer : Another beginner level JDBC Interview question, mostly asked on telephonic interviews. Here are main steps to connect to database. Load the Driver: First step is to load the database specific driver which communicates with database. Make Connection: Next step is get connection from the database using connection object, which is used to send SQL statement also and get result back from the database. Get Statement object: From connection object we can get statement object which is used to query the database Execute the Query:Using statement object we execute the SQL or database query and get result set from the query. Close the connection:After getting resultset and all required operation performed the last step should be closing the database connection. For complete code example you can also refere Java program to connect to Oracle database

58

Question 3: What is the mean of dirty read in database? Answer : This kind of JDBC interview question is asked on 2 to 4 years experience Java programmer, they are expected to familiar with database transaction and isolation level etc. As the name it self convey the meaning of dirty read read the value which may or may not be correct. in database when one transaction is executing and changing some field value same time some another transaction comes and read the change field value before first transaction commit or rollback the value ,which cause invalid value for that field, this scenario is known as dirty read. Question 4: What is 2 phase commit? Answer : This is one of the most popular JDBC Interview question and asked at advanced level, mostly to senior Java developers on J2EE interviews. Two phase commit is used in distributed environment where multiple process take part in distributed transaction process. In simple word we can understand like if any transaction is executing and it will effect multiple database then two phase commit will be used to make all database synchronized with each other. In two phase commit, commit or rollback is done by two phases: Commit request phase: in this phase main process or coordinator process take vote of all other process that they are complete their process successfully and ready to commit if all the votes are yes then they go ahead for next phase. And if No then rollback is performed. Commit phase: according to vote if all the votes are yes then commit is done. Similarly when any transaction changes multiple database after execution of transaction it will issue pre commit command on each database and all database send acknowledgement and according to acknowledgement if all are positive transaction will issue the commit command otherwise rollback is done . Question 5: What are different types of Statement? Answer : This is another classical JDBC interview question. Variants are Difference between Statement, PreparedStatemetn and CallableStatement in Java. Statement object is used to send SQL query to database and get result from database, and we get statement object from connection object. There are three types of statement: 1. Statement: its a commonly used for getting data from database useful when we are using static SQL statement at runtime. it will not accept any parameter. Statement stmt = conn.createStatement( ); ResultSet rs = stmt.executeQuery(); 2. PreparedStatement: when we are using same SQL statement multiple time its is useful and it will accept parameter at runtime. String SQL = "Update stock SET limit = ? WHERE stockType = ?"; PreparedStatement pstmt = conn.prepareStatement(SQL); ResultSet rs = pstmt.executeQuery(); To learn more about PreparedStatement, see What is PreparedStatement in Java and Benefits 3. Callable Statement: when we want to access stored procedures then callable statement are useful and they also accept runtime parameter. It is called like this CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery();

1.

2.

Question 6: How cursor works in scrollable result set? Answer : Another tough JDBC Interview question, not many Java programmer knows about using Cursor in Java. in JDBC 2.0 API new feature is added to move cursor in resultset backward forward and also in a particular row . There are three constant define in result set by which we can move cursor.

59

TYPE_FORWARD_ONLY: creates a nonscrollable result set, that is, one in which the cursor moves only forward TYPE_SCROLL_INSENSITIVE : a scrollable result set does not reflects changes that are made to it while it is open TYPE_SCROLL_SENSITIVE: a scrollable result set reflects changes that are made to it while it is open

Question 7: What is connection pooling? Answer : This is also one of the most popular question asked during JDBC Interviews. Connection pooling is the mechanism by which we reuse the recourse like connection objects which are needed to make connection with database .In this mechanism client are not required every time make new connection and then interact with database instead of that connection objects are stored in connection pool and client will get it from there. so its a best way to share a server resources among the client and enhance the application performance. If you use Spring framework, then you can also refer How to setup JDBC Connection Pool using Spring in Java

Question 8: What do you mean by cold backup, hot backup? Answer : This question is not directly related to JDBC but some time asked during JDBC interviews. Cold back is the backup techniques in which backup of files are taken before the database restarted. In hot backup backup of files and table is taken at the same time when database is running. A warm is a recovery technique where all the tables are locked and users cannot access at the time of backing up data.

Question 9: What are the locking system in JDBC Answer : One more tough JDBC question to understand and prepare. There are 2 types of locking in JDBC by which we can handle multiple user issue using the record. if two user are reading the same record then there is no issue but what if users are updating the record , in this case changes done by first user is gone by second user if he also update the same record .so we need some type of locking so no lost update. Optimistic Locking: optimistic locking lock the record only when update take place. Optimistic locking does not use exclusive locks when reading Pessimistic locking: in this record are locked as it selects the row to update Question 10: Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? Answer: No, we can open only one statement object when using JDBC-ODBC Bridge. Thats all on this list of 10 JDBC Interview question with answer. As I said JDBC API and there concepts are integral part of any Java interview and there is always atleast one question from JDBC. Since most application uses datbase in backend, JDBC becomes critical for any Java developer.

Q: Explain inner and outer SQL joins? A: Joins allow database users to combine data from one table with data from one or more other tables (or views, or synonyms). Tables are joined two at a time making a new table containing all possible combinations of rows from the original two tables.

60

Inner joins: Chooses the join criteria using any column names that happen to match between the two tables. The example below displays only the employees who are executives as well. ?

1
?

SELECT emp.firstname, exec.surname FROM employees emp, executives exec WHERE emp.id = exec.id;

1
?

Left Outer joins: A problem with the inner join is that only rows that match between tables are returned. The example below will show all the employees and fill the null data for the executives. ?

1
?

SELECT emp.firstname, exec.surname FROM employees emp left join executives exec ON emp.id = exec.id;

Right Outer join: A problem with the inner join is that only rows that match between tables are returned. The example below will show all the executives and fill the null data for the employees. ?

1
?

SELECT emp.firstname, exec.surname FROM employees emp right join executives exec ON emp.id = exec.id;

Full outer join: To cause SQL to create both sides of the join ?

1
?

SELECT emp.firstname, exec.surname FROM employees emp full join executives exec ON emp.id = exec.id;

Self join: A self-join is a join of a table to itself. If you want to find out all the employees who live in

61

the same city as employees whose first name starts with Peter, then one way is to use a sub-query as shown below: ?

1
?

SELECT emp.firstname, emp.surname FROM employees emp WHERE city IN (SELECT city FROM employees where firstname like Peter)

1
?

Q. Explain a sub-query? How does a sub-query impact on performance? A. It is possible to embed a SQL statement within another. When this is done on the WHERE or the HAVINGstatements, we have a subquery construct.

Q. What is subquery useful for? A. It is used to join tables and there are cases where the only way to correlate two tables is through a subquery. ?

1
?

SELECT emp.firstname, emp.surname FROM employees emp WHERE emp.id NOT IN (SELECT id FROM executives);

1
?

There are performance problems with sub-queries, which may return NULL values. The above subquery can be re-written as shown below by invoking a correlated sub-query. ?

1
?

SELECT emp.firstname, emp.surname FROM employees emp WHERE emp.id NOT EXISTS (SELECT id FROM executives);

1
?

The above query can be re-written as an outer join for a faster performance as shown below: ?

1
?

SELECT emp.firstname, exec.surname FROM employees emp left join executives exec on emp.id

= exec.id AND exec.id IS NULL;

The above execution plan will be faster by eliminating the need for a sub-query.

62

Q. Can you give SQL examples for the following scenarios? A. Scenario 1: Retrieve first name and sum of order qty for order sum greater than 25, and group the order sum by first name.? ?

1
?

SELECT FIRSTNAME,SUM(QTY) FROM orders GROUP BY FIRSTNAME HAVING SUM(QTY)>25;

1
?

1
?

Scenario 2: Retrieve all employees whose name has a String "au"? ?

1
?

SELECT * FROM employees emp WHERE emp.firstname LIKE %au%;

1
?

Scenario 3: select account number and adviser code for a given adviser code, but restrict the returned values to supplied min and max limit. For example, record 1 to record 10, record 11 to record 20, etc. The SQL for the above scenario needs to use some custom SQL parameters and functions. The example below uses the ROWNUM variable that keeps track of the row numbers in Oracle. The nested query shown below can limit the returned results based on a lower and upper limit. ?

1 2 3
?

select * from (select a.ACCOUNT_NO, a.ADVISER_CODE, ROWNUM rnum from ( Select * from accounts where ADVISER_CODE=:advCode order by advCode)

1 2 3

where ROWNUM <= :max_row) where rnum >= :min_row

Q: In your experience, what are some of the common mistakes developers make? A:

63

1. Cartesian joins SQL Joins are used to relate information in different tables. A Join condition is a part of the sql query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL WHERE Clause of select, update, deletestatements. The Syntax for joining two tables is: ?

1 2 3

SELECT col1, col2, col3 FROM table_name1, table_name2 WHERE table_name1.col2 = table_name2.col1;

If a sql join condition is omitted as shown below ?

1 2

SELECT col1, col2, col3 FROM table_name1, table_name2

or if the condition is invalid, then the join operation will result in a Cartesian product. The Cartesian product returns a number of rows equal to the product of all rows in all the tables being joined. For example, if the first table has 20 rows and the second table has 10 rows, the result will be 20 * 10, or 200 rows. This query will take a long time to execute.

2. Use of SELECT * For example, a common misuse of SELECT * is to extract a set of all employees and to insert them into another table called Contractors with the same structure ?

1 2

INSERT INTO Contractors SELECT * FROM Employees WHERE emp_type = 'C';

The above query does the job, however, one day business requirements change and two new columns are added to the Employees table: ?

1 2

ALTER TABLE Products ADD effective_start_date DATETIME, effective_end_date DATETIME;

All of sudden the query that extracts from the Employees table and insert records into the Contractor table results in error. "Insert Error: Column name or number of supplied values does not match table definition."

64

The fix is to explicitly list the column names in the query: ?

1 2

INSERT INTO Contractors (emp_id, emp_name) SELECT emp_id, emp_name FROM Employees WHERE emp_type = 'C';

3. Embedding User Interface (UI) layer logic into Data layer via SQL. For example SELECT '<a href="http://www.blogger.com/...">' + name ' </a>'

The above code is a bad practice because it tightly couples your UI Layer with the Data Layer.

4. Not using Prepared statements. Prepared statements are more secured and efficient than the ordinarystatements. Prepared statements prevent SQL injection attacks.

5. Using the predicate "LIKE" in indexed columns. The "LIKE" predicate typically performs a search without the normal performance benefit of indexes. Using '=', '<>', etc instead of "LIKE" will increase performance. Also should be aware of that case sensitivity (e.g., 'A' versus 'a') may be different based upon database Server or configuration.

6. Over use of cursors in stored procedures. If possible, avoid using SQL stored proc cursors. They generally use a lot of Server resources and reduce the performance and scalability of your applications. If you need to perform row-by-row operations, try to find another method to perform the task. Here are some alternatives to using a cursor:

Use WHILE LOOPS Use temp tables Use materialized views (allowing you to pre-join complex views and pre-compute summaries for super-fast response time. ) Use derived tables Perform multiple queries Use correlated sub-queries Use the CASE statement Q. Can you give some database performance tuning tips based on your experience? A.

65

1. Materialized views are one of the important SQL tuning tools in Oracle. Instead of the entire company accessing a single database server, user load can be distributed across multiple database servers with the help of materialized views in Oracle. Through the use of multi tier materialized views, you can create materialized views based on other materialized views, which enables you to distribute user load to an even greater extent because clients can access materialized view sites instead of master sites. To decrease the amount of data that is replicated, a materialized view can be a subset of a master table or master materialized view.

Materialized views are schema objects that can be used to summarize, precompute, replicate, and distribute data. It allows you to pre-join complex views and pre-compute summaries for super-fast response times. Unlike an ordinary view, which does not take up any storage space or contain any data, a materialized view provides indirect access to table data by storing the results of a query in a separate schema object. You can define a materialized view on a base table, partitioned table or view and you can define indexes on a materialized view. A materialized view can be stored in the same database as its base tables (improves query performance through query rewrite) or in a different database. It is also worth noting that this capability may not suit best for too frequent activities as in online transaction processing (i.e. OLTP) environments. In other databases equivalent functionalities can be achieved through triggers on base tables that would update/insert aggregate or dimension tables and queries can be executed against these aggregated or dimension tables as oppose to the base tables.

2. As a rule of thumb, every table should have a clustered index. Generally, but not always, the clustered index should be on a column that increases in one direction (i.e. monotonic) such as an identity column, or some other column where the value is increasing and is unique. In many cases, the primary key is the ideal column for a clustered index. Create an index on any column that is a foreign key. If you know it will be unique, set the flag to force the index to be unique. 3. Avoid temp tables as much as you can, but if you need a temp table, create it explicitly using Create Table #temp. 4. Only return the columns and the rows you need. 5. Avoid full table scan where possible. The full table scan can be caused by

No WHERE condition. No index on any type of field in the WHERE clause. NOT IN predicate that is easier to write (replace NOT IN with a left outer join).

66

WHERE clauses like column_name is not null, condition 1 or condition 2, column_name between ... and ..., not equality comparisons Use of SQL LIKE clause operator to find a string within a large table column (e.g. VARCHAR(2000), CLOB, BLOB). DISTINCT, ANY, and ALL.

67

Вам также может понравиться