Q. What happens if you pass a primitive int value to a method that accepts

a) long primitive
b) float primitive
c) Float object
d) Number object

A.

a) A widening conversion takes place from int to long. So, no compile or run time error.
b) A widening conversion takes place from int to float. So, no compile or run time error.
c) compile-time error. primitive type int can be auto-boxed to type Integer, but type Integer and Float are derived from type Number, and don't have the parent child relationship. So, they cannot be implicityly or exlplicitly cast to each other.
d) primitive type int can be auto-boxed to type Integer, and then implicitly cast to type Number as Number and Integer have the parent child relationship. So, no compile or run time error.

Q. What is the purpose of the intern( ) method in the String class?A. It is used for moving the String objects created with the "new" operator to the internal string pool.

Q. Why is the String class in Java is final immutable object?A.

Security: the system can pass on sensitive info like password, credit card number, etc as read-only information without worrying that it will be altered.

Immutable objects are thread-safe. Two or more threads can work on an immutable object at the same time without any possibility of conflict. Immutable String objects are great to be used as keys in a map without worrying about the key getting modified.

To keep things simple. Since final, you can't subclass it to have two different String objects that have the same value. It is also easier to implement some of the string methods like substring because of its immutability.

Q. Is the finally block is always guaranteed to be execute?A. No. The finally block is not executed under circumstances like

System.exit( ) in try or catch block.

If the thread executing the try or catch block is killed or interrupted.

If an exception is thrown from the finally block and not handled, then remaining code in the finally block is ignored.

Java multi-threading interview questions and answers - coding

The Java multi-threading questions are very popular with the job interviewers as it can be not only hard to grasp, but also concurrency issues are very hard to debug and fix. So, it really pays to have people with the good understanding in this key area. We looked at some basic questions and answers at Java multi-threading questions and answers. Let's look at more coding based questions and answers to build up on what we had learned before.

Q. Explain how you would get a Thread Deadlock with a code example?A. The example below causes a deadlock situation by thread-1 waiting for lock2 and thread-0 waiting for lock1.

Q. What happens if you restart a thread that has already started?A. You will get the following exception

Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:595)
at deadlock.DeadlockTest.main(DeadlockTest.java:38)

Q. Can you write a program with 2 threads, in which one prints odd numbers and the other prints even numbers up to 10?A. In Java, you can use wait( ) and notifyAll( ) to communicate between threads. The code below demonstrates that.

Firstly, create the thread classes and the main method that creates the thread and run it.

Note: This a typical example of splitting tasks among threads. A method calls notify/notifyAll( ) as the last thing it does (besides return). Since the printOdd( ) and printEven( ) methods were void, the notifyAll( ) was the last statement. If it were to return some value, the notifyAll( ) would have been placed just before the return statement.

Q. Write a multi-threaded Java program in which, one thread generates odd numbers and write to a pipe and the second thread generates even numbers and write to another pipe, and a third thread receives the numbers from both the pipes and evaluates if the sum is multiples of 5?

A. In Unix, a pipe (“|”) operator helps you to redirect output from one command to another. PipedReader and PipedWriter classes in java.io package helps you to do the same. It helps you to redirect the read input into writer seamlessly. In Unix, two different processes on different address spaces can communicate using pipe, but in java two threads on the JVM can communicate using Piped ByteStream/CharacterStream within the same process (i.e same address space)

Here is the code snippet. The Writer threads responsible for writing odd and even numbers to the respective pipes.

Dec 14, 2011

JSF Interview Questions and Answers: event handling

Q. What are the different types of JSF events?A. JSF is an event driven framework.

Action Events: bound to UI Command objects like a Command Button or a Hyper-link. Whenever a user presses a Command Button or clicks a hyperlink these Events get generated.

Value Change Events: bound to UI Components like Text Field, Check-Box, List and Radio Buttons. The Value Change Event is fired as soon as the value that is displayed in the view is modified.

Phase Events: As you saw earlier in the JSF overview blog, the request processing life-cycle in JSF includes six phases and any JSF implementation will fire Phase events during the start and end of each phase. If we want to capture the Phase Events, then can define a Phase Listener. These are handy for debugging as well.

Q. How are events handled in JSF? What is the difference between these event handling mechanisms?A.Action handlers and event listeners provide an event driven mechanism. Every time a user does something like clicking a button, selecting an item from a drop down, or submitting a form, an event occurs. Event notification is then sent via HTTP to the server and handled by the FacesServlet. Events can invoke custom business logic or initiate page navigation.

JSF provides two types of methods for handling events; listeners and action handlers, both of these may be defined within a managed bean. A listener takes an FacesEvent as a parameter and a void return type, while an action handler takes no parameters and returns a String.

Action listeners are provided by JSF to make it easier to handle action events. An advantage of using a listener is that the FacesEvent object provides additional information, such as the form element that initiated the event. An action handler in contrast has no knowledge of the source of the event, but based upon its return value, can initiate page navigation. The example below shows using both event handlers and event listeners.

In the above example, when the button is clicked the JSF implementation calls the action listener during the Invoke Application phase. The action listener method then has a chance to perform any processing related to the command element selected by the user. You can perform any processing you need to inside the method. The method can have any name, must be public, return void, and accept an ActionEvent as its only parameter.

A ValueChangeEvent is useful whenever you want to be notified when there is a change in the value of a component, such as text modification in a text field or a check box selection. Most JSF components support the valueChangeListener attribute.

Dec 10, 2011

JSF Interview Questions and Answers: postback and viewstate

Q. What is the difference between initial request and postback?A. Initial request (e.g. HTTP GET) is the request that is made from a browser in order to display a page. Postback happens when the browser posts the page back to the server with form values, etc. Initial request is created by clicking a link, pasting an URL in address bar, while a postback request is create by posting a form by clicking a submit button or any post request. Initial request passes only restore View & Render Response phases, while postback request process under all phases described in the JSF life cycle diagram.

During the restore view phase of the life cycle, ViewHandler retrieves the ResponseStateManager object in order to test if the request is a postback or an initial request. If a request is a postback, the restoreView method of ViewHandler is called. This method uses the ResponseStateManager object to re-build the component tree and restore state.
The ResponseStateManager object is the only one that knows what rendering technology is being used and is therefore the only one that can look at a request, which is rendering-technology specifiec. Here are the basic steps.

An isPostBack method on ResponseStateManager returns true if the current request is a postback.

A getState method is called by the restoreView method of ViewHandler to retrieve the component tree state from the current request.

A writeState method that writes out the state to the client. This method is called by the renderView method of ViewHandler during the render response phase.

Q. What is a viewstate in JSF?A. In JSF, there is a viewstate associated with each page, which is passed back and forth with each submits. The reason for the viewtate is that the HTTP is a stateless protocol. The state of the components across requests need to be maintained. The viewstate can change in between requests as new controls like UIInput can be added or modified. The view state is divided into two parts.

Part 1: Structure of the components
Part 2: Defines the state of the components. For example. enabled/disabled, input values, checked/unchecked, selected item, etc.

Understanding the JSF lifecycle helps understand the viewstate.

It can be achieved by either storing the viewstate on the server side in a session and then passing the viewstate id to the client via a hidden field as shown below:

Dec 9, 2011

JSF Interview Questions and Answers: Seam

Q. How does Seam framework fit in with the JSF framework?A. JSF's major shortcoming is its heavy reliance on the HTTP session, especially when propagating data across a sequence of pages. Seam rectifies this with a conversational scope. Seam provides some hooks into the JSF life cycle to achieve this along with other benefits.

Dec 8, 2011

Observer design pattern for publish/Subscribe model

The design patterns are very popular with the interviewers and Java/J2EE Job Interview Companion covers GoF design patterns, JEE design patterns, and EJB design patterns. This blog entry covers the observer design pattern.

Q. What is an observer design pattern?A. The Observer pattern is a behavioral design pattern that allows an object (an Observer) to watch another object (a Subject). The subject and observer to have a publish/subscribe relationship. Observers can register to receive events from the Subject.

Some of the practical uses of observer pattern are:

When a change to one object requires changing of others, and you don't know how many objects need to be changed.

When an object should be able to notify other objects without making assumptions about who these objects are and not tightly coupling them.

When a report is received or an event occurs, a message needs to be sent to the subscribed handlers.

Examples:

Programming Swing based GUI applications where the listeners register them with events like button click, property change, etc.

Programming a stock market application to know when the price of a stock changes.

Programming a order placement or trading application to know the status changes like pending, filled, shipped, rejected, etc.

So, whenever you want to have the state change or other information, instead of polling every few second, register the observers with a subject.

Q. Can you list some Java interfaces that use the observer design pattern?A.

The Java Message Service (JMS) models the observer pattern, with its guaranteed delivery, non-local distribution, and persistence, to name a few of its benefits. The JMS publish-subscribe messaging model allows any number of subscribers to listen to topics of interest. When a message for the published topic is produced, all the associated subscribers are notified.

The Java Foundation Classes (JFC) like JList, JTree and the JTable components manipulate data through their respective data models. The components act as observers of their data models.

In the java.util package, we have the Observer interface and the Observable class.

In an MVC (Model-View-Controller) architecture, the view gets its own data from the model or in some cases the controller may issue a general instruction to the view to render itself. In others, the view acts as an observer and is automatically notified by the model of changes in state that require a screen update.

Q. What are the pros and cons of an Observer design pattern?A.

PROS:

Loose coupling between Subject and Observer: The subject knows only a list of observers, that implement the Observer interface, it does no know the concrete implementation of the Observer.

Broadcast communication: An event notification is broadcast to observers irrespective of the number of Observers

CONS:

If not used carefully the observer pattern can add unnecessary complexity.

The order of Observer notifications is undependable. Simply registering the observers in a particular order will not enforce their order of notification. You don't necessarily know if the first registered listener is notified first or last. If you need to have cascading notifications, where object X must be notified first, followed by object Y, you must introduce an intermediary object to enforce the ordering.

The possibility of a memory leak. A reference to the Observer is maintained by the Subject. Until the Subject releases the reference, the Observer cannot be removed by the garbage collector.

Q. What is difference between singleton and prototype bean?A. If you had noticed the above examples, the scope was set to "singleton". This means single bean instance per IOC container. In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.

Scopes:

singleton – Return a single bean instance per Spring IoC container. you would use singletons for stateless services where you will only have one instance of each service, and since they are stateless they are threadsafe.

prototype – Return a new bean instance each time when requested. you would use prototypes for stateful scenarios like request actions (e.g. in struts), so a new object gets created to handle each request.

Q24. How would you use Spring to send JMS based messagesA24. Here is some pseudocode that uses Spring with JNDI and JMS to send messages. It assumes that the ConnectionFactory and Destination values are configured via JNDI.

To send messages

Locate a ConnectionFactory, typically using JNDI.

Locate a Destination, typically using JNDI.

Create a Spring JmsTemplate with the ConnectionFactory.

Create a JmsTemplate using the ConnectionFactory.

Inject the JmsTemplate and the destination to your "MyAppMessageSender" to send messages using the jmsTemplate and the destination you just injected.

A sessiion needs to be created via the Spring class MessageCreator, and subsequently a message is created on the session created.

To receive messages

Locate a ConnectionFactory, typically using JNDI.

Locate a Destination, typically using JNDI.

Create a message listener class (e.g. com.MyAppListener)

Create a JMS message container by injecting ConnectionFactory, Destination, and the listener. The container is responsible for binding the listener to the queue.

Dec 5, 2011

Hibernate Interview questions and answers: cacheing

Q. What is a second-level cache in Hibernate?A. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the SessionFactory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. The second-level cache needs to be explicitly configured. Hibernate provides a flexible concept to exchange cache providers for the second-level cache. By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.

second-level cache reduces the database traffic by caching loaded objects at the SessionFactory level between transactions. These objects are available to the whole application, not just to the user running the query. The 'second-level' cache exists as long as the session factory is alive. The second-level cache holds on to the 'data' for all properties and associations (and collections if requested) for individual entities that are marked to be cached. It is imperative to implement proper cache expiring strategies as caches are never aware of changes made to the persistent store by another application. he following are the list of possible cache strategies.

Read-only: This is useful for data that is read frequently, but never updated. This is the most simplest and best-performing cache strategy.

Read/write: Read/write caches may be appropriate if your data needs to be updated. This carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when session.close() or session.disconnect() is called.

Nonstrict read/write: This is most appropriate for data that is read often but only occasionally modified.This strategy does not guarantee that two transactions won't simultaneously modify the same data.

Transactional: This is a fully transactional cache that may be used only in a JTA environment.

Note: The usage options are: transactional|read-write|nonstrict-read-write|read-only. The cache can also be enabled at different granular level (e.g. parent, children, etc). The active orders will be cached for 300 seconds.

Q. How does the hibernate second-level cache work?A. Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database. Hibernate's static initialize() method, which populates a proxy object, will attempt to hit the second-level cache before going to the database. The Hibernate class provides static methods for manipulation of proxies.

As a consequence of using the Hibernate second-level cache, you have to be aware of the fact that each call of a data access method can either result in a cache hit or miss. So, configure your log4j.xml to log your hits and misses.

<logger name="org.hibernate.cache">
<level value="DEBUG" />
</logger>

Alternatively, you can use Spring AOP to log the cache access on your DAO methods.

The second level cache is a powerful mechanism for improving performance and scalability of your database driven application. Read-only caches are easy to handle, while read-write caches are more subtle in their behavior. Especially, the interaction with the Hibernate session can lead to unwanted behavior.

Q. What is a query cache in Hibernate?A. The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries. Let us have a look how Hibernate uses the query cache to retrieve objects. In order to make use of the query cache we have to modify the person loading example as follows.

You also have to change the hibernate configuration to enable the query cache. This is done by adding the following line to the Hibernate configuration.

<property name="hibernate.cache.use_query_cache">true</property>

Q. What are the pitfalls of second level and query caches?A. Memeory is a finite resource, and over use or incorrect useage like cacheing the Order object and all its referenced objects can cause OutOfMemoryError. Here are some tips to overcome the pitfalls relating to cacheing.

1. Set entity’s keys as query parameters, rather than setting the entire entity object. Critreia representations should also use identifiers as parameters. Write HQL queries to use identifiers in any substitutable parameters such as WHERE clause, IN clause etc.

In the example below, the entire customer and everything he/she references would be held in cache until either the query cache exceeds its configured limits and it is evicted, or the table is modified and the results become dirty.

Instead of setting the whole customer object as shown above, just set the id.

final Order customer = ... ;
final String hql = "from Order as order where order.cusomer.id = ?"
final Query q = session.createQuery(hql);
q.setParameter(0, customer.getId());
q.setCacheable(true);

2. Hibernate's query cache implementation is pluggable by decorating Hibernate's query cache implementation. This involves overriding the put( ) method to check if a canonical equivalent of a query results object already exist in the Object[][], and assign the same QueryKey if it exists.

3. If you are in a single JVM using in memory cache only, use hibernate.cache.use_structured_entries=false in your hibernate configuration.

Here are some general performance tips:

1. Session.load will always try to use the cache. Session.find does not use the cache for the primary object, but cause the cache to be populated. Session.iterate always uses the cache for the primary object and any associated objects.

2. While developing, enable the show SQL and monitor the generated SQL.

<property name="show_sql">true</property>

Also enable the "org.hibernate.cache" logger in your log4j.xml to monitor cache hits and misses.

Note: The OrderServiceImpl will have the interceptors turned using AOP to manage transaction, logging, and deadlock retry. The diagram below gives a big picture of interceptors, service, and repository.

Note: The deadlock retry filter is an interesting one. When an exception is thrown, it is inspected using a pattern matching (i.e. regular expression) to see if it is due to deadlock. If it is due to deadlock the invocation is repeated. This makes the call again to the target, which is the OrderServiceimpl via the TransactionInterceptor, which starts a new transaction.

Here is an example of the custom interceptor -- myappLoggingInterceptor. Aspect-Oriented Programming (AOP) offers a better solution to many problems. he AOP Alliance project (aopalliance-x.x.jar) is a joint open-source project between several software engineering people who are interested in AOP and Java.