Thursday, September 02, 2004

General Java Interview Questions

Topics
JDBC
Inner Classes
Enterprise Java Beans
EJB Transactions
Design Patterns
Collections
Synchronization

Questions
Q) final ref or final primitive wat is the difference
Q) compile time polymorphism & run time polymorphism
Q) String & StringBuffer- when will u use wat?
Q)When will u use static variable or static method?
Q) Wat if there is an exception in ejbremove? Is the bean instance destroyed? Or it remains?
Q)Does instance of return true for the parent class of the class specified?
Q) How do u convert an int to a string?
Q)How will u implement composition?
Q)What r volatile variables? When r they used?
Q) When to use session bean & when to use entity bean?
Q) CMP vs BMP?
Q) Coarse-grained & fine-grained entity beans?
Q) When will u use interface & when an abstract class?
Q) Include Directive, Include Action
Q) Wat is difference between outer join & inner join?
Q) How do threads communicate with each other
Q) How do u convert a mutable class to immutable?
Q) why J2EE
Q) Y have interfaces with no methods eg - java.io.Serialisable, java.lang.Clonable, java.rmi.Remote ?
Q) how do u ensure garbage collector will pick up the object?
Q) how does indexing help?
Q) JSP Forward or redirect.
Q) what does clone do if not overridden?
Q) Difference between runtime exception & compile time exception.
Q) how do u manage state?
Q) What is a memory leak in java?
Q) What all can you synchronize?
Q) If you have String x="foo"; String y="foo"; String z="foo"; how many instances of "foo" do you get?
Q) What is typesafe enum?

1) JDBC
There are 3 classes associated with JDBC.
java.sql.Driver
java.sql.DriverManager
java.sql.Connection

Generally the procedure is to first register a jdbc driver with the drivermanager. This happens with the Class.forName(""). (when u load a class with forName(), the loading, linking & initialization occurs. The initialization of JDBC driver involves registering the driver with the driver manager)

Then connection is requested from the driver manager. The driver manager in turn search through all of the known java.sql.Driver implementations for the one that connects with the URL you provided.

There r 3 kinds of statements
CreateStatement or just Statement
Prepared statement
Callable Statement

Never use create statement. The results r unformatted
Prepared statements execute faster then statements
Callable statement is an extention of prepared statement
Use callable statement while calling SP

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.

It is possible to update resultset using updateRow() - JDBC drivers are not required to provide this functionality. To specify whether the resultset is updatable, in preparedStatement, add parameter ResultSet.CONCUR_UPDATABLE


2) 5 uses of inner classes:

it allows you to group classes that logically belong together and to control the visibility of one within the other

Each inner class can independently inherit from an implementation. Thus, the inner class is not limited by whether the outer class is already inheriting from an implementation
The inner class can have multiple instances, each with its own state information that is independent of the information in the outer class object.
In a single outer class you can have several inner classes, each of which implement the same interface or inherit from the same class in a different way. An example of this will be shown shortly.
The point of creation of the inner class object is not tied to the creation of the outer class object.
There is no potentially confusing "is-a" relationship with the inner class; it's a separate entity
Disadvantage: the compiler/virtual machine, treats an inner class just like any other class. In order for the inner class to have access to the private variables of the outer class, the variables are made default access - accessible to the package.

3) Enterprise Java Beans
It automatically takes into account - security, resource pooling, persistence, concurrency & transactional integrity

Rmi & iiop provide error & exception handling, parameter passing & passing of transaction & security context

Several clients can be connected to one ejb object, but only one client thread can access the bean instance at a time. If, for example, one of the clients invokes a method on the ejb object, no other client can access that bean instance until the method invocation is complete. If the method is part of a large transaction, then the bean instance cannot be accessed at all, except within the same transactional context, until the entire transaction is complete.

Session bean can never be reentrant & they throw remote exception if a loopback is attempted. Same is true for non-reentrant entity beans. U can make entity bean reentrant by specifying it in the deployment descriptor.

Remove methods are defined in javax.ejb.EJBHome interface. So the home interface inherits them.

ejbCreate method alwayz returns primary key with bmp & null for cmp.
For session bean, return type is void

PortableRemoteObject.narrow is needed to support the requirements of rmi over iiop. Because CORBA supports many different languages, casting is not native to CORBA. Therefore, to get remote reference to home, we must explicitly narrow the object returned by lookup. This has the same effect as casting

All beans have a default jndi context java:comp/env/ejb

EJBHome interface methods
EJBMetaData getEJBMetaData
HomeHandle getHomeHandle
Void remove

EJBMetaData interface methods
EJBHome getEJBHome
Class getHomeInterfaceClass
Class getPrimaryKeyClass
Class getRemoteInterfaceClass
Boolean IsSession

EJBObject interface methods
EJBHome getEJBHome
Handle getHandle
Object getPrimaryKey
Boolean isIdentical
Void remove

when u make a call getByPk,
ejbload happens. the data is put in the entitybean frm db.
the return is the stub. on each invocation of a method on entity bean, a remote call is made. if caching is done, the dta is there in entity bean. ejb load does not happen. So db call is saved.


4) Transactions - EJB
Problems: Dirty reads: a dirty read occurs when the first transaction reads uncommited changes made by a second transaction. If the second transaction is rolled back, the data read by the first transaction becomes invalid.
10:00:00 client 1 chooses cabin 99 to be reserved
10:00:02 client 2 reads the list of reservation. So cabin 99 is not available
10:00:03 client 1 pays. But credit card invalid. So transaction rolled back & cabin 99 is now available

Repeatable reads: a repeatable read is when data read is guaranteed to look the same if read again during the same transaction. A non-repeatable read is when the data retrieved in a subsequent read within the same transaction can return different results.
10:00:00 client 1 reads list of available cabins with 2 beds. Cabin 99 is in the list
10:00:02 client 2 changes bed count from 2 to 3 for cabin 99.
10:00:03 client 1 reexecutes read of list of available cabins with 2 beds. Cabin 99 is still in the list

Phantom read: phantom read occurs when new records added to the db are detectable by the transactions that started prior to the insert.
10:00:00 client 1 reads list of available cabins with 2 beds. Cabin 99 is in the list
10:00:02 client 2 makes a reservation on cabin 99
10:00:03 client 1 reexecutes read of list of available cabins with 2 beds. Cabin 99 is no longer in the list

generally do not use client initiated transaction. B'coz after successfully performing an operation, when the bean returns, it might throw, remote exception. So the client would not know whether the operation happened or no.

if a ejb component sends & receives message in the same component, then it is possible that it will keep on waiting till it receives a message(in relation to jms & mdb). The solution to this problem is - after sending this message, call commit on the jms session, which is your jms transaction helper object. This causes the outgoing message buffer to be flushed.

Transaction attributes to be specified in deployment descriptor

Required - if already within a transaction, then the bean is part of the transaction. If not transaction already started, it starts a new

RequiresNew - if starts a new transaction. If a transaction already exists, then that is suspended & a new transaction is created. When this bean is done, the old transaction is resumed.

Supports - it runs only in a transaction if the client has one- it joins the transaction. If the client does not have a transaction, the bean runs with no transaction at all.

Mandatory - mandates tht a transaction be already running when the bean method is called. If transaction is not running, the javax.ejb.TransactionRequired exception is thrown.

Not Supported - that ur bean cannot be involved in a transaction at all. The transaction is suspended & resumed when the bean method is over.

Never - that ur bean cannot be involved in a transaction at all. If the client calls the bean in a transaction, then java.rmi.remote/javax.ejb.EJBExxception exception is thrown

Transaction isolation attributes
READ_UNCOMMITTED
READ_COMMITTED - transaction cannot read uncommitted data. Data that is being changed by another transaction cannot be read.
REPEATABLE_READ - transaction cannot change data that is being read by another transaction.
SERIALISABLE - transaction has exclusive read & update privileges to data. Other transaction can neither read nor update the same data.

U are allowed to specify isolation levels on per method basis but this flexibility comes with an imp restriction: all methods invoked in the same transaction must have the same isolation level.

In Entity EJB, a transaction spans ejb load, method & ejb store.

In bean managed transactions, u might write transaction begin in ejb load & transaction end in ejb store. But ejb load & ejb store are called by the container. So u can never be sure. The transaction may never end. So bean managed transactions are illegal in entity beans.

In MDB
Container managed transaction, the message is read off in the same transaction as the business logic is executed. If something goes wrong, the transaction will roll back & message acknowledgement will occur.
Bean managed transaction, the transaction begins & ends after the message is received. You can use the deployment descriptor acknowledgement modes to instruct the container about when to acknowledge the messages.

There is no way to specify isolation level in container-managed bean in a portable way.


5) Design Patterns
Singleton
home factory required a single instance of the factory class
when data is cached in a hashtable, a single instance of the hashtable is required

example of factory pattern
ejbhome factory

flyweight pattern

command pattern - struts
here there is an abstract base class called Action. All the other classes extend this action class. They have one command "perform". On button click, the control goes to a common servlet. This servlet (ActionServlet) reads the xml file for the next operation to call. The path info is given as input, stuts config is read & corresponding action class name is obtained. Then on this name, the perform method is invoked.


6) Collections
The collection interface is a group of objects with duplicates allowed
Set interface extends collection but forbids duplicates
List extends Collection also allows duplicates & introduces positional indexing
Map extends neither Set nor Collection & forbids duplicate key

Set
-HashSet
-TreeSet(use it to extract elements in a sorted manner)
it is generally faster to add elements to a hash set then convert the collection to a treeset.
Eg. hashset for sparce matrix
Treeset for JList

List
-ArrayList(random access, without inserting or removing) )(corresponding historical is vector)
-LinkList()(if frequent add & remove elements in the middle of the list and only access elements sequentially)
eg. Arraylist for JcomboBox


Map
-HashMap(inserting, deleting and locating)(corresponding historical is Hashtable & properties)
-TreeMap(traversing the keys in a sorted manner)

Historical List
-Vector (implements List interface)
-Stack (extends vector)

Historical Map
-Hashtable (implements map)
-Properties (implements map extends Hashtable)

Historical collection classes- operations are synchronized.

Iterator u can traverse a collection & safely remove elements from the underlying collection.
If iterator is traversing a collection while underlying collection is being modified by another thread, then the iterator fails by throwing ConcurrentModificationException.

If u need synchronized map, using hashtable is faster then using synchronized hashmap.

Fastest to search is hashtable
Then binary search on sorted collection & quick sort

Can u iterate thru hashmap. - no u have to use entryset in order to convert map to set


7) Synchronization
Synchronized method -Only one thread is executing that method at a time. The object containing the synchronized method is locked..in the sense that no one can call a synchronized method on the same object while the synchronized method is getting executed.
Synchronized block - where u specify the object which is locked . only one thread will execute the block at one time. Useful when shared resource exists in the block of code. Eg. Document series number - u read it, increment it & save the new number. All this should happen only once at a time.
When u have a object in a synchronized method & the same object is accessed by the unsynchronized object, then the unsynchronized object can access that object b?coz since it is unsynchronized, it does not check if the object is locked.

Whenever control enters a synchronized method, the thread that called the method locks the object whose method has been called. Other threads cannot call a synchronized method on the same object until the object is unlocked.


Q) final ref or final primitive wat is the difference
A) if final primitive is used, u cannot change it.
If final ref is used, then u can change the properties of the object but not the address

Q) compile time polymorphism & run time polymorphism
A) overloading is compile time polymorphism. overriding is dynamic or runtime polymorphism.

Q) String & StringBuffer- when will u use wat?
A) String is a constant & Stringbuffer is modifiable.
When there r a lot of string manipulations, u use StringBuffer b'coz otherwise a lot of new objects are created.

Q)When will u use static variable or static method?
A) U use static when u want the variable or method to be accessed at class level without creating an instance of the class.
Typical use of static
· - The proper place to define utility methods (methods that take input and provide output only through passed parameters and the return value) . Methods that don't manipulate or use the state of an object or class I call utility methods
· A way to control access to objects and data. Public class variables are a different story. If a public class variable isn't final, it is a global variable: that nasty construct that is the antithesis of data hiding. There is never any excuse for a public class variable, unless it is final.

Q) Wat if there is an exception in ejbremove? Is the bean instance destroyed? Or it remains? ? can someone answer this question

Q)Does instance of return true for the parent class of the class specified?
A) yes

Q) How do u convert an int to a string?
A)Integer.toString(i);
ToString is a static method of integer. This method takes an interger & returns a String Object. In general what happens when u convert an object to another type or when u convert a primitive to an object
-consider the binary representation of the int & string.i.e. '\u0030' for 0 '\u0031' for 1.

Q)How will u implement composition?
A)Put the code in finalise to delete child objects. As finalise will be called when the parent is getting deleted.

Q)What r volatile variables? When r they used?
A)Volatile variables r variables which are updated each time a change is made to them & checked each time the value is used.

Q) When to use session bean & when to use entity bean?
A)
1) In session bean u can call save operation anytime whenever u wish. So more control. In entity bean, the container decides when to call ejbload & ejbstore methods. So no control.
2) Parameter passing
When u do a query in session bean, u get result set - pass by value
When u call get method on entityhome, u get stubs to server side objects - pass by reference.
In order to display data in gui, the client has to traverse the network if pass by reference is done. Hence performance penalty. U can work around this problem by collocating session bean with the entity bean & serializing the entity bean object before sending it to the client.
3) Caching. Session bean do not represent data hence it cannot be cached. Entity beans can be cached by setting up certain flags in the deployment descriptor. If data is shared, caching offers benefits else it is of no use. Eg of non-shared data is personal account information on amazon.com. eg of shared data is a product catalog of 100 hottest books on amazon.com
4) If entity bean then schema independence. However if session bean crafted correctly gives schema independence. (schema independence is if some column in table is changed, the impact in ejb layer is minimal)

Q) CMP vs BMP?
A)
1) Cmp entity beans if tuned properly, is higher performing than bmp. With bmp, it takes 2 sql stmts to load an entity bean: the finder method(to load primary key) & then ejbload() method.
2) Cmp is harder to debug.
3) Cmp may not handle complex mapping.
4) In cmp no hardcoding of database api such as jdbc. But this feature is imp only to those who r selling their bean to diff ppl with diff db requirements.
5) In ejb2.0 relationships can be mapped. In bmp, lot of scaffolding code has to be written.

Q) Coarse-grained & fine-grained entity beans?
A) One choice u have is to make some of the entity beans as java classes. These r called dependent value classes.

Q) When will u use interface & when an abstract class?
A) U use an interface when u don?t have common code. U use abstract class when u have code that can be shared.
When u want to change implementation behind a common interface, use interface. Eg. In a media player, u might want to change the algorithm that runs to play the media. So when a new algorithm comes up, u just implement that interface & use the new algorithm.
Abstract classes let you define some behaviors; they force your subclasses to provide others. This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array)

Q) include directive <%@ include file="child.jsp" %>
include action
A) The include directive includes the content of the file during the translation phase where as include action includes the content of the file during execution/request processing phase.
For include directive, JSP Engine adds the content of the inserted page at translation phase, so it does not have an impact on performance.
For include action, JSP Engine adds the content of the inserted page at run time which imposes extra overhead.

Q) Wat is difference between outer join & inner join?
A) Outer join is when you want all rows frm one table & only those rows frm other table which match the value from the table which has all rows.
Inner join is a simple join.
Left outer join is same as left outer join except that in left outer join, the (+) is on right side & in right outer join (+) is on left side.
Full outer join is all rows frm both table.

Q) How do threads communicate with each other
A) Threads communicate with one another thr semaphores or message queues. Semaphore is a integer. One example showing the use of semaphores is when one thread needs to send data (e.g. through a buffer) to another thread. In multithreading environments there is no guarantee in which order two threads will come to the point where the first thread is filling the data buffer and the other thread is reading it. Therefore, these two threads need to synchronize execution at the exchange point. Semaphore's logic for this case is fairly simple: the reader thread calls wait() before reading the buffer and "hangs" if the semaphore is not yet signaled. The writer thread calls post() after filling the buffer with data and thus signals the reader thread that the data buffer is ready. This schema ensures that the data buffer will be read by the second thread only when the data is actually ready

Q) How do u convert a mutable class to immutable?
A)
1. Make the class definition final
2. Remove all setter methods
3. Let the constructor set the attributes of the class
4. Don?t use any method that will change the state of the object.

Q) why J2EE
A) scalability- b?coz the application can be distributed.
Modularity
Isolation of concerns
Extensible
Maintainability

Q) Y have interfaces with no methods eg ? java.io.Serialisable, java.lang.Clonable, java.rmi.Remote ? Can anyone write answer to this

Q) how do u ensure garbage collector will pick up the object?
A) make the reference to the object null. U can hint the jvm to collect garbage by calling system.gc()

Q) how does indexing help?
A) Indexing is basically a binary tree is generated. The nodes are the key values & physical addresses to the row.

Q) JSP Forward or redirect.
A) Redirect is slow b?coz a new request is created. Forward does not create a new request. RequestDispatcher x = req.getRequestDispather("url"); x.forward(req, res);

Q) what does clone do if not overridden?
A) there are 2 cases in this.
Case1 -If clone is called on object which has only primitive attributes.
Case 2 - If clone is called on onject; which has other object as attributes

Clone is a protected method of Object class. So to invoke on clone, u have to override this method.
For case 1 - u override the clone method & just call super.clone() in order to get ur object cloned.
For case 2 - u override the clone method & write implementation to create a duplicate object of the attribute object of the class. This is required b'coz when u call super.clone() the attributes of the container Object which are object references, the address gets copied to the cloned container object. Hence the cloned container object will point to the same attribute object since the addresses are the same.

Now it creates a new object but the constructor will not be called.

Q) Difference between runtime exception & compile time exception.
A)u have to handle compile time exceptions while u don't have to handle runtime exceptions.

Q) how do u manage state?
A) Session, cookies, database, url rewriting, caching

Q) What is a memory leak in java?
A) Memory leak in java is when a java object cannot be garbage collected.

Q) What all can you synchronize
A) You can synchronize a block, a method, an object, a class

Q) If you have String x="foo"; String y="foo"; String z="foo"; how many instances of "foo" do you get?
A) one since JVM automatically internalizes String. Internalizing means that when string class maintains a pool of Strings. When a new String is created, it checks if the same string is present in the pool. if it is present, it just returns the object from the pool and if not present, the value is added to the pool. I think that automatic internalizing happens only for Strings defined during compile time.

Q)What is typesafe enum