Ad

Friday 3 April 2015

How to implement selection sort algorithm in java

In this post we will see how to implement the selection sort algorithm in java with a sample program.In selection sorting
  1. We will find the smallest element in the array  and  then swap this element with the  element in the 0th index of the  array.
  2. Then we will find the second smallest element in the array and  swap this element with the element in the 1st index of the array.This iteration will continue upto the number of times equal to the the size of the array.
Below sample program will explain this in detail.

package test;

public class SelectionSortSample {

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arry = new int[] { 20, 3, 150, 5, 6, 78, 2, 123, 43, 45, 99, 1,
12 };
SelectionSortSample selectionSort = new SelectionSortSample();
selectionSort.sort(arry);
}

public void sort(int[] arry) {
printElements(arry);
int len = arry.length;
int min = 0;
int temp=0;
for (int i = 0; i < len; i++) {
min=i;
for(int j=i+1;j<len;j++)
{
if(arry[j]<arry[min])
{
min=j;
}
}
temp=arry[i];
arry[i]=arry[min];
arry[min]=temp;
printElements(arry);
}

}

public void printElements(int[] arry) {
for (int i = 0; i < arry.length; i++) {
System.out.print("  " + arry[i]);
}
System.out.println();
}

}


When we run the above program,we will get this output

  20  3  150  5  6  78  2  123  43  45  99  1  12
  1  3  150  5  6  78  2  123  43  45  99  20  12
  1  2  150  5  6  78  3  123  43  45  99  20  12
  1  2  3  5  6  78  150  123  43  45  99  20  12
  1  2  3  5  6  78  150  123  43  45  99  20  12
  1  2  3  5  6  78  150  123  43  45  99  20  12
  1  2  3  5  6  12  150  123  43  45  99  20  78
  1  2  3  5  6  12  20  123  43  45  99  150  78
  1  2  3  5  6  12  20  43  123  45  99  150  78
  1  2  3  5  6  12  20  43  45  123  99  150  78
  1  2  3  5  6  12  20  43  45  78  99  150  123
  1  2  3  5  6  12  20  43  45  78  99  150  123
  1  2  3  5  6  12  20  43  45  78  99  123  150
  1  2  3  5  6  12  20  43  45  78  99  123  150


Above output will show the array elements position at the end of each iteration.

How to implement insertion sort algorithm in java

In this post we will see how to implement the insertion sort algorithm in java with a sample program.In insertion sorting
  1. we will select a key from the array for each iteration ,which will start from index 1 of the array to the last element.
  2. The key will be compared with the elements precedence to it (i.e if the key selected is at index 2,it will be compared with the elements at index 1 and index 0) and the key will be inserted at the right position in the array.
Below sample program will explain this in detail.

package test;

public class InsertionSortSample {

public static void main(String[] args) {
int[] arry = new int[] { 20, 3, 150, 5, 6, 78, 2, 123, 43, 45, 99, 1,
12 };
InsertionSortSample insertionSort = new InsertionSortSample();
insertionSort.sort(arry);
}

public void sort(int[] arry) {
printElements(arry);
int len = arry.length;
int key = 0;
int j=0;
for (int i = 1; i < len; i++) {
key=arry[i];
j=i-1;
while(j>=0 && key<arry[j])
{
arry[j+1]=arry[j];
j--;
}
arry[j+1]=key;
printElements(arry);
}

}

public void printElements(int[] arry) {
for (int i = 0; i < arry.length; i++) {
System.out.print("  " + arry[i]);
}
System.out.println();
}

}

When we run the above program,we will ge this output

  20  3  150  5  6  78  2  123  43  45  99  1  12
  3  20  150  5  6  78  2  123  43  45  99  1  12
  3  20  150  5  6  78  2  123  43  45  99  1  12
  3  5  20  150  6  78  2  123  43  45  99  1  12
  3  5  6  20  150  78  2  123  43  45  99  1  12
  3  5  6  20  78  150  2  123  43  45  99  1  12
  2  3  5  6  20  78  150  123  43  45  99  1  12
  2  3  5  6  20  78  123  150  43  45  99  1  12
  2  3  5  6  20  43  78  123  150  45  99  1  12
  2  3  5  6  20  43  45  78  123  150  99  1  12
  2  3  5  6  20  43  45  78  99  123  150  1  12
  1  2  3  5  6  20  43  45  78  99  123  150  12
  1  2  3  5  6  12  20  43  45  78  99  123  150

Above output will show the array elements position at the end of each iteration and how the key is inserted at the right position.

Tuesday 31 March 2015

How to implement bubble sort algorithm in java

In this post we will see how to implement the bubble sort algorithm in java with a sample program.
Lets say there are N elements in the array to be sorted and the bubble sorting takes place by
  1.    Comparing  the adjacent elements in the array and swap its corresponding position if found greater.
  2.    Above step will be iterated upto the maximum of N -1 iteration until the array is fully sorted.
Below sample program will explain this in detail.

package test;

public class BubbleSortSample {

public static void main(String[] args) {
int[] arry = new int[] { 20, 3, 150, 5, 6, 78, 2, 123, 43, 45, 99, 1,
12 };
BubbleSortSample bubbleSort = new BubbleSortSample();
bubbleSort.sort(arry);
}

public void sort(int[] arry) {
printElements(arry);
int len = arry.length;
boolean isSwaped = false;
int temp = 0;
for (int i = 0; i < len; i++) {
isSwaped = false;
for (int j = 0; j < len - i - 1; j++) {
if (arry[j] > arry[j + 1]) {
temp = arry[j];
arry[j] = arry[j + 1];
arry[j + 1] = temp;
isSwaped = true;
}
}
printElements(arry);
if (!isSwaped) {
System.out.println("  Array has been fully sorted,hence rest of the iteration skipped");
break;
}
}
}

public void printElements(int[] arry) {
for (int i = 0; i < arry.length; i++) {
System.out.print(" " + arry[i]);
}
System.out.println();
}

}



When we run the above program,we will get this output

  20  3  150  5  6  78  2  123  43  45  99  1  12
  3  20  5  6  78  2  123  43  45  99  1  12  150
  3  5  6  20  2  78  43  45  99  1  12  123  150
  3  5  6  2  20  43  45  78  1  12  99  123  150
  3  5  2  6  20  43  45  1  12  78  99  123  150
  3  2  5  6  20  43  1  12  45  78  99  123  150
  2  3  5  6  20  1  12  43  45  78  99  123  150
  2  3  5  6  1  12  20  43  45  78  99  123  150
  2  3  5  1  6  12  20  43  45  78  99  123  150
  2  3  1  5  6  12  20  43  45  78  99  123  150
  2  1  3  5  6  12  20  43  45  78  99  123  150
  1  2  3  5  6  12  20  43  45  78  99  123  150
  1  2  3  5  6  12  20  43  45  78  99  123  150
  Array has been fully sorted,hence rest of the iteration skipped

Above output will show the array elements position at the end of each iteration and how the elements in the arrays were swapped.

Friday 27 March 2015

Lazy initialization of spring beans using lazy-init and default-lazy-init

In this post we will learn about the lazy initialization of spring beans using attribute lazy-init and default-lazy-init.By default spring container will create all the singleton bean at  container startup i.e when the spring container is loaded.This is necessary since if there is any error in creating the beans or setting the dependencies will be known to us at the container load time itself.But sometimes we don't need this behavior.We would like to create the bean only when it is requested and not at the container startup,thus reducing the container startup time.
 
Below code example will show how to lazy initialize the bean.

Employee- Spring bean which we will lazy initialize.
LazyInitDemo -  Main class which load the container and initializes the bean.
Studentcontext.xml - metadata configuration details for the spring container.

Employee.java

package bean;

public class Employee {

private String empId;

private String empName;

public Employee(String empId, String empName) {
this.empId = empId;
this.empName = empName;
System.out.println("Employee bean Created empId:" + empId + " empName:"
+ empName);
}

public String getEmpId() {
return empId;
}

public String getEmpName() {
return empName;
}

}

employeecontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="employee" class="bean.Employee" lazy-init="true">
<constructor-arg  name="empId" value="E01"/>
<constructor-arg  name="empName" value="Rahul"/>
</bean>

</beans>

As we can see in the application context file,we set the attribute lazy-init to true in the bean definition.This will make this bean to be create only when it is requested and not at the container load time.

LazyInitDemo.java

package bean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class LazyInitDemo {

public static void main(String[] args) {
ApplicationContext bf = new ClassPathXmlApplicationContext(
new String[] { "employeecontext.xml" });
System.out.println("Spring Container Laoded::");
System.out
.println("Going to request the employee bean from the container::");
Employee emp = bf.getBean("employee", Employee.class);
}
}

OUTPUT:

When we run LazyInitDemo class, we will get the below output

Spring Container Loaded::
Going to request the employee bean from the container::
Employee bean Created empId:E01 empName:Rahul


As we can see in the output,employee bean was not created at container loaded time and was created only when it was requested.

when we need all the beans defined in the application context to be lazy initialized,use the attribute default-lazy-init in the parent "beans" tag as shown below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-lazy-init="true">

<!--- bean 1 definition  -->

<!--- bean 2 definition  -->

</beans>

Thursday 26 March 2015

Spring bean Life Cycle - Callback Methods

In this post we will learn about the spring bean life cycle callback methods.Spring container provides the below two callback methods for the bean,so that the bean can perform certain actions during initialization or on destruction of the bean.
  • Initialization callback - After the bean is created by the container and the properties are set,the container will call this callback method.
  • Destruction callback - when the bean is about to destroyed i.e when the container is about to exit,the container will call this callback method.
In this post we will see how to configure this callback methods using the application context file (using attributes init-method and destroy-method).Below code example will explain this in detail.

Student - Spring bean class for which we will configure the callback methods.
CallbackDemo -  Main class which loads the container and initializes the bean.
Studentcontext.xml - Metadata configuration details for the spring container.

Student.java

package test;

public class Student {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void init() {
System.out.println("Bean initialization callback invoked for student::"
+ this.name);
}

public void destroy() {
System.out.println("Bean Destruction callback invoked for student::"
+ this.name);
}
}

studentcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="student" class="test.Student" init-method="init" destroy-method="destroy">
<property  name="name" value="Ram"/>
</bean>

</beans>

As we can see in the application context file,we used the below two attributes in the bean definition of student.
  • init-method - This will configure the initialization callback method(which is init) for the student bean
  • destroy-method - This will configure the destruction callback method(which is destroy) for the student bean
CallbackDemo.java

package test;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CallbackDemo {

public static void main(String[] args) {
AbstractApplicationContext  bf = new ClassPathXmlApplicationContext(
new String[] { "studentcontext.xml" });
bf.registerShutdownHook();
Student student= bf.getBean("student",Student.class);
}

}

We need to register the shutdownhook on the AbstractApplicationContext,so that the container will have the graceful shutdown and hence the corresponding destruction callback method on the bean will be called.

OUTPUT:

When we run the callbackDemo class, we will get the below output

Bean initialization callback invoked for student::Ram
Bean Destruction callback invoked for student::Ram

As we can see in the output,spring container
  • invoked the initialization callback(init method), after the properties in the bean are set.
  • invoked the destruction callback(destroy method) ,when the container is about to exit.

Wednesday 25 March 2015

depends-on attribute in spring with an example

In this post we will see the usage of depends-on attribute in spring.In spring if a bean has a dependency on another bean,we will declare one bean as the property of the other.But however in some cases the dependency will be indirect i.e we want a bean to be initialize only after a certain bean is initialized.depends-on attribute is used in this case. Below code example will explain this in detail.

BeanA,BeanB - Spring bean classes.Here we want the Spring container to initialize BeanB first and then the BeanA.
DependsDemo -  Main class which load the container and initializes the bean.
beancontext.xml - metadata configuration details for the spring container.

BeanA.java

package test;

public class BeanA {

private String id;

public BeanA(String id) {
this.id = id;
System.out.println("BeanA created::id=" + this.id);
}

public String getId() {
return id;
}

}

BeanB.java

package test;

public class BeanB {

private String id;

public BeanB(String id) {
this.id = id;
System.out.println("BeanB created::id=" + this.id);
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}
}


beancontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="beanA" class="test.BeanA" depends-on="beanB">
<constructor-arg  name="id" value="A01"/>
</bean>

<bean id="beanB" class="test.BeanB">
<constructor-arg  name="id" value="B01"/>
</bean>

</beans>


As we can see in the application context file,in the bean definition of BeanA we used depends-on attribute to specify its dependency on BeanB.Hence the spring container will initialize the BeanB first and then the bean BeanA.

DependsDemo.java

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DependsDemo {

public static void main(String[] args) {
System.out.println("Initilaizing the container::");
ApplicationContext bf = new ClassPathXmlApplicationContext(
new String[] { "beancontext.xml" });
}

}

OUTPUT:

When we run DependsDemo class we will get the below output

Initilaizing the container::
BeanB created::id=B01
BeanA created::id=A01

As we can see in the output,spring container initialized the BeanB first and then the BeanA.

Monday 23 March 2015

class net.sf.cglib.core.DebuggingClassWriter has interface org.objectweb.asm.ClassVisitor as super class

In this post we see how to resolve the exception "java.lang.IncompatibleClassChangeError: class net.sf.cglib.core.DebuggingClassWriter has interface org.objectweb.asm.ClassVisitor as super class".The full stacktrace for this exception will look like below:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employee' defined in class path resource [aop.xml]: Initialization of bean failed; nested exception is java.lang.IncompatibleClassChangeError: class net.sf.cglib.core.DebuggingClassWriter has interface org.objectweb.asm.ClassVisitor as super class
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
           at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
           at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
           at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
           at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
           at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
           at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
           at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
           at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
           at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)
           at aspect.AspectTest.main(AspectTest.java:10)
Caused by: java.lang.IncompatibleClassChangeError: class net.sf.cglib.core.DebuggingClassWriter has interface org.objectweb.asm.ClassVisitor as super class
           at java.lang.ClassLoader.defineClass1(Native Method)
           at java.lang.ClassLoader.defineClass(Unknown Source)
           at java.security.SecureClassLoader.defineClass(Unknown Source)
           at java.net.URLClassLoader.defineClass(Unknown Source)
           at java.net.URLClassLoader.access$100(Unknown Source)
           at java.net.URLClassLoader$1.run(Unknown Source)
           at java.net.URLClassLoader$1.run(Unknown Source)
           at java.security.AccessController.doPrivileged(Native Method)
           at java.net.URLClassLoader.findClass(Unknown Source)
           at java.lang.ClassLoader.loadClass(Unknown Source)
           at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
           at java.lang.ClassLoader.loadClass(Unknown Source)
           at net.sf.cglib.core.DefaultGeneratorStrategy.getClassVisitor(DefaultGeneratorStrategy.java:30)
           at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:24)
           at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
           at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144)
           at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116)
           at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
           at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
           at net.sf.cglib.proxy.Enhancer.(Enhancer.java:69)
           at org.springframework.aop.framework.Cglib2AopProxy.createEnhancer(Cglib2AopProxy.java:228)
           at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:170)
           at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:112)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:476)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:362)
           at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
           at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
           ... 11 more

This exception will be thrown,if we have the cglib.jar referring to a incompatible asm.jar set in our classpath.For instance if we have cglib-3.1.jar we will get this exception when we have asm-3.1.jar set in the classpath.Hence to resolve this we need to remove this older version of asm.jar and refer the asm.jar version greater than 4.0.So if we add the asm-4.0.jar(which is the compatible version for the cglib-3.1) to our classpath,we will not get the above exception.