Jun 29, 2014

Top 50 Core Java Interview questions you can't afford to get wrong

Core Java Interview Questions and Answers

1-10 Language Fundamentals every Java developer must know 11-23 OOP every Java developer must know 24-36 interfaces and generics every Java developer must know 37-42 garbage collection and pass-by-reference every Java developer must know 43-54 maps and objects every Java developer must know

Q1. What is the difference between “==” and equals in comparing Java String objects?
A1. Comparing two String objects using “==” instead of “equals( )”. When you use “==”, you are actually comparing two object references, to see if they point to the same object. For example:

public class StringEquals {

 public static void main(String[ ] args) {
   String s1 = "Hello";
   String s2 = new String(s1);
   String s3 = "Hello";

   System.out.println(s1 + " equals " + s2 + " -> " +  
                                                s1.equals(s2));      //true

   System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2)); //false
   System.out.println(s1 + " == " + s3+ " -> " + (s1 == s3));  //true  

The variable s1 refers to the String instance created by "Hello". The object referred to by s2 is created with s1 as an initializer, thus the contents of the two String objects are identical, but they are distinct objects having distinct references s1 and s2. This means that s1 and s2 do not refer to the same object and are, therefore, not ==, but equals( ) as they have the same value "Hello". The s1 == s3 is true, as they both point to the same object due to internal caching. The references s1 and s3 are interned and points to the same object in the string pool.

Q2. Can you explain how Strings are interned in Java?
A2. String class is designed with the Flyweight design pattern in mind. Flyweight is all about re-usability without having to create too many objects in memory. A pool of Strings is maintained by the String class. When the intern( ) method is invoked, equals(..) method is invoked to determine if the String already exist in the pool. If it does then the String from the pool is returned instead of creating a new object. If not already in the string pool, a new String object is added to the pool and a reference to this object is returned. For any two given strings s1 & s2, s1.intern( ) == s2.intern( ) only if s1.equals(s2) is true.

Two String objects are created by the code shown below. Hence s1 == s2 returns false.

//Two new objects are created. Not interned and not recommended.
String s1 = new String("A");             
String s2 = new String("A");  

Instead use:

String s1 = "A";
String s2 = "A";   

s1 and s2 point to the same String object in the pool. Hence s1 == s2 returns true.

Since interning is automatic for String literals String s1 = “A”, the intern( ) method is to be used on Strings constructed with new String(“A”).

Q3. Why String class has been made immutable in Java?
A3.  For security and performance.

Security: The main reason for immutability is security. In Java you pass file names, host names, login names, passwords, customer account numbers, etc as a string object. For example, had String been mutable, 'user 1' could log into a Java application using his user-name and password credentials, and then possibly change the name of his password file name, which is a String object from 'password1' to 'password2' before JVM actually places the native OS system call to open the file. This is a serious security breach allowing 'user 1' to open user 2's password file.

Performance: Immutable classes are ideal for representing values of abstract data (i.e. value objects) types like numbers, enumerated types, etc. If you need a different value, create a different object. In Java, Integer, Long, Float, Character, BigInteger and BigDecimal are all immutable objects. Immutable classes are inherently thread-safe, hence they are less error prone and can be used safely in a multi-threaded environment for better scalability. Optimization strategies like caching of hashcode, string pooling, etc can be easily applied to improve performance.

Q4. In Java, what purpose does the key words final, finally, and finalize fulfill?
A4. 'final' makes a variable reference not changeable, makes a method not over-ridable, and makes a class not inheritable.

'finally' is used in a try/catch statement to almost always execute the code. Even when an exception is thrown, the finally block is executed. This is used to close non-memory resources like file handles, sockets, database connections, etc till Java 7. This is is no longer true in Java 7.

Java 7 has introduced the AutoCloseable interface to avoid the unsightly try/catch/finally(within finally try/catch) blocks to close a resource. It also prevents potential resource leaks due to not properly closing a resource.

// pre Java 7

  BufferedReader br = null;

  try {
     File f = new File("c://temp/simple.txt");
     InputStream is = new FileInputStream(f);
     InputStreamReader isr = new InputStreamReader(is);
     br = new BufferedReader(isr);

     String read;

     while ((read = br.readLine()) != null) {
  } catch (IOException ioe) {
  } finally {
     //Hmmm another try catch. unsightly
     try {
       if (br != null)
       } catch (IOException ex) {

Java 7 – try can have AutoCloseble types. InputStream and OutputStream classes now implements the Autocloseable interface.

try (InputStream is = new FileInputStream(new File("c://temp/simple.txt"));
     InputStreamReader isr = new InputStreamReader(is);
     BufferedReader br2 = new BufferedReader(isr);) {

     String read;

     while ((read = br2.readLine()) != null) {

catch (IOException ioe) {

try can now have multiple statements in the parenthesis and each statement should create an object which implements the new java.lang.AutoClosable interface. The AutoClosable interface consists of just one method. void close() throws Exception {}. Each AutoClosable resource created in the try statement will be automatically closed without requiring a finally block. If an exception is thrown in the try block and another Exception is thrown while closing the resource, the first Exception is the one eventually thrown to the caller. Think of the close( ) method as implicitly being called as the last line in the try block.

'finalize' is called when an object is garbage collected. You rarely need to override it. It should not be used to release non-memory resources like file handles, sockets, database connections, etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize( ) method.

So, final and finally are used very frequently in your Java code, but the key word finalize is hardly or never used.

Q5. What value will the following method return?

public static int getSomeNumber( ){  
 return 2;     
   } finally {         
 return 1;     

A5. 1 is returned because 'finally' has the right to override any exception/returned value by the try..catch block. It is a bad practice to return from a finally block as it can suppress any exceptions thrown from a try..catch block. For example, the following code will not throw an exception.

public static int getSomeNumber( ){     
  throw new RuntimeException( );     
 } finally {         
  return 12;     

Q6. What can prevent execution of a code in a finally block?
A6. a) An end-less loop.

public static void main(String[ ] args) {
 try {
  System.out.println("This line is printed .....");
  //endless loop
  System.out.println("Finally block is reached."); // won't reach        

b) System.exit(1) statement.

public class Temp {

    public static void main(String[ ] args) {
        try {
            System.out.println("This line is printed .....");
            System.out.println("Finally block is reached.");// won't reach

c) Thread death or turning off the power to CPU.
d) An exception arising in a finally block itself.
e) Process p = Runtime.getRuntime( ).exec("");

If using Java 7 or later editions, use AutoCloseable statements within the try block.

Q7. Can you describe “method overloading” versus “method overriding”? Does it happen at compile time or runtime?
A7. Method overloading: Overloading deals with multiple methods in the same class with the same name but different method signatures. Both the below methods have the same method names but different method signatures, which mean the methods are overloaded.

public class {
     public static void evaluate(String param1);    // method #1
     public static void evaluate(int param1);       // method #2 

This happens at compile-time. This is also called compile-time polymorphism because the compiler must decide how to select which method to run based on the data types of the arguments. If the compiler were to compile the statement:

evaluate(“My Test Argument passed to param1”);

it could see that the argument was a string literal, and generate byte code that called method #1.

Overloading lets you define the same operation in different ways for different data.

Method overriding: Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures. Both the below methods have the same method names and the signatures but the method in the subclass MyClass overrides the method in the superclass BaseClass.

public class A {
   public int compute(int input) {                      //method #3
        return 3 * input;

public class B extends A {
   public int compute(int input) {                     //method #4
        return 4 * input;

This happens at runtime. This is also called runtime polymorphism because the compiler does not and cannot know which method to call. Instead, the JVM must make the determination while the code is running.

The method compute(..) in subclass “B” overrides the method compute(..) in super class “A”. If the compiler has to compile the following method,

public int evaluate(A reference, int arg2)  {
     int result = reference.compute(arg2);

The compiler would not know whether the input argument 'reference' is of type “A” or type “B”. This must be determined during runtime whether to call method #3 or method #4 depending on what type of object (i.e. instance of Class A or instance of Class B) is assigned to input variable “reference”.

A obj1 = new B( );
A obj2 = new A( );
evaluate(obj1);     // method #4 is invoked as stored object is of type B
evaluate(obj2);     // method #3 is invoked as stored object is of type A

Overriding lets you define the same operation in different ways for different object types.

Q8. What do you know about class loading? Explain Java class loaders? If you have a class in a package, what do you need to do to run it? Explain dynamic class loading?
A8. Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So, how is the very first class loaded? The very first class is specially loaded with the help of static main( ) method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.

Loads JDK internal classes, java.* packages as defined by the sun.boot.class.path system property. Typically loads the rt.jar and i18n.jar archives.
Loads jar files from JDK extensions directory as defined by the java.ext.dirs system property. Usually from the lib/ext directory of the JRE.
Loads classes from the system classpath as defined by the java.class.path property, which is set by the CLASSPATH environment variable or command line options -classpath or -cp as discussed earlier. The developers are responsible for providing the necessary classpath information.

Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true as explained in the above diagram.

Q9. Explain static vs. dynamic class loading?
A9. Classes are statically loaded with Java’s “new” operator.

class MyClass {
    public static void main(String args[]) {
       Car c = new Car( );

Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically.

//static method which returns a Class
Class.forName (String className); 

The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.

// A non-static method, which creates an instance of a 
// class (i.e. creates an object).
class.newInstance ( ); 

Static class loading throws “NoClassDefFoundError” if the class is not found and the dynamic class loading throws “ClassNotFoundException” if the class is not found.

Q10. What tips would you give to someone who is experiencing a class loading or “Class Not Found” exception?
A10. “ClassNotFoundException” could be quite tricky to troubleshoot. When you get a ClassNotFoundException, it means the JVM has traversed the entire classpath and not found the class you've attempted to reference.

1) Stand alone Java applications use -cp or -classpath to define all the folders and jar files to look for. In windows separated by ";" and in Unix separated by ":".

java -classpath "C:/myproject/classes;C:/myproject/lib/my-utility.jar;C:/myproject/lib/my-dep.jar" MyApp

2) Determine the jar file that should contain the class file within the classpath -- war/ear archives and application server lib directories. Search recursively for the class.

$ find . -name "*.jar" -print -exec jar -tf '{}' \; | grep -E  "jar$|String\.class"

You can also search for the class at

3) Check the version of the jar in the manifest file MANIFEST.MF, access rights (e.g. read-only) of the jar file, presence of multiple versions of the same jar file and any jar corruption by trying to unjar it with "jar -xvf ...". If the class is dynamically loaded with Class.forName("com.myapp.Util"), check if you have spelled the class name correctly.

4) Check if the application is running under the right JDK? Check the JAVA_HOME environment property

$  echo $JAVA_HOME 

Core Java Interview Questions and Answers

1-10 Language Fundamentals every Java developer must know 11-23 OOP every Java developer must know 24-36 interfaces and generics every Java developer must know 37-42 garbage collection and pass-by-reference every Java developer must know 43-54 maps and objects every Java developer must know


Can you write an abstract Java comparator that will work with multiple fields to sort on?

Comparators are used in Java to custom sort objects. You need good coding skills to write abstract classes.

Q. Can you write an abstract Comparator class that will allow more specific comparator classes like EmployeeComparator to sort an object like Employee shown below?

package test;

public class Employee {
 private String firstName;
 private String surname;
 private int age;
 public Employee(String firstName, String surname, int age, Gender gender) {
  this.firstName = firstName;
  this.surname = surname;
  this.age = age;
 protected String getFirstName() {
  return firstName;
 protected void setFirstName(String firstName) {
  this.firstName = firstName;
 protected String getSurname() {
  return surname;
 protected void setSurname(String surname) {
  this.surname = surname;
 protected int getAge() {
  return age;
 protected void setAge(int age) {
  this.age = age;
 public String toString() {
  return "Employee [firstName=" + firstName + ", surname=" + surname + ", age=" + age + "]\n";

A. Pay attention to the Generics, inner class, and access control modifiers. It may look easy, but try writing it yourself.

Step 1:  Create the "AbstractGenericComparator" that can be extended by more specific comparator classes to extend.

 package test;

import java.util.Comparator;

 * class is abstract, hence should have at least 1 abstract method. 
 * T is the type of object to compare 
 * S is the type of SortBy that defines --> Field and order for sorting
public abstract class AbstractGenericComparator<T, S> implements Comparator<T> {

 // array of multiple sort by fields
 private SortBy<S>[] sortBy;
 //takes var args 1 or more SortBy fields
 public AbstractGenericComparator(SortBy<S>... sortBy) {
  //fail fast & precondition check
  if (sortBy.length == 0) {
   throw new IllegalArgumentException("At least one SortByr must be supplied!");
  this.sortBy = sortBy;

 public int compare(T o1, T o2) {
  int result = 0;
  //sort by 1 or more fields.
  for (int index = 0; index < this.sortBy.length; index++) {
            result = compare(this.sortBy[index], o1, o2);
            if (result != 0) {
                return result;
        return result;
 protected SortBy<S>[] getSortBy() {
  return sortBy;

 protected abstract int compare(SortBy<S> sortBy, T o1, T o2);

 // static inner class
 public static class SortBy<S> {
  private S field;
  private boolean isAscending = true;
  protected S getField() {
   return field;
  protected void setField(S field) {
   this.field = field;
  protected boolean isAscending() {
   return isAscending;
  protected void setAscending(boolean isAscending) {
   this.isAscending = isAscending;


Step 2: Create the EmployeeComparator that extends AbstractGenericComparator.

package test;

public class EmployeeComparator<T,S> extends
  AbstractGenericComparator<Employee, String> {

 public EmployeeComparator(SortBy<String>... sortBy) {
  * simplified. Not handling null, etc at this point
  * Assuming that firstname, surname, and age are mandatory fields.
 protected int compare(SortBy<String> sortBy, Employee o1, Employee o2) {

  Employee e1 = (Employee) o1;
  Employee e2 = (Employee) o2;

  //Java 7 switch statement supports String
  switch (sortBy.getField()) {
  case "firstName":
   if (sortBy.isAscending()) {
    return e1.getFirstName().compareTo(e2.getFirstName());
   } else {
    return -e1.getFirstName().compareTo(e2.getFirstName());
  case "surname":
   if (sortBy.isAscending()) {
    return e1.getSurname().compareTo(e2.getSurname());
   } else {
    return -e1.getSurname().compareTo(e2.getSurname());
  case "age":
   if (sortBy.isAscending()) {
    return new Integer(e1.getAge()).compareTo(e2.getAge());
   } else {
    return  -new Integer(e1.getAge()).compareTo(e2.getAge());
   throw new UnsupportedOperationException("Reached unsupported comparison");


Step 3: Write a test class with main method.

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import test.AbstractGenericComparator.SortBy;

public class ComparatorTest {

 public static void main(String[] args) {
  //create Employee objects
  Employee emp1 = new Employee("Paul", "Smith", 15, Employee.Gender.Male);
  Employee emp2 = new Employee("Emma", "Smith", 28, Employee.Gender.Female);
  Employee emp3 = new Employee("Emma", "Smith", 18, Employee.Gender.Female);
  Employee emp4 = new Employee("John", "Anders", 17, Employee.Gender.Male);

  List<Employee> employees = new ArrayList<Employee>();

  //Create SortBY objects
  SortBy<String> sortByFirstName = new SortBy<String>();

  SortBy<String> sortBySurname = new SortBy<String>();

  SortBy<String> sortByAge = new SortBy<String>();

  System.out.println("Before sorting");
  //Create an EmployeeComparator
  EmployeeComparator<Employee, String> sorter = 
   new EmployeeComparator<Employee, String>(sortByFirstName,sortBySurname, sortByAge);
  Collections.sort(employees, sorter);
  System.out.println("\nafter sorting by firstName, surname, and age");
  //Create another EmployeeComparator
  EmployeeComparator<Employee, String> sorter2 = 
    new EmployeeComparator<Employee, String>(sortByAge,sortByFirstName,sortBySurname);

  Collections.sort(employees, sorter2);
  System.out.println("\nafter sorting by age,surname, and firstname ");


Before sorting
[Employee [firstName=Paul, surname=Smith, age=15]
, Employee [firstName=Emma, surname=Smith, age=28]
, Employee [firstName=Emma, surname=Smith, age=18]
, Employee [firstName=John, surname=Anders, age=17]

after sorting by firstName, surname, and age
[Employee [firstName=Emma, surname=Smith, age=18]
, Employee [firstName=Emma, surname=Smith, age=28]
, Employee [firstName=John, surname=Anders, age=17]
, Employee [firstName=Paul, surname=Smith, age=15]

after sorting by age,surname, and firstname 
[Employee [firstName=Paul, surname=Smith, age=15]
, Employee [firstName=John, surname=Anders, age=17]
, Employee [firstName=Emma, surname=Smith, age=18]
, Employee [firstName=Emma, surname=Smith, age=28]

Labels: ,

Jun 28, 2014

Working with Java BigDecimal class for monetary values

When you are working with monetary values in Java, you must use a BigDecimal data type. Many developers often have the following questions.

Q1. How to compare BigDecimal numerically?
This means 5.120 should be equal to 5.1200000. The default equals( ) implementation in BigDecimal class returns true only if two objects are numerically equivalent AND have the same scale(i.e. 5.120  is not equals( ) to 5.1200000).

Q2. How to check if an amount is zero, positive, or negative?
Q3. How to extract the decimal portion of the amount?
Q4. How to determine if it is an integer value?

Here is a utility class that answers the above questions

package com.writtentest10;

import java.math.BigDecimal;

public class BigDecimalUtils {

 private BigDecimalUtils() {


  * The 'equals'  method in BigDecimal class returns true 
  * only if the two objects are numerically equivalent AND
  * have the same scale so (4.130 != 4.130000000)
  * This method returns true if the two values are numerically equivalent
 public static boolean equals(BigDecimal value1, BigDecimal value2) {
  return (value1.compareTo(value2) == 0);

 public static boolean isZero(BigDecimal value) {
  return (value.signum() == 0);

 public static boolean isNonZero(BigDecimal value) {
  return (value.signum() != 0);

 public static boolean isPositive(BigDecimal value) {
  return (value.signum() == 1);

 public static boolean isNegative(BigDecimal value) {
  return (value.signum() == -1);

 public static BigDecimal getExponent(BigDecimal value) {
  return BigDecimal.valueOf(value.longValue());

 public static BigDecimal getMantissa(BigDecimal value) {
  if (isZero(value)) {
   return value;

  BigDecimal result = value.abs();
  BigDecimal exponent = getExponent(result);

  if (isZero(exponent)) {
   return result;

  return result.subtract(exponent);

 public static boolean isInteger(BigDecimal value) {
  return isZero(value) ? false : isZero(getMantissa(value));


The JUnit test class

package com.writtentest10;

import java.math.BigDecimal;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class BigDecimalUtilsTest {

 private boolean setUpIsDone = false;

 private BigDecimal positiveValue1;
 private BigDecimal positiveValue2;
 private BigDecimal negativeValue;

 public void init() {

  if (setUpIsDone) {

  positiveValue1 = BigDecimal.valueOf(25.12);
  positiveValue2 = BigDecimal.valueOf(25.1200);
  negativeValue = BigDecimal.valueOf(-25.12);

  setUpIsDone = true;

 public void testEqual() {
  Assert.assertTrue(BigDecimalUtils.equals(positiveValue1, positiveValue2));
  Assert.assertFalse(BigDecimalUtils.equals(positiveValue1, negativeValue));
 public void testPositiveNegativeAndZero() {
 public void testGetMantissa() {
 public void testIsInteger() {

Here is a real life example of using BigDecimal for monetary calculation with design patterns.

Labels: ,

Jun 26, 2014

Transaction management with Spring and JTA interview questions and answers

Q. What is a Transaction? What does setAutoCommit do?
A.  A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other operations fail as well. For example if you transfer funds between two accounts there will be two operations in the set

1. Withdraw money from one account.
2. Deposit money into other account.

These two operations should be completed as a single unit. Otherwise your money will get lost if the withdrawal is successful and the deposit fails. There are four characteristics (ACID properties) for a Transaction.

All the individual operations should either complete or fail. The design of the transaction should update the database correctly. Prevents data being corrupted by concurrent access by two different sources. It keeps transactions isolated or separated from each other until they are finished. Ensures that the database is definitely updated once the Transaction is completed.
Transactions maintain data integrity. A transaction has a beginning and an end like everything else in life. The setAutocommit(….), commit( ) and rollback( ) are used for marking the transactions (known as transaction demarcation). When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed immediately after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:

    Connection myConnection = dataSource.getConnection();
    // set autoCommit to false

    withdrawMoneyFromFirstAccount(.............);   //operation 1
    depositMoneyIntoSecondAccount(.............);   //operation 2
    myConnection .commit();
catch(Exception sqle){
     myConnection .rollback();
  }catch( Exception e){}
        if( conn != null) {
  } catch( Exception e) {}

The above code ensures that both operation 1 and operation 2 succeed or fail as an atomic unit and consequently leaves the database in a consistent state. Also, turning auto-commit off will provide better performance.

Q. What is transaction demarcation? What are the different ways of defining transactional boundaries?
A. Data Access Objects (DAO) are transactional objects. Each operation associated with CRUD operations like Create, Update and/or Delete operations should be associated with transactions. Transaction demarcation is the manner in which transaction boundaries are defined. There are two approaches for transaction demarcation.

There are 2 types of transaction demarcation

1. Declarative transaction demarcation
2.  Programmatic transaction demarcation

1. Declarative transaction demarcation:

The programmer declaratively specifies the transaction boundaries using transaction attributes for an EJB via ejb-jar.xml deployment descriptor.

Note: Spring framework has support for declarative transaction demarcation by specifying transaction attributes via Spring config files. If you choose Spring framework to mark the transaction boundaries, then you need to turn off transaction demarcation in your EJB by marking it as NotSupported.

Q. How are these declarative transactions know when to rollback?

EJBs: When the EJB container manages the transaction, it is automatically rolled back when a System Exception occurs. This is possible because the container can intercept “System Exception”. However, when an "Application Exception" occurs, the container does not intercept it and therefore leaves it to the code to roll back using ctx.setRollbackOnly() method.

Spring Framework: Transaction declaration format is:


By default transactions are rolled-back on java.lang.RuntimeException. You can control when transactions are committed and rolled back with the “+” or “-“ prefixes in the exception declaration. “+” means commit on exception (You can even force it on RuntimeException) and “-” means rollback on exception. You can specify multiple rules for rollback as “,” separated.

For example:  Following declaration will rollback transactions on RunTime exceptions and MyCheckedException, which is a checked exception.


2.  Programmatic transaction demarcation:

The programmer is responsible for coding transaction logic as shown above. The application controls the transaction via an API like JDBC API, JTA API, Hibernate API etc. JDBC transactions are controlled using the java.sql.Connection object. There are two modes: auto-commit and manual commit. Following methods are provided in the JDBC API via non-XA java.sql.Connection class for programmatically controlling transactions:

public void setAutoCommit(boolean mode);
public boolean getAutoCommit();
public void commit();
public void rollback();

For XA-Connections use the following methods on javax.transaction.UserTransaction.

public void begin();
public void commit();
public void rollback();
public int getStatus();
public void setRollbackOnly();
public void setTransactionTimeOut(int)

Q. What support does Spring framework have for transaction management?

1. Spring supports both global transactions across multiple transactional resources through JTA and resouce specific local transaction associated with a JDBC connection. It provides a consistent programming model to support both local and global transactions. You write your code once, and it can benefit from different transaction management strategies in different environmen.

2. Supports both declarative transaction management via AOP and programmatic transaction management with the Spring Framework transaction abstraction which can run over any underlying transaction infrastructure. With the preferred declarative model, developers typically write little or no code related to transaction management.

Step 1: Define your transaction manager in a Spring context file

<bean id="txnManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"/>
<tx:annotation-driven transaction-manager="txnManager"/>

Step 2: In your business service layer that makes calls to a number of daos, annotate to define your transaction demarcation

public int addUser(User user) {

The @Transactional annotation takes propagation and isolation levels as attributes, and the defaults being Propagation : Required and Isolation level : Default.

3. Spring framework has support for most transactional APIs such as JDBC, Hibernate, JPA, JDO, JTA etc. All you need to do is use proper transaction manager implementation class. For example org.springframework.jdbc.datasource.DriverManagerDataSource for JDBC transaction management and org.springframework.orm.hibernate3.HibernateTransactionManager for Hibernate as ORM tool.

4. The support for programmatic transaction management is provided via TransactionTemplate or PlatformTransactionManager implementation.

private PlatformTransactionManager txnManager;

public int addUser(User user) {
  TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
  TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
      //....transactional operations
   catch(Exception ex){

The Transaction Definition object encapsulates the transactional properties such as the isolation level, propagation behavior, timeout etc. The Transaction Status object represents the status of the executing transaction whether it is in new, completed, etc.

Q. What is a distributed (aka JTA/XA) transaction? How does it differ from a local transaction?
A. There are two types of transactions:

Local transaction: Transaction is within the same database. As we have seen above, with JDBC transaction demarcation, you can combine multiple SQL statements into a single transaction, but the transactional scope is limited to a single database connection. A JDBC transaction cannot span multiple databases.

Distributed Transaction (aka Global Transaction, JTA/XA transaction): The transactions that constitute a distributed transaction might be in the same database, but more typically are in different databases and often in different locations. For example, A distributed transaction might consist of money being transferred from an account in one bank to an account in another bank. You would not want either transaction committed without assurance that both will complete successfully. The Java Transaction API (JTA) and its sibling Java Transaction Service (JTS), provide distributed transaction services for the JEE platform. A distributed transaction (aka JTA/XA transaction) involves a transaction manager and one or more resource managers. A resource manager represents any kind of data store. The transaction manager is responsible for coordinating communication between your application and all the resource managers. A transaction manager decides whether to commit or rollback at the end of the transaction in a distributed system. A resource manager is responsible for controlling of accessing the common resources in the distributed system.

Q. What is two-phase commit?
A.  two-phase commit is an approach for committing a distributed transaction in 2 phases.

Q. What do you understand by JTA and JTS?
A. JTA is a high level transaction interface which allows transaction demarcation in a manner that is independent of the transaction manager implementation. JTS specifies the implementation of a Transaction Manager which supports the JTA. The code developed by developers does not call the JTS methods directly, but only invokes the JTA methods. The JTA internally invokes the JTS routines.

Q. What is a XA resource?
A. The XA specification defines how an application program uses a transaction manager to coordinate distributed transactions across multiple resource managers. Any resource manager that adheres to XA specification can participate in a transaction coordinated by an XA-compliant transaction manager.

JTA transaction demarcation requires a JDBC driver that implements XA interfaces like javax.sql.XADatasource, javax.sql.XAConnection and javax.sql.XAResource. A driver that implements these interfaces will be able to participate in JTA transactions. You will also require to set up the XADatasource using your application server specific configuration files, but once you get a handle on the DataSource via JNDI lookup, you can get a XA connection via javax.sql.DataSource.getConnection() in a similar manner you get a non-XA connections. XA connections are different from non-XA connections and do not support JDBC’s auto-commit feature. You cannot also use the commit( ), rollback( ) methods on the java.sql.Connection class for the XA connections. A J2EE component can begin a transaction programmatically using javax.transaction.UserTransaction interface or it can also be started declaratively by the EJB container if an EJB bean uses container managed transaction. For explicit (i.e. programmatic) JTA/XA transaction you should use the UserTransaction.begin( ), UserTransaction.commit() and UserTransaction.rollback() methods. For example:

// programmatic JTA transaction
InitialContext ctx = new InitialContext();
UserTransaction utx = (UserTransaction)ctx.lookup(“java:comp/UserTransaction”);

try { 
    DataSource ds = getXADatasource();
    Connection con = ds.getConnection(); // get a XAconnection.
    PreparedStatement pstmt = con.prepareStatement(“UPDATE Employee emp where =?”);
    pstmt.setInt(1, 12456);
   utx.commit();//transaction manager uses two-phase commit protocol to end transaction  
catch(SQLException sqle){
    throw new RuntimeException(sqle);

Q. Why JTA transactions are more powerful than JDBC transactions?
A. JTA transactions are more powerful than JDBC transactions because a JDBC transaction is limited to a single database whereas a JTA transaction can have multiple participants like:
  • JDBC connections.
  • JMS queues/topics.
  • Enterprise JavaBeans (EJBs).
  • Resource adapters that comply with JEE Connector Architecture  (JCA) specification.  

Labels: , , ,

Jun 25, 2014

What is the difference between strategy and command design patterns?

Many design patterns look similar, but there are subtle differences as I explained the differences between Proxy, Decorator, Adapter, Bridge, and Facade design patterns Why do Proxy, Decorator, Adapter, Bridge, and Facade design patterns look very similar? What are the differences? In this post, let's compare strategy and command patterns.

Q. What is the difference between a strategy and a command pattern?
A. Firstly, some example

Strategy - quicksort or mergesort, simple vs compound interest calculations, etc
Command - Open or Close actions, redo or undo actions, etc. You need to know the states undo.


public interface AbstractStrategy {
     abstract void execute(Object arg);

public class ConcreteStrategy implements AbstractStrategy {

    public void execute(Object arg) {
        // Work with passed-in argument.



public interface AbstractCommand {
     abstract void execute();

public class ConcreteCommand implements AbstractCommand {

    private Object arg;

    public ConcreteCommand(Object arg) {
        this.arg = arg;

    public void execute() {
        // Work with own state.


Q. Can you spot the subtle differences?
  1. Strategy handles how something should be done by taking the supplied arguments in the execute(....) method. For example simple and compound interest will be different classes like SimpleInterestStrategy and CompoundInterestStrategy with different algorithms. Command creates an object out of what needs to be done (i.e. hold state) so that these command objects can be passed around between other classes. The actions the command represent can be undone or redone by maintaining the state. There will tend to be a large number of distinct Command objects that pass through your application.
  2. Design patterns provide a common vocabulary among the designers and developers. So, by looking at the classes and interfaces suffixed with Strategy and Command, the designers and users will understand the intent (i.e. point 1)

Command design pattern example:

Here is an example where requests are batched and then either committed as a batch or if an exception is thrown, rolled back as a batch. 2 types of command objects are used to increment and decrement the count of number of requests added to a batch. Both these command objects maintain the count via the CountState object.

Step 1: The interface for the command objects.

public interface AbstractCommand {
    abstract void execute();
    abstract void undo();

Step 2: A POJO object to store count data.

public final class CountState {

  private int count;
  public void increment(){
  public void decrement() {
  public int getCount() {
   return this.count;

Step 3: Increment and Decrement command objects

public class IncrementCommand implements AbstractCommand {

 private CountState count;
 public IncrementCommand(CountState count) {
  this.count = count;

 private String previousString;

 public void execute() {

 public void undo() {

public class DecrementCommand implements AbstractCommand {

 private CountState count;
 public DecrementCommand(CountState count) {
  this.count = count;

 private String previousString;

 public void execute() {

 public void undo() {

Step 4: Now, the request processor class that is responsible for adding batching requests via addRequest() or removeRequest() methods and batch execution or rollback via commitBatch() and rollbackBatch() methods. This makes makes use of the command objects.

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

public class RequestProcessor {

 private Deque<AbstractCommand> commandStack = null;
 private AbstractCommand incCmd;
 private AbstractCommand decCmd;

 private Map<String, String> requestCollection = new HashMap<>();

 public RequestProcessor(AbstractCommand incCmd, AbstractCommand decCmd) {
  this.commandStack = new ArrayDeque<>();
  this.incCmd = incCmd;
  this.decCmd = decCmd;

 public void addRequest(String requestId, String requestTxt) {
  requestCollection.put(requestId, requestTxt);

 public void removeRequest(String requestId) {

 public void commitBatch() {
  // ...logic to action all the requests
  // left out for brevity
  this.commandStack = new ArrayDeque<>();

 public void rollbackBatch() {
  AbstractCommand cmd = null;
  while (!commandStack.isEmpty()) {
   cmd = commandStack.pop();

Finally, the client app that makes use of the RequestProcessor and other objects.

public class ClientApp {

 public static void main(String[] args) {
  CountState state = new CountState();
  AbstractCommand incCmd = new IncrementCommand(state);
  AbstractCommand decCmd = new DecrementCommand(state);
  RequestProcessor processor = new RequestProcessor(incCmd, decCmd);

  processor.addRequest("1", "productcode:123, price:25.50");
  processor.addRequest("2", "productcode:456, price:12.50");
  processor.addRequest("3", "productcode:789, price:14.50");

  // ...


  try {

   System.out.println("number of requests processed:" + state.getCount()); // 2
   throw new RuntimeException();

  } catch (Exception ex) {
   System.out.println("number of requests processed:" + state.getCount()); // 0

The strategy deign pattern example is covered in Java design pattern interview questions and answers: strategy and factory pattern

Labels: ,

Jun 24, 2014

Top 17 Unix commands Java developers use frequently

Unix for software developers

1.Top 17 Unix commands Java developers use frequently 2.History commands 3.Shell scripting 4. Reading from a file
5.Purging older files 6.Splitting and archiving files 7.Emulator, SSH client 8.Unix commands for developers 9.Unix basic interview Q&A

1. Find with grep to search for files with a certain text. For example, search all properties files where there are "inbox" search texts defined.

$find . -type file -name "*.properties" | xargs grep inbox \{\}; #
$find . -type f -name "*.properties" -exec grep "inbox" {} /dev/null \;

This will recursively search all sub folders as well. Very handy if you are searching for something. The addition of /dev/null is for the grep to consistently print the file name when it finds a match.

If you are searching within a single folder, for example, to list all the log files that have "job-no-300"

grep -l "job-no-300" *.log

To recursively delete .svn folders of a project to remove any links to subversion

find . -type d -name .svn -exec rm -rf {} \;

2. If a log file is too large, split it into smaller files before using less -200 xaaaa.

split -b 1m -a 3 PUWPD394.20140623.172525.log

files are split into xaaa, xaab, xaaac, etc.

3. Identify the jar file that has a particular class or resource file. For example, to find the jar files that has MyConnection.class filer. Handy for identifying class loading issues for batch job.

find . -name '*.jar' -print0 |  xargs -0 -I '{}' sh -c 'jar tf {} | grep MyConnection.class

4. find all the files that has URLs that are http:// with https:// with the power of sed command

find . -type f -name '*.properties' -exec sed -i 's/http\:\/\//https\:\/\//g' {} \;

5. Create a symbolic link

ln -s

now, -> Handy when you have different environmental properties files, and can use a symbolic link to connect to particular environment like test1, test2, test3, etc.

6. Execute a shell command

$./ -env test1 -logile myapp.log

where -env test1 and -logfile myapp.log are arguments passed to the shell script.

7. Run a shell script in the background even after you log out  the session. For example, kick off a long running batch job.

$nohup  ./ -env test1 -logile myapp.log &

nohup ensures that it runs even after you logout.  and & is for running in the background.

8. change directory, make a new directory, create an empty file, find the present folder, and list files.

$ cd folder1

$ mkdir folder2

$cd folder2

$touch test.txt   #new file

$pwd    #list current folder

$cat test.txt   #display contents
$more test.txt   #paginates

$ls -ltr
$ls -ltr *300* #all jobs with job number 300 

9. Copy or move files

$cp /test3/*.txt /test1/
$cp /test3/a.txt /test/b.txt # copy a file with another name
$mv /test3/a.txt /test/b.txt

If you mv, the source file will be deleted. You can use mv to rename a file as well.

10. history command to reuse some of the commands you already used.


$history | grep mkdir



11. Check a log file.

$less -200 myapp.log
tail -f myapp.log

shift+G to go to bottom of the file
g to go to beginning of the file
/INFO to search for "INFO"
:q to quit

12. Edit a file

$vi myapp.txt

a -> append
x --> delete a character

13. Java process control commands

$ps -ef | grep java
$kill-3 12345  #kill a process with pid 12345 

14 Network connections and sockets info. You can identify ports already in use.

$netstat -a | grep 444

15. archive the files in the current folder with tar.

tar cvzf myapp.tgz .   #z means gzip. c - create
tar xvzf myapp.tgz     #untar and un gzip x - extract

16. Transfer files with scp.

scp myappl.tgz   # copy to a server
scp .   # copy from a server

17. Commands to verify network connectivity

$ping hostname
$telnet hostname 25 #hostname and port number

This was meant to be a quick list. You can search for more detailed examples in this blog.


Jun 23, 2014

JNDI and LDAP interview questions and answers

Q. What is JNDI? And what are the typical uses within a JEE application?
A.  JNDI stands for Java Naming and Directory Interface. It provides a generic interface to LDAP (Lightweight Directory Access Protocol) and other directory services like NDS (Novell Directory Service), DNS (Domain Name Service) etc. It provides a means for an application to locate components that exist in a name space according to certain attributes. A JEE application component uses JNDI interfaces to look up and reference system-provided and user-defined objects in a component environment. JNDI is not specific to a particular naming or directory service. It can be used to access many different kinds of systems including file systems.

Q. What resources can you look up via a JNDI tree?
A. The JNDI API enables applications to look up objects such as DataSources, EJBs, MailSessions, JMS connection factories and destinations (Topics/Queues) by name. These Objects can be loaded into a JNDI tree using a JEE application server’s administration console. To load an object in a JNDI tree, choose a name under which you want the object to appear in a JNDI tree. The JEE deployment descriptors indicate the placement of JEE components in a JNDI tree.

Q. What are the parameters you need to define for a JNDI connectivity?

The name service provider class name (WsnInitialContext for WebSphere application server).

Map env = new HashMap(); 

The provider URL: The name service hostname and port number.

env.put(Context.PROVIDER_URL, " iiop://localhost:1050"); 
Context ctx = new InitialContext(env);

Q. Can you compare JNDI, File system, and database?
A. JNDI is like a file system or a Database.

File System JNDI Database
File system starts with a mounted drive like c:\ JNDI starts with an InitialContext. i.e. new InitialContext().
Database instance

Uses a subdirectory. C:\subdir1 Navigate to a sub-context. e.g. Subcontext1 Tablespace
Access a subdirectory c:\subdir1\subdir2 Drill down through other sub-contexts. e.g. subcontext1/subcontext2 Table
Access a file. C:\subdir1\subdir2\myFile
Access an object or a service.
New InitialContext().lookup(“objectName”);



Select * from demo.myTable

Q. What is a JNDI InitialContext?
A. All naming operations are relative to a context. The InitalContext implements the Context interface and provides an entry point for the resolution of names.

Q. What is an LDAP server? And what is it used for in an enterprise environment?
A.  LDAP stands for Lightweight Directory Access Protocol. This is an extensible open network protocol standard that provides access to distributed directory services. LDAP is an Internet standard for directory services that run on TCP/IP. Under OpenLDAP and related servers, there are two servers – slapd, the LDAP daemon where the queries are sent to and slurpd, the replication daemon where data from one server is pushed to one or more slave servers. By having multiple servers hosting the same data, you can increase reliability, scalability, and availability.

It defines the operations one may perform like search, add, delete, modify, change name It defines how operations and data are conveyed.

LDAP has the potential to consolidate all the existing application specific information like user, company phone and e-mail lists. This means that the change made on an LDAP server will take effect on every directory service based application that uses this piece of user information. The variety of information about a new user can be added through a single interface which will be made available to Unix account, NT account, e-mail server, Web Server, Job specific news groups etc. When the user leaves his account can be disabled to all the services in a single operation.

So, LDAP is most useful to provide “white pages” (e.g. names, phone numbers, roles etc) and “yellow pages” (e.g. location of printers, application servers etc) like services. Typically in a JEE application environment it will be used to authenticate and authorise users.

Q. Why use LDAP when you can do the same with relational database (RDBMS)?
A. In general LDAP servers and RDBMS are designed to provide different types of services. LDAP is an open standard access mechanism, so an RDBMS can talk LDAP. However the servers, which are built on LDAP, are optimized for read access so likely to be much faster than RDBMS in providing read access. So in a nutshell, LDAP is more useful when the information is often searched but rarely modified. (Another difference is that RDBMS systems store information in rows of tables whereas LDAP uses object oriented hierarchies of entries.) .

Key LDAP Terms:

DIT: Directory Information Tree. Hierarchical structure of entries, those make up a directory.

DN: Distinguished Name. This uniquely identifies an entry in the directory. A DN is made up of relative DNs of the entry and each of entry’s parent entries up to the root of the tree. DN is read from right to left and commas separate these names. For example ‘cn=Peter Smith, o=ACME, c=AUS’.

objectClass: An objectClass is a formal definition of a specific kind of objects that can be stored in the directory. An ObjectClass is a distinct, named set of attributes that represent something concrete such as a user, a computer, or an application.

LDAP URL: This is a string that specifies the location of an LDAP resource. An LDAP URL consists of a server host and a port, search scope, baseDN, filter, attributes and extensions. Refer to diagram below:

So the complete distinguished name for bottom left entry (ie Peter Smith) is cn=Peter Smith, o=ACME, c=AUS. Each entry must have at least one attribute that is used to name the entry. To manage the part of the LDAP directory we should specify the highest level parent distinguished names in the server configuration. These distinguished names are called suffixes. The server can access all the objects that are below the specified suffix in the hierarchy. For example in the above diagram, to answer queries about ‘Peter Smith’ the server should have the suffix of ‘o=ACME, c=AUS’. So we can look for “Peter Smith” by using the following distinguished name:

cn=Peter Smith, o=ACME, c=AUS   //where o=ACME, c=AUS is the suffix

LDAP schema: defines rules that specify the types of objects that a directory may contain and the required optional attributes that entries of different types should have.

Filters: In LDAP the basic way to retrieve data is done with filters. There is a wide variety of operators that can be used as follows: & (and), | (or), ! (not), ~= (approx equal), >= (greater than or equal), <= (less than or equal), * (any) etc.

(& (uid=a*) (uid=*l) )

Q. So where does JNDI fit into this LDAP?
A. JNDI provides a standard API for interacting with naming and directory services using a service provider interface (SPI), which is analogous to JDBC driver. To connect to an LDAP server, you must obtain a reference to an object that implements the DirContext. In most applications, this is done by using an InitialDirContext object that takes a Hashtable as an argument:

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, “com.sun.jndi.ldap.LdapCtxFactory”);   
env.put(Context.PROVIDER_URL, “ldap://localhost:387”);
env.put(Context.SECURITY_AUTHENTICATION, “simple”);
env.put(Context.SECURITY_PRINCIPAL, “cn=Directory Manager”);
env.put(Context.SECURITY_CREDENTIALS, “myPassword”);
DirContext ctx = new InitialDirContext(env);

Labels: , ,

Jun 22, 2014

How to write internalized Java applications? What do you understand by the terms internationalization (i18n) and localization (l10n) relating to Java programming? What is a ResourceBundle?

Localization (aka i10n, where 10 is the number of letters between the letter ‘i’ and the letter ‘n’ in the word localization ) refers to the adaptation of an application or a component to meet the language, cultural and other requirements to a specific locale (i.e. a target market).

Internationalization (aka i18n, where 18 is the number of letters between the letter ‘i’ and the letter ‘n’ in the word internationalization) refers to the process of designing a software so that it can be localized to various languages and regions cost-effectively and easily without any engineering changes to the software. A useful website on i18n is

Q. What are the characteristics of an internalized program?
  • The same executable can run worldwide without having to recompile for other or new languages. 
  • Text messages and GUI component labels are not hard-coded in the program. Instead they are stored outside the source code in “.properties” files and retrieved dynamically based on the locale. 
  • Culturally dependent data such as dates and currencies appear in formats that conform to end user's region and language. (e.g. USA date format mm/dd/yyyy, Australian date format dd/mm/yyyy). 

Q. What are the different types of data that vary with region or language?
A. Messages (error messages, warning messages, info messages, etc), dates, currencies, numbers, measurements, phone numbers, postal addresses, tax calculations, graphics, icons, GUI labels, sounds, colors, online help, etc.

Q. What is a Locale?
A.  A Locale has the form of xx_YY (xx – is a two character language code && YY is a two character country code. E.g. en_US (English – United States), en_GB (English - Great Britain), fr_FR (french - France). The java.util.Locale class can be used as follows:

Locale locale1 = new Locale(“en”, “US”);
Locale locale2 = Locale.US;
Locale locale3 = new Locale(“en”);
Locale locale4 = new Locale(“en”, “US”, “optional”); // to allow the possibility of more than one 
                                                     // locale per language/country combination.

locale2.getDefault().toString();         //  en_US
locale2.getLanguage();                   //  “en” 
locale2.getCountry();                    //  ”US”

Resource bundles can be created using the locale to externalize the locale-specific messages:

   Greetings = Hello

   Greetings = Bonjour

These resource bundles reside in classpath and gets read at runtime based on the locale.

Locale currentLoc = new Locale(“fr”, “FR”); 
ResourceBundle messages = ResourceBundle.getBundle(“Message”, currentLoc);
System.out.println(messages.getString(“Greetings”));  //prints Bonjour

Note: When paired with a locale, the closest matching file will be selected. If no match is found then the default file will be the In JEE, locale is stored in HTTP session and resource bundles (stored as *.properties files under WEB-INF/classes directory) are loaded from the web.xml deployment descriptor file. Locale specific messages can be accessed via tags (e.g. Struts, JSTL etc).

The java.text package consists of classes and interfaces that are useful for writing internationalized programs. By default they use the default locale, but this can be overridden. E.g. NumbeFormat, DateFormat, DecimalFormat, SimpleDateFormat, MessageFormat, ChoiceFormat, Collator (compare strings according to the customary sorting order for a locale) etc.


Date now = new Date();
Locale locale = Locale.US;

String s = DateFormat.getDateInstance(DateFormat.SHORT, locale).format(now);

NumberFormat usFormat = NumberFormat.getInstance(Locale.US);
String s1 = usFormat.format(1785.85);  // s1   1,785.85

NumberFormat germanyFormat = NumberFormat.getInstance(Locale.GERMANY);
String s2 = germanyFormat.format(1785.85);  // s2  1.785,85

To use default locale:

To use specific locale:

Q. When a web application has users with different time zones, how will you manage dates and time in the system in a manner that looks consistent to all users
  • UTC is the coordinate universal time in the UK (like Greenwhich mean time). All time zones are calculated as offsets to UTC time. For example, Sydney is UTC+10, India is UTC+5.30, etc.
  • During somer, some regions do have the daylight savings. UTC time is independent of daylight savings time and it needs to be taken into consideration.
  • If your application needs to store dates and time internally, for example in a database, convert it to UTC time before storing it.
  • When the user retrieves records with date/time, it gets converted to their locale time as users like to see that date and time converted to his own time zone.
  • Websites need to capture the user customization info like preferred language, country of residence, current location, preferred time zone

Q. What is the difference between String.compareTo( ) and
A. Every language has its own rules for how strings and letters are sorted. So, using the String.compareTo( ) method may not work for all languages. So, you need use a java.text.Collator instance created for a specific Locale.

Locale   locale = Locale.UK;
Collator collator = Collator.getInstance(locale);
int result ="Apple", "Apple");

Q. How does Java keep stings internally?
A. In Java all strings are kept in unicode (UTF-16 is 16 bit unicode). Since not all text received from users or the outside world is in unicode, your application may have to convert from non-unicode to unicode when reads and do the reverse by converting from unicode to non-unicode when writes. The Java String class and io package have methods to perform this conversion.

bytes[] bytes = str.getBytes(Charset.forName("UTF-8"));
Reader      reader      = new InputStreamReader(inputStream,


Jun 21, 2014

JDBC Interview Questions and Answers

Q. What is JDBC? How do you connect to a database?
A.  JDBC stands for Java DataBase Connectivity. It is an API which provides easy connection to a wide range of databases. To connect to a database we need to load the appropriate driver and then request for a connection object. The Class.forName(….) will load the driver and register it with the DriverManager.

Class.forName(“oracle.jdbc.driver.OracleDriver”); //dynamic class loading
String url = jdbc:oracle:thin:@hostname:1526:myDB;
Connection myConnection =  DriverManager.getConnection(url, “username”, “password”);

The driver jar file (e.g. ojdbc14.jar) needs to be in the classpath.

Q. What is a datasource?
A.  The DataSource interface provides an alternative to the DriverManager for making a connection. DataSource makes the code more portable than the  DriverManager because it works with JNDI and it is created, deployed and managed separately from the application that uses it. If the DataSource location changes, then there is no need to change the code, but change the configuration properties in the server. This makes your application code easier to maintain. DataSource allows the use of connection pooling and support for distributed transactions. A DataSource is not only a database but also can be a file or a spreadsheet. A DataSource object can be bound to JNDI and an application can retrieve and use it to make a connection to a database. JEE application servers provide tools to define your DataSource with a JNDI name. When the server starts it loads all the DataSources into the application server’s JNDI service.

DataSource configuration properties are shown below:

JNDI Name = jdbc/myDataSource
URL = jdbc:oracle:thin:@hostname:1526:myDB
UserName, Password
Implementation class name = oracle.jdbc.pool.OracleConnectionPoolDataSource
Jar file in the Classpath = ojdbc14.jar
Connection pooling settings like = minimum pool size, maximum pool size, connection timeout, statement cache size etc.

Once the DataSource has been set up, then you can get the connection object as follows:

Context ctx = new InitialContext(); //JNDI context
DataSource ds = (DataSource)ctx.lookup("jdbc/myDataSource"); 
Connection myConnection = ds.getConnection(“username”,”password”);

Q. Why should you prefer using a DataSource?
A. Best practice: In a very basic application a Connection obtained from a DataSource and a DriverManager are identical. But, the JEE best practice is to use DataSource because of its portability, better performance due to pooling of valuable resources, and the JEE standard requires that applications use the container’s resource management facilities to obtain connections to resources. Every major web application container provides pooled database connection management as part of its resource management framework.

Design Pattern: JDBC architecture decouples an abstraction from its implementation so that the implementation can vary independent of the abstraction. This is an example of the bridge design pattern. The JDBC API provides the abstraction and the JDBC drivers provide the implementation. New drivers can be plugged-in to the JDBC API without changing the client code.

Q. Have you used a Data Access Object (DAO) pattern? Why is it a best practice to use a DAO pattern
A. A DAO class provides access to a particular data resource in the resource tier or data tier(e.g. relational database, XML, mainframe, etc) without coupling the resource’s API to the business logic in the middle tier. A tier is a physical machine, whereas a layer is logical.

For example, you may have a EmployeeServiceImpl in the business logic layer with business logic, and  uses EmployeeDAO in the data access layer for accessing data in the data tier.  EmployeeServiceImpl uses the interface EmployeeDAO as opposed to the implementation. This is the best practice of "coding to interface not implementation". If your data resource change from a database to a Mainframe system, then reimplementing EmployeeDAO for a different data access mechanism (to use a mainframe Connector) would have little or no impact on any classes like EmployeeServiceImpl that uses EmployeeDAOEmployeeDAOImpl can even decide to use hibernate framework instead of using the JDBC directly. The EmployeeServiceImpl will not be impacted as long as the contract in EmployeeDAO is met.

Inversion of control (IoC) frameworks like Spring framework promotes the design principle of “code to interface not implementation”.

Q. What are the best practices relating to exception handling to make your DAOs more robust and maintainable?
  • If you catch an exception in your DAO code, never ignore it or swallow it because ignored exceptions are hard to troubleshoot. DAO class methods should throw checked exceptions only if the caller can reasonably recover from the exception or reasonably handle it (e.g. retry operations in optimistic concurrency control). If the caller cannot handle the exception in a meaningful way, consider throwing a runtime (i.e. unchecked) exception. For example, Hibernate 3 exceptions are all runtime exceptions. 
  • DAO methods should not throw low level JDBC exceptions like java.sql.SQLException. A DAO should encapsulate JDBC rather than expose it to rest of the application. Use chained exceptions to translate low-level exceptions into high-level checked exceptions or runtime exceptions. DAO methods should not throw java.lang.Exception because it is too generic and does not convey any underlying problem. 
  • Log your exceptions, configuration information, query parameters, etc.

Q. What are JDBC Statements? What are different types of statements? How can you create them?
A.  A statement object is responsible for sending the SQL statements to the Database. Statement objects are created from the connection object and then executed.

Statement stmt = myConnection.createStatement();
ResultSet rs = stmt.executeQuery(“SELECT id, name FROM myTable where id =1245”); //to read
stmt.executeUpdate(“INSERT INTO (field1,field2) values (1,3)”);//to insert/update/delete/create 

The types of statements are:
  • Statement (regular statement as shown above) .
  • PreparedStatement (more efficient than statement due to pre-compilation of SQL and prevents SQL injection attack. Always use this over a statement) .
  • CallableStatement (to call stored procedures on the database).

To use prepared statement:

PreparedStatement prepStmt = 
                 myConnection.prepareStatement("SELECT id, name FROM myTable where id = ? ");
prepStmt.setInt(1, 1245);

Callable statements are used for calling stored procedures.

CallableStatement calStmt = myConnection.prepareCall("{call PROC_SHOWMYBOOKS}");
ResultSet rs = cs.executeQuery(); 

To learn more about using JDBC with Spring and Hibernate framework:

Labels: ,

Password based Encryption and decryption example in Java

Password-Based Encryption is can be accomplished using the PBEParameterSpec class. For example, if you are storing passwords for your database or RESTful web service connections in your properties file, they need to be encrypted and base64 encoded. You can't have clear text passwords lying around in properties files, URLs, or database tables.

Here is a sample CryptoHelper class that make use of PBEParameterSpec to perform password protected encryption and decryption.

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.PBEKeySpec;

public class CryptoHelper {

    // Define the salt
    private static final byte[] SALT = {(byte)0x41, (byte)0x42, (byte)0x43, (byte)0x44,
                                        (byte)0x45, (byte)0x46, (byte)0x47, (byte)0x48}; //A to H

    // Iteration count
    private static final int COUNT          = 20;

    private static final String ALGORITHM   = "PBEWithMD5AndDES";

    // Create PBE parameter set
    private static PBEParameterSpec pbeParamSpec = new PBEParameterSpec(SALT, COUNT);

     * Not necessary at the moment as all methods are currently static.
    protected CryptoHelper() {

     * Encrypt a byte buffer using the given password.
     * @param   data        The data to be encrypted.
     * @param   password    The password to be used.
     * @return  An encrypted byte array buffer.
     * @exception   CryptoException     Hmmm, we have a problem.
     * @see #decrypt(byte[],String)
    public static byte[] encrypt(byte[] data, String password)  {
        return doCipher(Cipher.ENCRYPT_MODE, data, password);

     * Decrypt a byte buffer using the given password.
     * @param   data        The data to be decrypted.
     * @param   password    The password to be used.
     * @return  The original byte array buffer.
     * @exception   CryptoException     Hmmm, we have a problem.
     * @see #encrypt(byte[],String)
    public static byte[] decrypt(byte[] data, String password)  {
        return doCipher(Cipher.DECRYPT_MODE, data, password);

     * Performs password based encryption/decryption.
     * @param   mode     Encrypt/Decrypt (Cipher.DECRYPT_MODE/Cipher.ENCRYPT_MODE)
     * @param   data     The data to be encrypted/decrypted.
     * @param   password The password to be used.
     * @return  The transformed byte buffer.
     * @exception   CryptoException     Hmmm, we have a problem.
    private static byte[] doCipher(int mode, byte[] data, String password) {
        try {
            // First generate a SecretKey from the password given...
            PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

            // Create PBE Cipher
            Cipher pbeCipher = Cipher.getInstance(ALGORITHM);

            // Initialize PBE Cipher with key and parameters
            pbeCipher.init(mode, pbeKey, pbeParamSpec);

            // Encrypt/Decrypt the data
            return pbeCipher.doFinal(data);
        } catch(Exception ex) {
            throw new RuntimeException("Cryptography Exception: " + ex);

The class with the method using the helper class.

//You can use any Base64 encoding library 
import org.eclipse.persistence.internal.oxm.conversion.Base64;

public class CryptographyTest {
 public static void main(String[] args) {
   String clearDatabasePassword = "passw0rd";
   String encryptionPasword = "changeit";
   byte[] encryptedDatabasePassword = CryptoHelper.encrypt(clearDatabasePassword.getBytes(), 
   System.out.println("Encrypted:" + new String(encryptedDatabasePassword));
   byte[] decryptedDatabasePasswor = CryptoHelper.decrypt(encryptedDatabasePassword, 
   System.out.println("Decrypted:" + new String(decryptedDatabasePasswor));
   //gives you the readable characters that can be used in your properties file
   System.out.println("Encrypted and Base64 encoded:" + new String(Base64.base64Encode(

The output is

Encrypted:—¥3urÓ«É |Ã÷ Œ±)
Encrypted and Base64 encoded:l6UzdXLTq8mgfMP3FIyxKQ==

Now, you can have the password stored in file as shown below


Base64 encoding helps you compactly transport binary data as readable characters.

Labels: ,