Saturday, April 6, 2013

How does Session handling works in Servlet environment ?

There are multiple ways to handle session by a servlet framework. For example following methods can be used,

  1. Storing Cookies on the client side
  2. URL Rewriting
  3. Hidden form fields

Servlets use cookies as the default mechanism for session tracking, but in case cookies are disabled on the client, Server can use URL re-writing for achieving the same.

When server calls request.getSession(true), then server generates and sends JSESSIONID back to the client for all future session references. JSESSIONID will then be stored by the client and sent back to the server using any of the above mentioned mechanisms.

To ensure that your Servlets support servers that use URL rewriting to track sessions, you must pass all the URL's used in your servlet through the

HttpServletResponse.encodeURL() method like :
out.println("<form actionb ='"+res.encodeURL("/example/htmlpage")+"'>");
This will append the sessionID to the form's action.

Discuss internal's of a Concurrent Hashmap (CHM) in Java 7

In Java 1.7, A ConcurrentHashMap is a hashmap supporting full concurrency of retrieval via volatile reads of segments and tables without locking, and adjustable expected concurrency for updates. All the operations in this class are thread-safe, although the retrieval operations does not depend on locking mechanism (non-blocking). And there is not any support for locking the entire table, in a way that prevents all access. The allowed concurrency among update operations is guided by the optional concurrencyLevel constructor argument (default is16), which is used as a hint for internal sizing.
Fig 1. Internals Implementation diagram for HashMap

ConcurrentHashMap is similar in implementation to that of HashMap, with resizable array of hash buckets, each consisting of List of HashEntry elements. Instead of a single collection lock, ConcurrentHashMap uses a fixed pool of locks that form a partition over the collection of buckets.

Here is the code snippet showing HashEntry class

static final class HashEntry {
        final int hash;
        final K key;
        volatile V value;
        volatile HashEntry next;
HashEntry class takes advantage of final and volatile variables to reflect the changes to other threads without acquiring the expensive lock for read operations.
The table inside ConcurrentHashMap is divided among Segments (which extends Reentrant Lock), each of which itself is a concurrently readable hash table. Each segment requires uses single lock to consistently update its elements flushing all the changes to main memory.

put() method holds the bucket lock for the duration of its execution and doesn't necessarily block other threads from calling get() operations on the map. It firstly searches the appropriate hash chain for the given key and if found, then it simply updates the volatile value field. Otherwise it creates a new HashEntry object and inserts it at the head of the list.
Iterator returned by the ConcurrentHashMap is fail-safe but weakly consistent. keySet().iterator() returns the iterator for the set of hash keys backed by the original map. The iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.
Re-sizing happens dynamically inside the map whenever required in order to maintain an upper bound on hash collision. Increase in number of buckets leads to rehashing the existing values. This is achieved by recursively acquiring lock over each bucket and then rehashing the elements from each bucket to new larger hash table.

Question : Is this possible for 2 threads to update the ConcurrentHashMap at the same moment ?

Answer : Yes, its possible to have 2 parallel threads writing to the CHM at the same time, infact in the default implementation of CHM, atmost 16 threads can write in parallel. But in worst case if the two objects lie in the same segment, then parallel write would not be possible. On the other-hand reads are not blocking in nature, so any number of threads can read the data at the same time, also reads can overlap with writes. 

Question : Can multiple threads read from a given Hashtable concurrently ?

Answer : No, get() method of hash table is synchronized (even for synchronized HashMap). So only one thread can get value from it at any given point in time. Full concurrency for reads is possible only in ConcurrentHashMap via the use of volatile.

What are four principles of OOP, How aggregation is different than Composition ?

There are 4 major principles that make an language Object Oriented.  These are Encapsulation, Data Abstraction, Polymorphism and Inheritance.


Encapsulation is the mechanism of hiding of data implementation by restricting access to public methods.


Abstract means a concept or an Idea which is not associated with any particular instance. Using abstract class/interface we express the intent of the class rather than the actual implementation. In a way, one class should not know the inner details of another in order to use it, just knowing the interfaces should be good enough.


Inheritances expresses "is a" relationship between two objects. Using proper inheritance, In derived classes we can reuse the code of existing super classes.


It means one name many forms. It is further of two types - static and dynamic. Static polymorphism is achieved using method overloading and dynamic polymorphism using method overriding.

What is aggregation, how is it different from composition ? 

Both of these are special type of association and differ only in weight of relationship.
Composition is stronger form of "is part of" relationship compared to aggregation "has a".
In composition, the member object can not exist outside the enclosing class while same is not true for Aggregation.

What are the key principles when designing a scalable software

  1. Stateless design using REST can help achieve scalability whereever possible. In such application, minimal session elements need to be replicated while distributing the application over multiple hosts. Users can save their favorite URLs and thus there should be no need for the page flow, if we use REST.
  2. Logging can be done asynchronously to save precious time of a method call.
  3. More processes vs more threads can be configured based on the demand of the target application. Generally it is advised to have a JVM with up to 2 GB memory because increasing memory beyond 2 GB incurs heavy GC pauses, and if we require more processing then we prefer to have a separate process for the JVM altogether. Multiple independent tasks should be run in parallel. Tasks can be partitioned to improve the performance.
  4. If we improve upon the concurrency of the software piece, then we can increase its scalability. This can be achieved by reducing the dependency on the shared resources. We should try utilizing the latest hardware optimization through JAVA as much as possible. For example we can use Atomic utilities provided in java.util.concurrent.atomic package, or Fork & Join to achieve higher throughput in concurrent applications. We should try holding the shared locks for as little time as possible. 
  5. Resource pooling and caching can be used to improve the processing time. Executing jobs in batches can further improve the performance.
  6. Picking up appropriate algorithm and data structure for a given scenario can help optimize the processing.
  7. If we are using SQL in our application then we should tune the SQL, use batching whereever possible and create indexes on the essentials table columns for faster retrievals.
  8. We should tune our JVM for optimum memory settings (Heap, PermGen, etc) and Garbage collection settings. For example if we do lot of text processing in our application with big temporary objects being created, then we should have larger Young Generation defined so that frequent gc run does not happen.
  9. Keep up to date with new technologies for performance benefits.

Good resources for a Java Developer

Essential Tool kit for Java Developer

IntelliJ IDE
Java DB
Twitter Bootstrap CSS library
Struts 2
Tortoise SVN
Apache Web Server
Jetty Server
Firebug extension for mozilla Firefox
Cygwin for Unix simulation


Design Patterns in Java - Head First
Concurrency In Practice by Brian Goetz
Effective Java 2nd Edition by Joshua Bloch
Algorithms 4th edition :
Cracking the coding interview at CareerCup

Technology Forums

Great Tutorials Articles

Few articles on Java 6 at IBM website
Concurrency In Practice by Brian Goetz -
Java Articles  :
Java SE Tutorial :
Java 7 docs:

Video Tutorials

What is AtomicInteger class and how it's functioning is different from using a volatile or synchronized?

AtomicInteger uses combination of volatile & CAS (compare and swap) to achieve thread-safety for Integer Counter. It is non-blocking in nature and thus highly usable in writing high throughput concurrent data structures that can be used under low to moderate thread contention.


In computer science, compare-and-swap (CAS) is an atomic instruction used in multi-threading to achieve synchronization. It compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value. This is done as a single atomic operation. The atomicity guarantees that the new value is calculated based on up-to-date information

Thread Contention

Essentially thread contention is a condition where one thread is waiting for a lock/object that is currently being held by another thread. Wwaiting thread cannot use that object until the other thread has unlocked that particular object.

Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block. So the visibility of volatile field is guaranteed by the JMM (Java Memory Model).

AtomicInteger class stores its value field in a volatile variable, thus it is a decorator over the traditional volatile variable, but it provides unique non-blocking mechanism for updating the value after requiring the hardware level support for CAS (compare and set/swap). Under low to moderate thread contention, atomic updates provides higher throughput compared to synchronized blocking increment operation.
Here is the implementation for getAndIncrement() method of AtomicInteger Class (as of Java 7).

public final int getAndIncrement() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return current;

You can see that no lock is acquired to increment the value, rather CAS is used inside infinite loop to update the new value, that’s why it can be used to write scalable application where thread contention is low to medium.

Discuss the effects of a volatile keyword in Java

Volatile is a mechanism for lighter weight synchronization where memory visibility of the protected state is guaranteed to all consecutive threads.

A write to volatile variable not only flush changes of the volatile variable but all the non volatile variables changed before write to volatile. Thus a simple flag of volatile type can serve the memory visibility guarantee of all the other variables changed before. The following figure explain it in entirety.

Non-atomic treatment of long and double

For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64-bit value from one write, and the second 32 bits from another write.

Writes and reads of volatile long and double values are always atomic.

Writes to and reads of references are always atomic, regardless of whether they are implemented as 32-bit or 64-bit values.

It is safe to perform read-modify-write operations on a shared volatile variable as long as you ensure that the volatile variable is only written from single thread.
volatile variables are liable to get into race conditions because atomicity is required to solve race condition

What happens when wait() & notify() method are called ?

When wait() method is invoked from a synchronized context, the following things happen

  1. The calling thread gives up the lock.
  2. The calling thread gives up the CPU.
  3. The calling thread goes to the monitor's waiting pool.

And in case of notify() method, following things happen

  1. One of the waiting thread (may be a random thread) moves out of the monitor's waiting pool.
  2. Thread comes into ready state (RUNNABLE).
  3. Tries its best to require the monitor lock before it can proceed to the method execution.

What do you understand by Java Memory Model ?

Interviewer's Intent - Interviewer wants to understand if you can write concurrent code.

Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes guarantee of visibility of memory operations across the Threads.

Let's first discuss about Memory Barrier which are the base for our further discussions. There are two type of memory barrier instructions in JMM - read barriers & write barrier.

A read barrier invalidates the local memory (cache, registers, etc) and then reads the contents from the main memory, so that changes made by other threads becomes visible to the current Thread.
A write barrier flushes out the contents of the processor's local memory to the main memory, so that changes made by the current Thread becomes visible to the other threads.

JMM semantics for synchronized
When a thread acquires monitor of an object, by entering into a synchronized block of code, it performs a read barrier (invalidates the local memory and reads from the heap instead). Similarly exiting from a synchronized block as part of releasing the associated monitor, it performs a write barrier (flushes changes to the main memory)
Thus modifications to a shared state using synchronized block by one Thread, is guaranteed to be visible to subsequent synchronized reads by other threads. This guarantee is provided by JMM in presence of synchronized code block.

JMM semantics for Volatile  fields
Read & write to volatile variables have same memory semantics as that of acquiring and releasing a monitor using synchronized code block. So the visibility of volatile field is guaranteed by the JMM. Moreover afterwards Java 1.5, volatile reads and writes are not reorderable with any other memory operations (volatile and non-volatile both). Thus when Thread A writes to a volatile variable V, and afterwards Thread B reads from variable V, any variable values that were visible to A at the time V was written are guaranteed now to be visible to B.

Let's try to understand the same using the following code

Data data = null;
volatile boolean flag = false;

Thread A
data = new Data();
flag = true; <-- writing to volatile will flush data as well as flag to main memory

Thread B
if(flag==true){ <-- reading from volatile will perform read barrier for flag as well data.
use data; <--- data is guaranteed to visible even though it is not declared volatile because of the JMM semantics of volatile flag.

Cracking Java Interviews 3rd Edition (Core Java 8, Hibernate & Spring framework) - Questions Bank for Investment Banking, Product Company Interviews



Buy this e-Book Instantly

Option 1. Instant Buy for Rs. 250 from (updates to same revision are freely delivered)

 Option 2. Instant Buy for Rs. 300 from

Option 3. 9.99$ from Lulu Press
Support independent publishing: Buy this e-book on Lulu.

Option 4. For 250/- Rs by direct deposit to Bank a/c (that's 16% savings, expect some delay, but 100% refund if you don't like the contents in 10 days)
Buy it by direct deposit to my bank account (NEFT), and i will send you the PDF version of the book before receiving the money.

Bank Details for NEFT Transfer
a/c 5277618224
IFSC : CITI0000002
Citi Bank 
Branch NA. Delhi

Don't forget to send me the details on email :

Explain the threading Jargon

Race Condition
A race condition occurs when the correctness of a computation depends on the relative timing of multiple threads by the runtime. In this scenario Getting the right result relies on the lucky timings.

Dead Lock
Dead lock occurs when two or more threads are blocked forever, waiting for each other to release up the shared resource. For two threads, it happens when two threads have a circular dependency on a pair of synchronized shared resources.

Describes a situation where a thread is unable to gain regular access to shared resource and is unable to make any progress
This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

Mutex stands for mutually exclusive, only one kind of operation (READ or WRITE) is allowed at a given time frame.

Live Lock
A thread often acts in response to the action of other threads, if the other thread's action is also in response to another thread, then live lock may result. No progress but threads are not blocked.

A synchronizer is any object that coordinates the control of flow of threads based on its state. For example, semaphore, CountDownLatch, FutureTask, Exchanger, CyclicBarrier, etc.

A synchronizer that can delay the progress of threads until it reaches the terminal state.

Counting semaphore are used to control the number of activities that can access a certain shared resource or perform a given action at the same time. Semaphores are normally used implement resource pool or to impose a bound on a collection.

A two party barrier in which the parties exchange data at the barrier point.

Is it possible to write a method in Java which swaps two int or Integer ?

The answer is No.

For knowing the exact answer you must be knowing how Parameter Passing works in Java.

Incase of primitive int
Parameters to the method are passed by value in Java. In case of primitive data types, a copy of the value is passed to the method, so any changes in the method will not reflect in the calling code.

Incase of Integer Wrapper Class
For objects, the reference to the Object are copied by value to the calling method. If we reassign these reference copies then the changes will not be reflected to the method calling this swap(x,y).

// This code will never work as intended
public void swap(Integer x, Integer y){
       Integer tmp =x;

Can the keys in Hashing data structure be made Mutable ?

Interviewer's intent is to know how good you know about Hashing Data Structure

The answer is NO. If we make the keys mutable then the hashcode() of the key will no more be consistent over time which will cause lookup failure for that object from the data structure. Let's analyze this example.
public void testMutableKey(){
        Map testMap = new HashMap<>();
        MutableKey mutableKey = new MutableKey();
        testMap.put(mutableKey, new Object());
        Object o = testMap.get(mutableKey);
        System.out.println("before changing key = " + o);
        mutableKey.setName("abc");    <==== Problematic Instruction
        o = testMap.get(mutableKey);
        System.out.println("after changing key = " + o);

    public static void main(String[] args) {
        MutableHashKey test = new MutableHashKey();

Program Output : 
before changing key = java.lang.Object@489bb457
after changing key = null

From the above example we see that as soon as we change the key, we are not able to get the associated object from the Map. 
Let's see what's happening inside
When we put the mutableKey to HashMap then hashcode() is calculated for the key, suppose it comes out to be 11. So the Object123 is successfully inserted into the HashMap at bucket Location 11.
Then we modify the key and try to get the object. HashMap's get() method again calculates the hashcode of the Key, since the Key is changed in between, so suppose hashcode() comes out to be 33 this time. Now the get() method goes to the bucket at address 33 and tries to retrieve the object, but it find nothing over there and returns the null.
Never make changes to the hashmap's key, otherwise the associated object can not be fetched using get() method. Though it will be accessible using other methods which iterate over the entire collection.

What if we don't synchronize the getters/accessors of a shared mutable object in multi-threaded applications ?

From Effective Java 2nd Edition - Item 66

When multiple threads share mutable data, each thread that reads or writes the data must perform synchronization. In fact, synchronization has no effect unless both read and write operations are synchronized.

Synchronization serves two major purposes in a multi-threaded scenario, one is atomicity of the operation and second is the memory visibility of the changes made by one thread to all other threads (Brian Goetz article on read and write barriers). In case of getters the changes made to the shared variable will get reflected to the new thread if the code block is synchronized, otherwise dirty reads may happen and the thread may see the stale state of the shared object.

So all the methods returning the mutable protected state of the shared object must be synchronized unless the  field returned is immutable, final or volatile.

Let's take example of a simple Counter Class.

public class Counter {
 private int c = 0;
 public synchronized void increment() {

 public synchronized int getValue() {  /*Must be synchronized to see the guaranteed correct value*/
  return c;
That's the reason that get() method of vector class is synchronized & must be synchronized.

Best way for storing currency values in Java

Question : Which data type would you choose for storing currency values like Trading Price ? What's your opinion about Float, Double and BigDecimal ?

Float & Double are Bad for financial world, never use them for monetary calculations.

There are two main reasons supporting this statement -

1.) All floating point values that can represent a currency amount (in dollars and cents) can not be stored exactly as it is in the memory. So if we want to store 0.1 dollar (10 cents), float/double can not store it as it is. Let's try to understand this fact by taking this simple example

public class DoubleForCurrency {

public static void main(String[] args) {
 double total = 0.2;
 for(int i=0;i<100;i++){
 System.out.println("total = " + total);

OUTPUT : total = 20.19999999999996
The output should have been 20.20 (20 dollars and 20 cents), but floating point calculation made it 20.1999999999..

2.) There is not much flexibility provided by Math.round() method for rounding the given calculation result compared to functionality offered by MathContext. RoundingMode provides options such as ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_UNNECESSARY, etc

BigDecimal For the Rescue
BigDecimal represents a signed decimal number of arbitrary precision with an associated scale. BigDecimal provides full control over the precision and rounding of the number value. Virtually its possible to calculate value of pi to 2 billion decimal places using BigDecimal.

That's the reason we should always prefer BigDecimal or BigInteger for financial calculations.


Primitive type - int and long are also useful for monetary calculations if decimal precision is not required

We should really avoid using BigDecimal(double value) constructor instead prefer BigDecimal(String) because BigDecimal (0.1) results in 0.100000...5..3 being stored in BigDecimal instance. In contrast BigDecimal ("0.1") stores exactly 0.1

Question : What is Precision and Scale ?
Precision is the total number of digits (or significant digits) of a real number
Scale specifies number of digits after decimal place

For example, 12.345 has precision of 5 and scale of 3

How to format BigDecimal Value without getting exponentiation in the result & Strip the trailing zeros?

We might get exponentiations in the calculation result if we do not follow some best practices while using Bigdecimal. Below is the code snippet which shows a good usage example of handling the calculation result using Bigdecimal.

public class BigDecimalForCurrency {
    public static void main(String[] args) {
        int scale = 4;
        double value = 0.11111;
        BigDecimal tempBig = new BigDecimal(Double.toString(value));
        tempBig = tempBig.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
        String strValue = tempBig.stripTrailingZeros().toPlainString();
        System.out.println("tempBig = " + strValue);

Top 50 Java Interview Questions for Investment Banking Domain & HealthCare IT

1. What do you understand by thread-safety ? Why is it required ? And finally, how to achieve thread-safety in Java Applications ?

Hint : discuss the need for the concurrent programming, using volatile, synchronization, Immutability & Atomic packages to address the concurrency problems. Discuss the Java Memory Model. Impact of final keyword in Java. Differences between wait and notify method in Object class.

2. What are the drawbacks of not synchronizing the getters of an shared mutable object ?

3. Discuss the Singleton Design Pattern ? How to make it thread-safe ? Discuss the Double Check Locking (DCL) ?

4. Can Keys in HashMap be made Mutable ? What would be the impact in that case ?

5. How would you implement your own ThreadPool in Java ? Discuss the designing part.

6. How would you implement a Stack or a Queue in Java ? It must be synchronized.

7. Discuss Big O notation for calculating relative performance of Algorithms. How do various collection methods perform in terms of Big O Notation ?

8. Implement Queue using an ArrayList.

9. What are the types of Inner classes with example of each ?

10. What is a tree map ? Discuss its underlying implementation i.e. red-black binary tree.

11. There are 1 million trades, you need to check if a given trade exists in those trades or not. Which Collection would you chose to store those 1 million trades and why ?

Hint : think from time complexity point of view and why HashSet could be a better data structure for storing these trades assuming we have sufficient memory to hold those items.

12. What is difference between StringBuilder and String ? Which one should be preferred.

13. In a program, multiple threads are creating thousands of large temporary StringBuilder objects. Life span of all those objects is 1 GC cycle. But somehow we are getting JVM pauses in our application. How would you troubleshoot the problem ?

Hint : Think from GC tuning perspective

14. What are memory generations in Hot Spot VM ? How generational GC's work ?

15. What is difference between Primary Key and Unique Key ?

16. What is clustered and non-clustered index in Sybase database ?

17. What is Outer and Inner Join ?

18. What is ADT ? We do not need to know how a data type is implemented in order to be able to use it.

19. Are you familiar with a messaging system i.e. MQ ? What is a QueueManager ? Why do you think the Queue is so important in banking world ?

20. How would you make an application asynchronous ? Can Message Queues help achieving this ?

21. How to achieve loose coupling in your application ?

22. What is TDD and how it helps Agile methodology of software development ?

23. How to make a class Immutable ? What purpose Immutablity solve ?

24. What is difference between Callable and Runnable ?

25. What are Inheritance strategies in JPA ?

26. Discuss Internals of HashMap and ConcurrentHashMap ?

27. What is best way to store Currency Values in Java application ?

28. What is AtomicInteger and how it is useful  in concurrent environment ?

29. What are key principles while designing Scalable Software Applications ?

30. What does Collections.unmodifiableCollection() do ? is it useful in multi-threading environment ?

31. How would you add an element to a Collection while iterating over it in a loop ?

32. There are 3 Classes A, B and C. C extends B and B extends A, each class has a method named add() with same signature (overriding). Is it possible to call A's add() method from Class C ? Reason ?

33. How would you write a simple Interceptor in Struts 2 which can log the request and response to an Action ?

34. What are database transaction isolation levels ? What is the default value for transaction isolation level.

35. How does Session Handling works in Servlet Environment?

36. What is difference between Http's redirect and forward request ?

37. Iterator Interface provides a remove() method but no add() method, Why ?

38. Can you give a try writing a rough Implementation for BlockingQueue in Java ?

39. What are Common Threading Issues in Java ?

40. Given a Collection of 1 million integers ranging between 1 and 9, Can you sort them all in Big O(n) time ?

41. How would you resolve Task Inter dependency pragmatically as is done in Ant ?

42. How would you sort 900 MB of data using 100 MB of RAM ?

43. What do you understand by GC tuning, What are GC pauses (stop the world)? How would you tune a given Java Program ?

44. What is a PriorityQueue ? How is it implemented in Java ? What are its usages ?

45. Your are give a file with millions of numbers in it. Find the 20 biggest numbers ?

46. What is difference between synchronized HashMap and a hashtable ?

47. What do you understand by Token Bucket Algorithm. What are its applications ?

48. What are the key principles when designing a software for performance efficiency ?

49. How would you describe Producer Consumer problem in Java ?

50. Design Phone Book for a mobile using TRIE (or a prefix tree)

51. How would you count word occurrence in a very large file ? How to keep track of top 10 occurring words?
52. What happens when you type a url in browser's address bar ?

For many other questions refer to my e-Book

Instant buy this PDF eBook from ShunyaFoundation

Questions that most Java candidates answer wrongly !!

There are few questions for which I rarely find right answer from the interview Candidates, here is the list ..

1. Is it required to synchronize the accessor of a shared mutable object in case of multi-threading ? Why ?

2. In which scenario StringBuilder should be preferred over String class ?

3. I am working on an application where millions of temporary StringBuilder objects are being created, due to which app is facing large GC pauses, how would you rectify the problem, assuming that memory available can not be increased to great extent.

4. How Atomic updates are different from their synchronized counterpart ?

5. When do we get the ConcurrentModificationException ? What constitutes the structural modifications in a collection?

6. Is it possible to write a method in Java which can swap two int variable ? What if we change the type from int to Integer ?

7. What is difference between Class and the Instance level locking ?

8. Can you prove a scenario where thread starvation occurs ?

9. Is it a mandate to make all fields final inside a immutable class ? If yes, why ?

10. How to fix Double Check Locking (DCL multi-threading singleton problem)?

11. What is Java Memory Model ? Who should read it ?

12. What is upper bound and lower bound in generics ?

13. What happens when an exception is thrown from a try block which has no catch clause. But in finally block, a value is returned by the method ? Discuss the scenario.

Good Software Practices in Java World as of Year 2013

Bad and outdated software practices come up with their own headache for the developer. Developers must keep them up-to date both technologically and functionally to have fun in programming.

1. Follow good software development practices like Test Driven Development. A very good test coverage (End To End and Unit Tests) keeps a developer away from last minute stress at production deployment time.
2. Automate all the mundane tasks related to development/deployment.
3. Take a software change request only if it is really required.
4. Keep refactoring your code base time to time, don't leave any duplicate code inside code base. Follow DRY (don't repeat yourself) strictly. Every object must have a single authoritative representation in the system.
5. Add an automated test case for every new bug found.
6. Document interfaces and reasons instead of implementation.
7. Use profiler to identify bottlenecks.
8. Use pair programming when bringing someone new up to speed and when tackling particularly tricky problems
9. Use tools to find the duplicates and refactor to reuse the existing code.
10. Work in small steps with frequent feedback and correction to avoid the last minute surprises.
11. Continuous Integration environment is must for rapid bug free development.