Saturday, December 6, 2014

Interview Questions on Core Java

This post will be dynamic, will keep on updating.

In this post i will be trying to post core java interview questions being asked for 4-5 years of experience.

1. Collections 

  • One might ask for difference between different type of collections like: ArrayList and LinkedList, Vector and ArrayList, HashMap and ConcurrentHashmap
  • Other typical question on collection will be to explain implementation of some of typical collections like: HashMap, ConcurrentHashmap etc.
2. Concurrency

Hope this will help.

Friday, October 10, 2014

start tomcat in debug mode

Steps to start tomcat in debug mode:

1. Open catalina.bat from %Catalina_Home%\bin directory in edit mode.
2. Add “-Xdebug -Xrunjdwp:transport=dt_socket,address=4711,server=y,suspend=n” in JAVA_OPTS as below,

set JAVA_OPTS=%JAVA_OPTS% -Xdebug -Xrunjdwp:transport=dt_socket,address=4711,server=y,suspend=n

Steps to start tomcat windows service in debug mode:

  1. Install windows service using c:\tomcat7\bin> service.bat install
  2. Now go to %Catalina_Home%\bin and run tomcat7w.exe
  3. In Java table, there is Java Options text area, add below parameters in it,

a. -Xdebug
b. -Xrunjdwp:transport=dt_socket,address=4711,server=y,suspend=n

   4. Now start you tomcat service from services or command prompt, server will be running in debug mode.

Hope this helps.

Monday, September 29, 2014

Spring Interview Question: How to make Spring beans of type prototype by default.

Spring Interview Question: How to make Spring beans of type prototype by default.

In spring springs are of 5 types,

1. Singleton (Default)
2. Prototype
3. Request Scope
4. Session Scope
5. Global Scope

Singleton: there will be only one instance of a bean will exist in the Spring context.

Prototype beans: there will be seperate bean to fullfill all dependencies in a spring context, in other words more than one instances of bean will exist in spring context.

By default all beans are of singleton type.

Recently in an interview, a question was asked to one of my friend, what are the types of bean in spring and what is default type.

The above explanation is pretty sufficient to answer this, but the next subsequent question was a bit trickky, "How can you make all the beans in spring prototype" or "How can you make default type of beans prototype in spring".

This question can only be answered if one is fully aware of spring bean lifecycle. This can be achieved by implementing BeanFactoryPostProcessor and overriding postProcessBeanFactory method.

Below is the code snippet to do this.

public class PrototypePostProcessor implements BeanFactoryPostProcessor {

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
for(String bean : beanFactory.getBeanDefinitionNames() ) {

Hope this will help.

Feel free post your suggestions in comments.

Wednesday, January 29, 2014

Exception handling in java

Exception handling is one of important aspect of programming. In java, many developers catch Exception as below

// Code 
} catch (Exception ex) {}

Which is wrong because it catches RuntimeException or un-checked exceptions as well.

Few things which a developer needs to take care while exception handling are as below:
  • Always do resource clean up, use finally block for resource clean up. like closing database or network connections.
  • Do not use Parent Exception class or Throwable (untill and unless necessary), because it handles un checked exceptions as well.
  • log exceptions just once, don't log exceptions multiple times in multiple layers.
  • Do not suppress or ignore exceptions.

Hope this will help.

Sunday, September 29, 2013

how to select a schema and list all tables in mysql?

In this post i will explain how to select a schema and list down all tables in mysql DB.

First login to mysql command using  below command,

c:\mysqlDB\bin>mysql -u -p
Enter your password:

and then by use command select schema as below,

mysql>use test;

this command will select schema. Now use show tables command to list all tables.

mysql> show tables;

this will list down all tables in test schema, as shown in below screenshot.

How to check all the schemas present in mysql?

In mysql how to check all the schemas present?

First login using root user, and then use show databases command which will list down all the schemas present on server.

mysql> show databases;

this command will list down all the schemas/databses present on server, as shown in attached screenshot.

Hope this will help some of you.

Tuesday, February 26, 2013

Singleton Design Pattern in java

Singleton Design Pattern in Java

One of the most frequently asked question in java interviews. Interview will start discussion about singleton by “what is singleton design pattern” or “what all design patterns you have used or knowledge about”. Once you tell them the definition of singleton they will ask for writing a class with singleton implementation and will be followed by related question. Overall it depends on how you handle these questions. Here I will try to explain all the questions which I was asked in interviews.

Singleton definition: This design pattern ensures that for every singleton class there will be only one instance present in JVM. This design pattern involves only one class, which has its own private reference and provide a method to access it from outside so that this same instance will be used every time.

There are number of ways to implement it, but I will explain just 2 ways which are simplest and least confusing.
1. Early instantiation using static keyword.

/*Early instantiation using static field */
class SingletonExample {
private static SingletonExample instance = new SingletonExample();

private SingletonExample() {
System.out.println("SingletonExample(): Initializing instance eagerly");

public static SingletonExample getInstance() {    
return instance;

By method instance will be created when the class first get loaded by classloader.

2. Lazy initialization using synchronization
/*Lazy instantiation*/
class SingletonEx {
private static SingletonEx instance;
private SingletonEx() {
System.out.println("SingletonEx (): Initializing instance");

public static SingletonEx getInstance() {
if (instance == null) {
synchronized(SingletonEx.class) {
if (instance == null) {
System.out.println("getInstance(): First time getInstance was invoked!");
instance = new SingletonEx();
return instance;

By this method instance will be created when instance was called for the first time by calling getInstance() method, and here we are doing this using double locking mechanism.

We are using synchronization to ensure that in case if two different threads access getInstance method simultaneously, it will not end up creating two different instances. 

As synchronization is very expensive when we talk about performance, that is why synchronized block is placed inside the conditional block which will be executed only when instance is null/not initialized.

This is all about Singleton, if you feel i have missed some aspect or question about singleton, pls let me know. Suggestions are always welcome ;-)

Tuesday, February 19, 2013

VI editor on Unix and Linux commands for beginners

For software developers its normal to work on UNIX or Linux environment, because most of the time Prod servers are deployed on Unix machines.

VI is just like notepad in Windows, but it is very powerful. Most of the times we use very limited functions of it. I myself also know only those command which i require to get my work done.

Below are the commands which we use very frequently.

Open a file: vi

If you want to open a file in read-only mode use: vi -R

There are few mode of VI editors like command mode, insertion mode, replace mode and append mode.

All below commands work in command mode, other modes are for writing code to file.

Insertion mode(i - insert before cursor), replace mode(r replace 1 char, R), Append Mode (a - append after cursor).

To come back to command mode from any other mode just press ESC.

Commands for deletion:

dw : deletes a word under cursor
db : deletes word before cursor
dd: deletes current line
ndd: deletes n lines
x - deletes character under cursor


shift + g: last line of file
0 : start of line
$ : end of file
e : end of next word
w: start of next word

Exiting VI file:

:wq - save the changes and exit
:q! - discard the changes and exit
:wq! - save changes from read-only file and exit
:w - save changes to file.

Searching contents in VI editor:
?keyword : searches keyword in file from bottom to top.
/keyword : searches keyword in file from top to bottom.
Navigation while searching
n for next occurrence and N for previous occurrence.

UNDO Command:
u: undo last command

yy (yank)'copies' line which may then be put by the p(put) command. (Precede with a count for multiple lines eg: nyy)

These are sufficient for working on VI editor.. I will keep on updating this list, as i will come across or learn new command.

You are also requested to leave comments if want to add something to this post.

Saturday, November 17, 2012

HTML hide a row or column of table dynamically

This is a normal html trick or tip to hide or show an html element. use below mentioned javascript to hide or show such elements.


for example: if we want to hide a row of html table based on click of a button,


function hideRow(id) {

<table border="1" cellpadding="1" cellspacing="0" style="width: 200px;">
<tr id="row1"><td scope="col">Col11</td><td>Col12</td></tr>
<input onclick="hideRow('row1') type="button" value="Hide Row1" />

Replace < with < and > with > sign.

function hideRow is accepting id of row which you want to hide, inside the method we are setting CSS style display to none which hides an html element.

likewise you can do for column and other elements by replacing id with the id of element.

Thursday, October 18, 2012

How to sort a Map based on values in java?

Once i had an requirement to sort an HashMap based on the values, how i achieved this is explained below,

First stored the entryset as an ArrayList and then used Comparator to sort that List. After that created new LinkedHashMap, as LinkedHashMap preserves the insertion order, so inserted the List values in LinkedHashMap, which is now sorted based on Values.

Map unSortedMap = new HashMap();
unSortedMap.put("w", "e");
unSortedMap.put("d", "z");
unSortedMap.put("q", "g");
unSortedMap.put("f", "t");
unSortedMap.put("s", "m");

List> list = new LinkedList>();
for (Entry entry : unSortedMap.entrySet()) {
System.out.println(entry.getKey() + " -- " + entry.getValue());

Collections.sort(list, new Comparator>() {
public int compare(Entry o1,
Entry o2) {
return o1.getValue().compareTo(o2.getValue());
Map sortedMap = new LinkedHashMap();
for (Entry entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
for (Entry entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + " -- " + entry.getValue());

this will be the output
==========UnSorted Map===============
f -- t
w -- e
d -- z
s -- m
q -- g
==========Sorted Map===============
w -- e
q -- g
s -- m
f -- t
d -- z

Note: This will fail if you use null values in Map. I am trying to figure out the solution for that, if you have any then please comment.