## Monday 25 September 2017

### Java Program for Bubble Sort in Ascending and Descending order

Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements bubble to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.

Time Complexity:--

Best case performance    O(n)
Worst case performance  -  O(n^2)

Bubble Sort program for sorting in ascending order,

```package com.pr;
public class BubbleSort {

public static void main(String[] args) {

BubbleSort sort = new BubbleSort();
sort.bubbleSort(new int[]{1,10,4,3,8,2,15});
}

public void bubbleSort(int[] arr) {
int length = arr.length;

System.out.println("Array before bubble sort is: ");
for (int i = 0; i< arr.length; i++) {
System.out.print(arr[i]+" ");
}

for (int i = 0; i<arr.length; i++) {
for (int j = 1; j< (length-i); j++) {
if (arr[j-1] > arr[j]) {
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
System.out.println("");
if (i== 0) {
System.out.println("Sorting step by step:");
}
for (int k = 0; k< arr.length; k++) {
System.out.print(arr[k]+" ");
}
}

System.out.println("");
System.out.println("Array after bubble sort is: ");
for (int i = 0; i< arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
}```
` `

Output:-
Array before bubble sort is:
1 10 4 3 8 2 15
Sorting step by step:
1 4 3 8 2 10 15
1 3 4 2 8 10 15
1 3 2 4 8 10 15
1 2 3 4 8 10 15
1 2 3 4 8 10 15
1 2 3 4 8 10 15
1 2 3 4 8 10 15
Array after bubble sort is:
1 2 3 4 8 10 15

Bubble Sort program for sorting in descending order,

For descending order, change the above code at line no.15
`arr[j-1] > arr[j] to arr[j-1] < arr[j],`

```package com.pr;
public class BubbleSort {

public static void main(String[] args) {

BubbleSort sort = new BubbleSort();
sort.bubbleSort(new int[]{1,10,4,3,8,2,15});
}

public void bubbleSort(int[] arr) {
int length = arr.length;

System.out.println("Array before bubble sort is: ");
for (int i = 0; i< arr.length; i++) {
System.out.print(arr[i]+" ");
}

for (int i = 0; i<arr.length; i++) {
for (int j = 1; j< (length-i); j++) {
if (arr[j-1] < arr[j]) {
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
System.out.println("");
if (i== 0) {
System.out.println("Sorting step by step:");
}
for (int k = 0; k< arr.length; k++) {
System.out.print(arr[k]+" ");
}
}

System.out.println("");
System.out.println("Array after bubble sort is: ");
for (int i = 0; i< arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
}```
` `
Output: -
Array before bubble sort is:
1 10 4 3 8 2 15
Sorting step by step:
10 4 3 8 2 15 1
10 4 8 3 15 2 1
10 8 4 15 3 2 1
10 8 15 4 3 2 1
10 15 8 4 3 2 1
15 10 8 4 3 2 1
15 10 8 4 3 2 1
Array after bubble sort is:
15 10 8 4 3 2 1

## Sunday 24 September 2017

### Difference between the Runnable and Callable interface in Java

This is also one of the important question of Java interview for middle level developer.  Runnable interface is added in JDK 1.0 where as Callable was added much later i.e in Java 5, along with many other concurrent features CopyOnWriteArrayList, ConcurrentHashMap, BlockingQueue and ExecutorService .

If you see basic functionality both Callable and Runnable interfaces are implemented by any class whose instances are to be executed by another thread.  Callable interface have a some extra features which were not there in Runnable.  Those features are,
• Callable can return value
• It can throw exception

Difference between Runnable and Callable:--

1)  The Callable and Runnable are interfaces and both have a single method but that method and it's signature is different.

Runnable:-

```   public interface Runnable {
public abstract void run();
}```

Callable :

```   public interface Callable<V> {
V call() throws Exception;
}```

2)  Callable interface is a part of the java.util.concurrent package whereas Runnable interface is a part of the java.lang package.

3)  If you have noticed the signature of call method in the callable interface, you can see that call method can return value

`      V call() throws Exception`
```
```
`  `
In the above code, V is the computed result.  Callable is a generic interface and type is provided at the time of creating an instance of Callable implementation.

Example:-

```   Callable<Integer> callableObj = new    Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 2;
}
};```

run() method of Runnable interface doesn't return any value,  return type is void.

```  @override
public void run() {
//does not return anything
}```
` `
` `
4)  Another difference that can be noticed from the signatures of the call() and run() method is that you can not give a exception with throws clause in run method.

This below statement will give compile time error,

`    public void run() throws InterruptedException`
` `
In call() method exception can be given with throws clause, as below.

`    public Integer call() throws InterruptedException`
```
```

5)  In order to run runnable task options are ,
• Thread class has a constructor that takes Runnable as parameter.
• Executor interface has execute method which takes Runnable as parameter.
• ExecutorService has submit method which takes Runnable as parameter.
For Callable,
• Thread class doesn't have any constructor that takes Callable as a parameter.
• ExecutorService has submit method which takes Callable as a parameter.
• ExecutorService also has invokeAll and invokeAny methods that takes Callable as a parameter.
• Executors class has callable method that can convert Runnable to Callable
`    Callable callable = Executors.callable(Runnable task); `
```
```
```
```
```
```
Related Posts:-

4) Thread join() method example in Java
5) Producer Consumer Problem - Solution using wait and notify In Java

## Saturday 23 September 2017

### Internal Implementation of LinkedList in Java

In Previous post, discussed about the In this post, we can discuss the internal working of LinkedList and implementation of main methods in the LinkedList.

The LinkedList is a linear data structure, where each element is a separate object.  Each element i.e Node of a list is comprising two items, the data and reference to the next node. The last node has a reference to null.  The entry point into a linked list is called the head of the list. It should be noted that head is not a separate node, but the reference to the first node.  If the list is empty then the head is a null reference.

A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow dynamically.

Below code is internal implementation or source code of add(), remove(), contains(), get() and size() methods of LinkedList(Singly Linked List).

```package com.pr;

private int listcount;

listcount = 0;
}

Node temp = new Node(data);
while (current.getNext() != null) {
current = current.getNext();
}
current.setNext(temp);
listcount++;
}

public void add(Object data, int index) {
Node temp = new Node(data);
for (int i = 0; i < index && current.getNext() != null ; i++) {
current = current.getNext();
}
temp.setNext(current.getNext());
current.setNext(temp);
listcount++;
}

public Object get(int index) {
if (index < 0) {
return null;
}
for (int i = 0; i<index; i++) {
if (current.getNext() == null)
return null;
current = current.getNext();
}
return current.getData();
}

public boolean remove(int index) {
if(index < 0 && index > listcount) {
return false;
}
for (int i = 0; i < index; i++) {
if (current.getNext() == null)
return false;
current = current.getNext();
}
current.setNext(current.getNext().getNext());
listcount--;
return true;
}

public boolean contains(Object obj) {
for (int i = 0; i< listcount; i++) {
if (current.getNext().getData().equals(obj))
return true;
current = current.getNext();
}
return false;
}

public boolean isEmpty() {
return listcount == 0;
}

public int size() {
return listcount;
}
}

class Node {
Node next;
Object data;
public Node(Object data) {
this.data = data;
this.next = null;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
```

The main program :--

```package com.pr;

public class MainClass {
public static void main(String[] args) {
System.out.println(list.size());
System.out.println(list.isEmpty());
System.out.println(list.contains("AB"));
System.out.println(list.get(1));
}
}
```

Output : - 2
false

true
BC

Related Post : -
1) Internal implementation of ArrayList in Java
2)

## Friday 15 September 2017

### What is Generics in Java with examples ? and What are the advantages of using Generics.

In Java 1.5 added one important feature i.e Java Generics.  If you have been working on Collections and having java 5 or above versions then sure you have used it Generics.  At high level definition, generics are nothing but parameterized  types.
It allows a class or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections framework and eliminates the need for casting.  This helps in detecting bugs at compile time itself.  Fixing compile time error is easier than run time errors .  It avoids the ClassCastException at run time.

Let's see an example, Writing a List without Generics as below,

```   List list = new ArrayList();
Integer x = (Integer) list.get(1); //will throw ClassCastException at run time
```

In the above code, It will add any type of the Object into the list. It won't check the type safety hence there is no compile time error.  Only run time it can check for the type safety and will throw ClassCastException.

With Generics, same above code will be written as,

```    List<Integer> list = new  ArrayList<Integer>();
list.add("A"); // It will show a compile time error.
Integer x = list.get(0);
```

The above code show compile time error while adding String to the list.  So it can type safety at compile time itself, it can not allow to add.  In this code explicit type casting is not required while getting the list values.

Let us see another advantage of Generics,  Type inference.

Type inference is a Java compiler’s ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.
Generic Methods introduce you to type inference, which enables you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets.

Generic Classes:-
The Generic class is an ordinary class with type parameters, example as below

```public class GenericClass<T> {
private T t;

this.t = t;
}

public T get() {
return t;
}

public static void main(String[] args) {

GenericClass<String> stringClass = new GenericClass<String>();
GenericClass<Integer> integerClass = new GenericClass<Integer>();

System.out.println("Integer Value: " + integerClass.get());
System.out.println("String Value: " + stringClass.get());
}
}

Output:
Integer Value: 1
String Value: Hello World
```

Wildcards in Generics:-
In generic code, the question mark(?)  is called the wildcard, represents an unknown type.  There are two types of wildcards in Generics 1) Bounded and  2) Unbounded
The bounded wildcard is further divided into upper bounded wildcard and lower bounded wildcard.

Upper Bounded Wildcards

To declare an Upper bounded wildcard, use the wildcard character(?)  followed by the extends keyword, followed by its upper bound(type). Note that, in this context,  extends is used in a general sense to mean either extends (for classes) or implements (for interfaces).  Upper bounded wildcard restricts the unknown type to be a specific type or sub type of that type.

Consider the below code,

```public static void sumOfList(List<? extends Number> list) {
//some code
}```
` `
Here the argument list is bound to the Number type. This method works on lists of Number and the sub types of Number such as Integer, Double and Float.

Lower Bounded Wildcards

To declare a Lower bounded wildcard, use the wildcard character(?) , followed by the super keyword, followed by its lower bound(type). A lower bounded wildcards restricts the unknown type to be a specific or super type of that type.
Consider the below code,

```public static void sumOfList(List<? super Integer> list) {
//some code
} ```
```
This method works on a lists of Integer or super type of Integer i.e lists of Number.
```

Unbounded Generics
The Unbounded wildcard type is specified using the wildcard character(?) . e.g List<?> . This is called  a list of unknown type.  This is useful when you are writing a method that does only read only operation or uses only common methods defined in the interface and doesn't use any implementation specific methods.

For example, you can write a common method that just displays the elements of the list or calculates the size of the list.

```public void display(List<?> list){
Iterator<?> itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}

public static int sizeOfList(List<?> list){
return list.size();
}
```

Type Erasure :-

Generics were introduced to provide tighter type checks at compile time and to support generic programming. Type erasure is nothing but the Java compiler replaces the type parameters with their bounded types or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods. It also Insert type casts if necessary to preserve type safety.
Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no run-time overhead.
Consider the below class,'

``` public class GenericClass<T> {
private T t;

this.t = t;
}

public T get() {
return t;
}
}
```

Here T is an unbounded parameter so during type erasure process Java compiler replaces it with the Object. So the code after compilation is as follows,

```  public class GenericClass {
private Object t;

this.t = t;
}

public Object get() {
return t;
}
}
```

Note : -  Standard convention to use Generic parameters are ,
T -  Type parameter
E -  Elements (using in LinkedList)
K - Key in Map
V - value in Map
N - Number

### Advantages of Spring JdbcTemplate over JDBC API

Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC API, but eliminate the lot of problems of JDBC API.

Problems While using JDBC API :-

The common problems while using JDBC API are as below,

1) We need to write a lot of code before and after executing the query such as creating connection,
statement and resultset and closing the resultset, statement and connection etc.

2) We need to perform exception handling code on the database logic.

3) We need to handle transaction.

4) Repetition of these codes i.e connection, statement and resultset codes for every transaction, so it's

Spring provides simplification in handling database access with the Spring JdbcTemplate which is in org.springframework.jdbc.core package.

1) The Spring JdbcTemplate allows to clean-up the resources automatically, no need to write the
extra code .

2) The Spring JdbcTemplate converts the standard JDBC SqlExceptions into RuntimeExceptions.
This allows the programmer to react more flexible to the errors.  And it also converts the vendor
specific error messages to the better understandable error messages.

3) The Spring JdbcTemplate offers several ways to query the database e.g queryForList() returns a
list of HashMaps.  key is the column name of database and value is the actual column data.

4) More convenient is the usage of ResultSetExtractor or RowMapper which allows to translates
the SQL result direct into an Object or a list of Objects .

Example of JdbcTemplate :-

Create one simple table employee, having id, name and salary are columns.

```    create table employee(
id integer(10),
name character varying(100),
salary integer(10)
);
```

The Employee class have properties id, name and salary with setters and getters. it's POJO class.

```    package com.adnblog;

public class Employee {
private int id;
private String name;
private int salary;
//no-arg and parameterized constructors
//getters and setters
}
```

The EmployeeDao class is having JdbcTemplate property and some methods having database operations.

```package com.adnblog;
import org.springframework.jdbc.core.JdbcTemplate;

public class EmployeeDao {

private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public int saveEmployee(int id, String name, int salary){
String query="INSERT INTO employee VALUES(?, ?, ?)";
return jdbcTemplate.update(query, id, salary);
}

public int updateEmployee(int id, String name, int salary){
String query="UPDATE employee
SET name = ?, salary = ? WHERE id = ?";
return jdbcTemplate.update(query, name, salary, id);
}

public List<Employee> findAll(){

String sql = "SELECT * FROM employee";

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

List<Map> rows = getJdbcTemplate().queryForList(sql);
for (Map row : rows) {
Employee emp = new Employee();
emp.setId((Integer)(row.get("ID")));
emp.setName((String)row.get("NAME"));
emp.setSalary((Integer)row.get("SALARY"));
}
return employeeList;
}
} ```
` `
Another one interface ResultSetExtractor is interface used to fetch data from the database, it will take resultset data as input and will return in the form of list.  Another interface RowMapper you can read from google.

Related Posts:--
1) What are different Spring Bean Scopes?
2) Spring @Qualifier Annotation with example
3) Spring Configuration Metadata (XML, Annotation and Java)
4) What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext
5) Spring Annotations

## Friday 8 September 2017

### Java Program to Sort ArrayList of Custom Objects By Property using Comparator interface

In previous one post, learned about diff. of  Comparable and Comparator interface.  The Comparator interface is used to sort the two different objects.  In this post or example,  gives to sort the ArrayList of Custom objects with multiple properties.

Example:- Sorting an ArrayList of Custom Objects with multiple properties

```package com.pr;

import java.util.Comparator;
import java.util.Date;

public class ComparatorExample {

public int id;
public String name;
public Date dof;

public ComparatorExample(int id, String name, Date dof) {
this.id = id;
this.name = name;
this.dof = dof;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public Date getDof() {
return dof;
}
public void setDof(Date dof) {
this.dof = dof;
}

//sorting based on Name, ascending order
public static Comparator<ComparatorExample> nameComp = new Comparator<ComparatorExample> () {

public int compare(ComparatorExample obj1, ComparatorExample obj2) {
return (obj1.getName().compareTo(obj2.getName())) ;
}
};

//sorting based on id, ascending order
public static Comparator<ComparatorExample> idComp = new Comparator<ComparatorExample> () {

public int compare(ComparatorExample obj1, ComparatorExample obj2) {
if (obj1.getId() > obj2.getId()) {
return 1;
} else if(obj1.getId() < obj2.getId()) {
return -1;
} else {
return 0;
}
}
};

// Sorting based on dof(i.e date format), ascending order
public static Comparator<ComparatorExample> dofComp = new Comparator<ComparatorExample> () {

public int compare(ComparatorExample obj1, ComparatorExample obj2) {
return obj1.getDof().compareTo(obj2.getDof());
}
};

@Override
public String toString() {
return "Name :"+name +", id : "+id+", dof : "+dof;
}
}
```
` `
`The main class to execute this sorting is,`
`  `

```package com.pr;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;

public class MainClassComparator {
public static void main(String[] args) throws ParseException {

ArrayList<ComparatorExample> list = new ArrayList<ComparatorExample>();
new SimpleDateFormat("yyyy-MM-dd").parse("1988-12-10")));

new SimpleDateFormat("yyyy-MM-dd").parse("1987-12-11")));

new SimpleDateFormat("yyyy-MM-dd").parse("1988-12-09")));

//Sorting based on id property
Collections.sort(list, ComparatorExample.idComp);
System.out.println("Sorting based on id property");
for (ComparatorExample e : list) {
System.out.println(e);
}

//Sorting based on name property
Collections.sort(list, ComparatorExample.nameComp);
System.out.println("Sorting based on name property");
for (ComparatorExample e : list) {
System.out.println(e);
}

//Sorting based on dof property
Collections.sort(list, ComparatorExample.dofComp);
System.out.println("Sorting based on dof property");
for (ComparatorExample e : list) {
System.out.println(e);
}
}
}
```
`OUTPUT : `
```Sorting based on id property
Name :Anand, id : 20, dof : Fri Dec 11 00:00:00 GMT+05:30 1987
Name :Bharat, id : 30, dof : Fri Dec 09 00:00:00 GMT+05:30 1988
Name :Kiran, id : 60, dof : Sat Dec 10 00:00:00 GMT+05:30 1988
```
```Sorting based on name property
Name :Anand, id : 20, dof : Fri Dec 11 00:00:00 GMT+05:30 1987
Name :Bharat, id : 30, dof : Fri Dec 09 00:00:00 GMT+05:30 1988
Name :Kiran, id : 60, dof : Sat Dec 10 00:00:00 GMT+05:30 1988
```
```Sorting based on dof property
Name :Anand, id : 20, dof : Fri Dec 11 00:00:00 GMT+05:30 1987
Name :Bharat, id : 30, dof : Fri Dec 09 00:00:00 GMT+05:30 1988
Name :Kiran, id : 60, dof : Sat Dec 10 00:00:00 GMT+05:30 1988
```

## Saturday 2 September 2017

### How to generate the StackOverflowError and OutOfMemoryError programmatically in Java

Every Java Developer can face this type of error while developing application.  Mostly you will get the java.lang.OutOfMemoryError due to the system memory limitation rather than programming mistake. In this case,  you can increase the heap size of JVM by default it should be 256MB(Java 6).

In this post, will discuss how to generate the OutOfMemoryError and StackOverflowError programmatically.  In OutOfMemoryError, again two types  PermGen space and heap space.
If declared more String literals in application then it will throw PermGen Space error.  If you created so many Objects using new keyword and not garbage collected for unreferenced objects, it will throw heap space error because there is no sufficient memory to create the new objects.

#### java.lang.OutOfMemoryError : java heap space examples(Source code)

``` package com.pr;

public class heapSpaceError {

public void method() {
int value = 10;
for (int i = 0; i<100; i++) {
int count = 5;
int[] a = new int[value];
value = value * 5;
System.out.println(a);
}
}

public static void main(String[] args) {
heapSpaceError error = new heapSpaceError();
error.method();
}
}```
` `
`Output : --`
```[I@eb42cbf
[I@56e5b723
[I@35a8767
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.pr.heapSpaceError.method(heapSpaceError.java:9)
at com.pr.heapSpaceError.main(heapSpaceError.java:16)```
` `
` `

#### java.lang.StackOverflowError  examples(Source code)

The JVM stack is used to store primitive datatype, variables and method invocation and method calls.  If variables are removed, memory is freed for other variables at the end of the method execution. The JVM will throw java.lang.StackOverflowError if there is shortage of memory in the stack area.
Below code is to generate the StackOverflowError programmatically,  by using the recursive calls.

```  package com.pr;

public class StackOverflowErrorEx {

public int m(int i) {
return m(i++);
}

public static void main(String[] args) {
StackOverflowErrorEx ex = new StackOverflowErrorEx();
ex.m(1);
}
} ```
` `
`Output :--`
```Exception in thread "main" java.lang.StackOverflowError
at com.pr.StackOverflowErrorEx.m(StackOverflowErrorEx.java:6)
at com.pr.StackOverflowErrorEx.m(StackOverflowErrorEx.java:6) ```

`Related Post:-`
```
```
`What is PermGen in Java? How to solve the Java.Lang.OutOfMemoryError: PermGen Space`