JDK Version history - Best Features

JDK Version history - Best Features

In this post I'll not go deep into each feature but keep it as a chit-sheet for interview preparation on different JDK best features in different versions. 

JDK 7 - new and best features
1. Diamond operator / Type interface >>
2. String is now allowed in Switch
3.Automatic resource management - try-with-resources statement
4.Underscore in Numeric literals _
5. Improved exception handling - Catching Multiple Exception Type in Single Catch Block
6. New file system API (NIO 2.0)
7. Binary Literals with prefix "0b"
8. Fork and Join
JDK 8 - new and best features
1. Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.
2.Collections :  Classes in the new java.util.stream package provide a Stream API to support functional-style operations on streams of elements.

Reference : [1] [2] [3]

Read more


Creating Web-Service Client for online webservices using AXIS2


Creating WS Client for on-line Web-services...

First we should know who is providing on-line web-services(WS).
http://www.webservicex.net is one such site where we can find different on-line web-services like Stock Quote, IP Locator etc.

We can see WSDL file for each WS in the above site and using this WSDL we need to generate our client and to query the WS .
We can send request to the on-line Web-service and in turn we get response for the request from WS .
So For example if we have generated Stock Quote WS client code , in request we send a symbol (for EX: IBM) to request it's recent stock quote value.
So in response we should get it's latest value and other stuff.

Before we generate WS Client code for provided WSDL in Stock quote from http://www.webservicex.net  .
Let's see how it works

SOAP UI is one of the easiest way to check this out.
Download SOAP UI ZIP and launch the SOAP UI . http://sourceforge.net/projects/soapui/files/soapui/5.0.0/SoapUI-5.0.0-windows-bin.zip/download
After extracting you can run file : soapui.bat from it's extracted location Webservices_Stuff\SoapUI-5.0.0\bin

Create a new project for example StockQuote in SOAPUI and provide WSDL path taken from http://www.webservicex.net for Stock Quote
WSDL used :
http://www.webservicex.net/stockquote.asmx?WSDL

On the left hand side in the SOAPUI new project is created with GetQuote and Request 1 etc.
If we double click the Request 1 we will see a window opened with two parts one with Request XML and other one Response XML.
There in the Request XML if set the ? symbol with IBM like one company symbol and click on run button on the top it gives us the response with
detailed information on the stock.

So now our next job is to create client code for the StockQuote in our eclipse .
So first let's download the AXIS2 project to help on this.
Download axis2-1.6.2-war.zip , from http://archive.apache.org/dist/axis/axis2/java/core/1.6.1/axis2-1.6.1-war.zip
And Create a user library to hold the required jars in path ...
Look for screenshot attached.

Now create a java project with name StockQuote and From Eclipse Run > RunConfigurations create new StockQuote run configuration.
In the main tab provide Project name as StockQuote and provide main class as
org.apache.axis2.wsdl.WSDL2Java

In the Arguments tab
under Program arguments
provide required arguments like

-o C:\Krish\MyDocs\WorkSpaces\My_Java_Workspace\StockQuote
-p com.demo.ws.stock.quote
-u
-uri http://www.webservicex.net/stockquote.asmx?WSDL


Now run this Run Configuration
Refresh the StockQuote Project from left navigation on Eclipse.
Now You should see new code file created for StockQuote Web-Service Client under Src directory.

Observe StockQuoteStub.java file.

to find out how to construct Request and Response objects
Now write your main client class ... sample file looks like below ..

Sample Main Code : 
import java.rmi.RemoteException;

import net.webservicex.www.GetQuote;
import net.webservicex.www.GetQuoteResponse;

import org.apache.axis2.AxisFault;

import com.demo.ws.stock.quote.StockQuoteStub;

public class MainClient {

 public static void main(String[] args) throws RemoteException {

  try {
   StockQuoteStub stub = new StockQuoteStub();
   GetQuote gq = new GetQuote();
   gq.setSymbol("IBM");
   GetQuoteResponse resp = stub.getQuote(gq);
   System.out.println(resp.getGetQuoteResult());
  } catch (AxisFault e) {
   e.printStackTrace();
  }

 }

}
Sample Output after running this WS : 
IBM197.024/15/2014-0.75195.99197.41195.425353177205.2B197.77-0.38%172.19 - 211.9814.94213.24International Bus

Read more


Sorting algorithms in java array

Sorting algorithms in java array
There are many sorting algorithms in data structures world each having their own pros and cons.
let's see how these searching algorithms can be implemented in Java using arrays. 
Below are the implemented searching algorithms  in the below example code.

  •     Implement bubble sort in java.
  •     Implement selection sort in java.
  •     Implement insertion sort in java.
  •     Implement quick sort in java.
  •     Implement merge sort in java.
Sorting class code : 

package com.krish.sorting;

import java.util.Random;

public class SortingTechniques {
 // Applies selection sort technique to the given array
 public static int[] doSelectionSort(int[] arr) {
  for (int i = 0; i < arr.length - 1; i++) {
   int index = i;
   for (int j = i + 1; j < arr.length; j++) {
    if (arr[j] < arr[index]) {
     index = j;
    }
   }
   int smallerNumber = arr[index];
   arr[index] = arr[i];
   arr[i] = smallerNumber;
  }
  return arr;
 }

 // Applies bubble sort technique to the given array
 public static int[] doBubbleSort(int[] arr) {
  int n = arr.length;
  int k;
  for (int m = n; m >= 0; m--) {
   for (int i = 0; i < n - 1; i++) {
    k = i + 1;
    if (arr[i] > arr[k]) {
     swapNumbers(i, k, arr);
    }
   }
  }
  return arr;

 }

 // Applies Insertion sorting Technique
 public static int[] doInsertionSort(int[] arr) {
  int temp;
  for (int i = 1; i < arr.length; i++) {
   for (int j = i; j > 0; j--) {
    if (arr[j] < arr[j - 1]) {
     temp = arr[j];
     arr[j] = arr[j - 1];
     arr[j - 1] = temp;
    }
   }
  }
  return arr;
 }

 // Applies Quick sort to the given array
 public static void doQuickSort(int lowerIndex, int higherIndex,int[] myArray) {
  int i = lowerIndex;
  int j = higherIndex;
  // calculate pivot number, I am taking pivot as middle index number
  int pivot = myArray[lowerIndex + (higherIndex - lowerIndex) / 2];
  // Divide into two arrays
  while (i <= j) {
   /**
    * In each iteration, we will identify a number from left side which
    * is greater then the pivot value, and also we will identify a
    * number from right side which is less then the pivot value. Once
    * the search is done, then we exchange both numbers.
    */
   while (myArray[i] < pivot) {
    i++;
   }
   while (myArray[j] > pivot) {
    j--;
   }
   if (i <= j) {
    exchangeNumbers(i, j,myArray);
    // move index to next position on both sides
    i++;
    j--;
   }
  }
  // call quickSort() method recursively
  if (lowerIndex < j)
   doQuickSort(lowerIndex, j,myArray);
  if (i < higherIndex)
   doQuickSort(i, higherIndex,myArray);
 }

 private static void exchangeNumbers(int i, int j,int[] myArray) {
  int temp = myArray[i];
  myArray[i] = myArray[j];
  myArray[j] = temp;
 }

 private static void swapNumbers(int i, int k, int[] arr) {
  int temp;
  temp = arr[i];
  arr[i] = arr[k];
  arr[k] = temp;
 }

 public static void printArray(int[] printArray) {
  for (int i : printArray) {
   System.out.print(i);
   System.out.print(", ");
  }
 }

 private static int[] getRandomNumbersArray() {
  Random myRandom = new Random();
  int[] randomArray = { myRandom.nextInt(100), myRandom.nextInt(20),
    myRandom.nextInt(600), myRandom.nextInt(60),
    myRandom.nextInt(200) };
  return randomArray;
 }

 public static void main(String[] args) {

  int[] myArray = getRandomNumbersArray();
  System.out.println("\nBefore Selection sort:");
  printArray(myArray);
  System.out.println("\nAfter Selection sort:");
  printArray(doSelectionSort(myArray));
  
  myArray = getRandomNumbersArray();
  System.out.println("\nBefore Bubble sort:");
  printArray(myArray);
  System.out.println("\nAfter Bubble sort:");
  printArray(doSelectionSort(myArray));
  
  myArray = getRandomNumbersArray();
  System.out.println("\nBefore Insertion sort:");
  printArray(myArray);
  System.out.println("\nAfter Insertion sort:");
  printArray(doSelectionSort(myArray));
  myArray = getRandomNumbersArray();
  
  System.out.println("\nBefore Quick sort:");
  printArray(myArray);
  int length = myArray.length;
  doQuickSort(0, length - 1,myArray);
  System.out.println("\nAfter Quick sort:");
  printArray(myArray);
 }
}

 Output : 

Before Selection sort:
10, 0, 480, 41, 175,
After Selection sort:
0, 10, 41, 175, 480,
Before Bubble sort:
77, 3, 91, 4, 8,
After Bubble sort:
3, 4, 8, 77, 91,
Before Insertion sort:
35, 14, 41, 24, 168,
After Insertion sort:
14, 24, 35, 41, 168,
Before Quick sort:
6, 9, 188, 21, 102,
After Quick sort:
6, 9, 21, 102, 188,

References : [1][2]

Read more


Queue implementation using linked list in Java

Queue implementation using linked list in Java
Queue is another famous data structure which allows operating from two ends(front and rear) through head and tail. It works in First In First Out(FIFO) fashion.
Queue data structure is like two ended room which allows entry(enqueue) from one end called as rear and exit (dequeue) from another end called a front...
So to remember , queue always supports insertion from rear-end / tail and deletion called as dequeue happens only from fron end / head.

Let's see how can we implement simple Queue data structure in Java using a single linked list. 

We need follow the Cell class we have used in the Stack example in the previous post.

Queue main class : 
package com.krish.queue;

import com.krish.datastructures.common.Cell;

public class QueueMain {
 Cell head;
 Cell tail;

 public QueueMain() {
  head = null;
  tail = null;
 }

 public void enqueue(Object obj) {
  Cell newCell = new Cell(obj, null);
  if (head == null && tail == null)
   head = newCell;
  else
   tail.next = newCell;
  tail = newCell;
  System.out.println("Enqueud element:"+obj);
  printQueue();
 }

 public Cell front() {
  return head;
 }

 public Cell rear() {
  return tail;
 }

 public void dequeue() {
  if (head == null && tail == null) {
   System.out.println("Q is empty");
  } else {
   System.out.println("Dequeued element:"+head.getVal());
   if (head.next == null) {
    tail = null;
   }
   head = head.next;
  }
  printQueue();
 }

 public int getsize() {
   int size = 0;
  if(!(head ==null && tail == null)){
     size = 1;
     for(Cell n = head; n.next != null; n = n.next)
         size = size+1; 
  
     return size;
  }
  return size;
  }

 public void printQueue() {
  if (head == null && tail == null) {
   System.out.println("Q is empty");
  } else {
   System.out.println("Q Elememts:");
   Cell current = head;
   System.out.println("Head");
   while (current != null) {
    System.out.println("->" + current.getVal());
    current = current.next;
   }
   System.out.println("<--tail br="">   System.out.println("Size of the Q:"+getsize());
  }
 }

 public static void main(String[] args) {
  QueueMain queue = new QueueMain();
  queue.enqueue(23);
  queue.enqueue(43);
  queue.enqueue(143);
  queue.enqueue(321);
  queue.dequeue();
  queue.dequeue();
 }
}
Output : 
Enqueud element:23
Q Elememts:
Head
->23
<--tail br="">Size of the Q:1
Enqueud element:43
Q Elememts:
Head
->23
->43
<--tail br="">Size of the Q:2
Enqueud element:143
Q Elememts:
Head
->23
->43
->143
<--tail br="">Size of the Q:3
Enqueud element:321
Q Elememts:
Head
->23
->43
->143
->321
<--tail br="">Size of the Q:4
Dequeued element:23
Q Elememts:
Head
->43
->143
->321
<--tail br="">Size of the Q:3
Dequeued element:43
Q Elememts:
Head
->143
->321
<--tail br="">Size of the Q:2

References : [1][2][3][4]

Read more


Stack implementation using linked list in Java

Stack implementation using linked list in Java with out using arrays

We have seen implementing the stack using arrays in java in the previous post which has certain drawbacks like inserting / deleting an element from the desired or particular location.

So in a linked list there is a connection for each node / cell (it contains one object to hold desired value and link to the next node / cell). 

So when user pushed an element to the stack first element goes to the end, and the recently pushed item will have connection to the last recent item. 

so when a new node is pushed, existing top becomes old and new one becomes top similarly for each pop operation in stack takes out top element and his next becomes present top. 

below example code helps to understand linked list creation using Cell class an StackUsing LinkedList class helps will do actual push and pop operations


Cell Class : (Linked list) :
package com.krish.datastructures.common;

public class Cell {
	Object val; // value in the cell
	public Cell next; // the address of the next cell in the list

	/**
	 * Constructor Cell builds a new cell
	 * 
	 * @param value
	 *            - the value inserted in the cell
	 * @param link
	 *            - the cell that is chained to this new cell
	 */
	public Cell(Object value, Cell link) {
		val = value;
		next = link;
	}

	/** getVal returns the value held in the cell */
	public Object getVal() {
		return val;
	}

	/** getNext returns the address of the cell chained to this one */
	public Cell getNext() {
		return next;
	}

	/**
	 * setNext resets the address of the cell chained to this one
	 * 
	 * @param link
	 *            - the address of the Cell that is chained to this one
	 */
	public void setNext(Cell link) {
		next = link;
	}
}


Stack using Linked list : 

package com.krish.stack;

import com.krish.datastructures.common.Cell;

public class StackUsingLinkedLists {
	public static Cell top;

	/** Constructor Stack creates an empty stack */
	public StackUsingLinkedLists() {
		top = null;
	}

	/**
	 * push inserts a new element onto the stack
	 * 
	 * @param ob
	 *            - the element to be added
	 */
	public void push(Object ob) {
		System.out.println("PUSH : Inserted the element:" + ob);
		top = new Cell(ob, top);
		printStack();
	}

	/**
	 * pop removes the most recently added element prints error if stack is
	 * empty
	 */
	public void pop() {
		if (top == null) {
			System.out.println("POP: Stack error: stack empty");
		} else {
			Object answer = top.getVal();
			top = top.getNext();
			System.out.println("POP: popped the element:" + answer);
			printStack();
		}

	}

	/**
	 * top returns the identity of the most recently added element
	 * 
	 * @return the element
	 * @exception RuntimeException
	 *                if stack is empty
	 */
	public Object top() {
		if (top == null) {
			throw new RuntimeException("Stack error: stack empty");
		}
		return top.getVal();
	}

	/**
	 * isEmpty states whether the stack has 0 elements.
	 * 
	 * @return whether the stack has no elements
	 */
	public boolean isEmpty() {
		return (top == null);
	}

	// Print the stack elements by using top and next
	public void printStack() {
		if (top == null) {
			System.out.println("PRINT: Stack error: stack empty");
		} else {
			System.out.println("PRINT:These are the stack elements now!");
			Cell temp = top;
			while (temp != null) {
				System.out.println(temp.getVal());
				temp = temp.next;
			}
		}
	}

	public static void main(String[] args) {
		StackUsingLinkedLists stack = new StackUsingLinkedLists();
		stack.pop();
		stack.push(23);
		stack.push(267);
		stack.push(500);
		stack.pop();
		stack.pop();
		stack.pop();
	}
}
Output : 
POP: Stack error: stack empty
PUSH : Inserted the element:23
PRINT:These are the stack elements now!
23
PUSH : Inserted the element:267
PRINT:These are the stack elements now!
267
23
PUSH : Inserted the element:500
PRINT:These are the stack elements now!
500
267
23
POP: popped the element:500
PRINT:These are the stack elements now!
267
23
POP: popped the element:267
PRINT:These are the stack elements now!
23
POP: popped the element:23
PRINT: Stack error: stack empty
Reference : [1] [2

Read more


Stack implementation in Java

Stack implementation in Java
Stack : Stack in first in last out operated data structure ,where the first inserted (push'ed)element into the stack will be taken out (pop'ed) at last. it is like single door room . Those who enters room first will be able to come out only in the last . In other word last pushed element will be poped out first .

which we call generally as LIFO - Last In First Out

We can implement this stack using Java arrays like below ...
The below implementation takes/reads size of the stack what user want to create and implements stack operations.

Main Program :
package com.krish.stack;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class StackMain {

	public static void main(String[] args) {
		try{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String size;

		System.out.println("Enter stack size u want to create : ");
		size = br.readLine();
		System.out.println("Creating a Stack size is:"+Integer.parseInt(size));
		Stack stack = new Stack(Integer.parseInt(size));
		stack.printStackElements();
		stack.push(100);
		stack.push(200);
		stack.push(300);
		stack.pop();
		stack.pop();
		stack.pop();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

}

Stack Class:  
package com.krish.stack;

public class Stack {
	int[] myStack;
	int top = -1;
	int size;

	public Stack(int size) {
		this.size = size;
		myStack = new int[size];
	}

	public void printStackElements() {
		if (top >= 0) {
			System.out.println("Present elements in the stack:");
			for (int i = 0; i <= top; i++) {
				System.out.println("Element at " + i + "position is "
						+ myStack[i]);
			}

		} else {
			System.out.println("Stack is empty");

		}

	}

	public void push(int element) {
		if (top < size - 1) {
			System.out.println("Pushing " + element + " to stack now");
			System.out.println("After push()");
			top++;
			myStack[top] = element;
			printStackElements();

		} else {
			System.out.println("Stack overflow; element can't be pushed");
		}
	}

	public void pop() {
		if (top >= 0) {
			System.out.println("Poping the top element now:" + myStack[top]);
			top--;
			printStackElements();
		} else {
			System.out.println("stack undeflow");
		}
	}
}

Output : 
 Enter stack size u want to create :
2
Creating a Stack size is:2
Stack is empty
Pushing 100 to stack now
After push()
Present elements in the stack:
Element at 0position is 100
Pushing 200 to stack now
After push()
Present elements in the stack:
Element at 0position is 100
Element at 1position is 200
Stack overflow; element can't be pushed
Poping the top element now:200
Present elements in the stack:
Element at 0position is 100
Poping the top element now:100
Stack is empty
stack undeflow

Advantages and disadvanaatages of using arrays in this : 
1. We can access any stack element when in array at any point of time randomly. 
2. Size is fixed we can't add more elements.
3. If we want to remove an element in between the elements then it is difficult to adjust the other elements. 
4. IF we want to insert at a particular position in between the array also it is difficult.

Reference : [1]

Read more

Translate

Enter your email address:

Buffs ...

Visitors


hits counter
View My StatsCheck Google Page Rank

Add to Google Reader or Homepage

Bookmark and Share

Tags


Powered by WidgetsForFree