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


SQL injection - Java

SQL Injection 

SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker).[1] SQL injection must exploit a security vulnerability in an application's software, for example, when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database.
   
PreparedStatements are the way to go, because they make SQL injection impossible. Here's a simple example taking the user's input as the parameters:

public insertUser(String name, String email) {
   Connection conn = null;
   PreparedStatement stmt = null;
   try {
      conn = setupTheDatabaseConnectionSomehow();
      stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
      stmt.setString(1, name);
      stmt.setString(2, email);
      stmt.executeUpdate();
   }
   finally {
      try {
         if (stmt != null) { stmt.close(); }
      }
      catch (Exception e) {
         // log this error
      }
      try {
         if (conn != null) { conn.close(); }
      }
      catch (Exception e) {
         // log this error
      }
   }
}
Reference : http://stackoverflow.com/questions/1812891/java-escape-string-to-prevent-sql-injection

Read more


JDBC - Java - Interview questions

JDBC - Java - Theory - Interview questions
JDBC Basics :

    Establishing a connection. : First, establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. This connection is represented by a Connection object.
    Create a statement. : A Statement is an interface that represents a SQL statement. You execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. You need a Connection object to create a Statement object.
  
    There are three different kinds of statements:

    Statement: Used to implement simple SQL statements with no parameters.
    PreparedStatement: (Extends Statement.) Used for precompiling SQL statements that might contain input parameters. See Using Prepared Statements for more information.
    CallableStatement: (Extends PreparedStatement.) Used to execute stored procedures that may contain both input and output parameters. See Stored Procedures for more information.

    Execute the query. :
    To execute a query, call an execute method from Statement such as the following:

    execute: Returns true if the first object that the query returns is a ResultSet object. Use this method if the query could return one or more ResultSet objects. Retrieve the ResultSet objects returned from the query by repeatedly calling Statement.getResultSet.
    executeQuery: Returns one ResultSet object.
    executeUpdate: Returns an integer representing the number of rows affected by the SQL statement. Use this method if you are using INSERT, DELETE, or UPDATE SQL statements.

    Process the ResultSet object. : You access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor. This cursor is a pointer that points to one row of data in the ResultSet object. Initially, the cursor is positioned before the first row. You call various methods defined in the ResultSet object to move the cursor.
    Close the connection. : When you are finished using a Statement, call the method Statement.close to immediately release the resources it is using. When you call this method, its ResultSet objects are closed.

For example, the method CoffeesTables.viewTable ensures that the Statement object is closed at the end of the method, regardless of any SQLException objects thrown, by wrapping it in a finally block:

} finally {
    if (stmt != null) { stmt.close(); }
}

JDBC throws an SQLException when it encounters an error during an interaction with a data source.

Read more


DB2 - GROUP BY - HAVING

DB2 - GROUP BY - HAVING
GROUP BY : To group different rows of data on specific coloumn name .
HAVING : on finale output of select query put we can put a condition to filter specific
Note : While "WHERE" is used to apply selection criteria to the base data, "HAVING" is used to apply selection criteria to the grouped data:

Example 1 :

TOUR_GROUP : Table has following coloumns

TOUR    GUIDE    LANGUAGE    TOUR_DATE    START_TIME    END_TIME    GROUP_SIZE    AVAILABILITY
Query 1 :

SELECT LANGUAGE, COUNT(*) "NUMBER_OF_TOURS", MAX(GROUP_SIZE) "MAX_GROUP_SIZE", MIN(GROUP_SIZE) "MIN_GROUP_SIZE"
FROM TOUR_GROUP
GROUP BY LANGUAGE
ORDER BY NUMBER_OF_TOURS;

Query 2 :
SELECT LANGUAGE, COUNT(*) "NUMBER_OF_TOURS", MAX(GROUP_SIZE) "MAX_GROUP_SIZE", MIN(GROUP_SIZE) "MIN_GROUP_SIZE"
FROM TOUR_GROUP
WHERE GROUP_SIZE <= 20
GROUP BY LANGUAGE
HAVING COUNT(*) > 1
ORDER BY NUMBER_OF_TOURS;
Query 3 :
SELECT TOUR, COUNT (DISTINCT LANGUAGE) "NUMBER_LANGUAGES"
FROM TOUR_GROUP
GROUP BY TOUR
ORDER BY COUNT(DISTINCT LANGUAGE), TOUR;

Reference : [1] [2]

Read more


Design pattern interview questions

Design pattern interview questions
  •  What is design patterns ? Have you used any design pattern in your code ?
Design patterns are tried and tested way to solve particular design issues by various programmers in the world. Design patterns are extension of code reuse.
  • Can you name few design patterns used in standard JDK library?
    • Decorator design pattern which is used in various Java IO classes,
    • Singleton pattern which is used in Runtime ,Calendar and various other classes,
    • Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf.
    • Observer pattern which is used in Swing and many event listener frameworks.
  • What is Singleton design pattern in Java ? write code for thread-safe singleton in Java.
    • Singleton pattern focus on sharing of expensive object in whole system. Only one instance of a particular class is maintained in whole application which is shared by all modules. Java.lang.Runtime is a classical example of Singleton design pattern. From Java 5 onwards you can use enum to thread-safe singleton.
  • What is MVC design pattern ? Give one example of MVC design pattern ?
    • Model-view-controller (MVC) is a pattern used to isolate business logic from the user interface. Using MVC, the Model represents the information (the data) of the application and the business rules used to manipulate the data, the View corresponds to elements of the user interface such as text, checkbox items, and so forth, and the Controller manages details involving the communication between the model and view. The controller handles user actions such as keystrokes and mouse movements and pipes them into the model or view as required.
    • MVC is often seen in web applications, where the view is the actual HTML page, and the controller is the code that gathers dynamic data and generates the content within the HTML. Finally, the model is represented by the actual content, usually stored in a database or XML files, and the business rules that transform that content based on user actions.
    • Struts frame work follows MVC.
    • caliculator design cane be one example of MVC.
  • Adapter design pattern ? Give examples of adapter design pattern in Java?
    • The Adapter Design Pattern allows you to make an existing class work with other existing class libraries without changing the code of the existing class.
    • We often need to use the methods of an existing class to work with other existing libraries. The way to do this is by creating another class, named the Adapter, that inherits from the existing class while implementing the interface of the existing library. The end result is that the Adapter can call the method of the existing class (since the Adapter inherits from the existing class) and can work in the existing library (since the Adapter implements the interface of the existing library).
    • Adaptee >Adapter > Interface.
    • adapter design pattern
  • ddd
References : [1] [2] [3]

Read more


Sorting a list using comparator (Difference between Comparator and Comparable in Java)


One of the common interview question is "What are differences between Comparator and Comparable". or "How will you sort collection of employee objects by its id or name". For that we can use two interfaces, i.e., Comparator and Comparable. Before we actually see differences,let me give you brief introduction of both.
Comparable interface
Class whose objects to be sorted must implement this interface. In this, we have to implement compareTo(Object) method.
Comparator interface
The class whose objects to be sorted do not need to implement this interface. Some third class can implement this interface to sort. E.g., xyz class can implement Comparator interface to sort collection of ABC object by id , by name etc
Here is a simple example using comparator interface sorted a simple list with custom objects...
Program :
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CollectionEmployee implements Comparator
 {

    /**
     * @param args
     */
    public int empID;
    public String empName;

    public CollectionEmployee(int eid, String ename) {
        empID = eid;
        empName = ename;
    }

    public int compare(CollectionEmployee object1, CollectionEmployee object2) {
        // TODO Auto-generated method stub
        return ((object1.empID > object2.empID) ? 1 : 0);
    }

    public static void main(String[] args) {
        List
 empList = new ArrayList
();
        empList.add(new CollectionEmployee(100, "saurabh"));
        empList.add(new CollectionEmployee(300, "Anirudh"));
        empList.add(new CollectionEmployee(200, "Babu"));
        System.out.println("----list as it is ------");
        for (CollectionEmployee emp : empList) {
            System.out.println("No: " + emp.empID + " Name: " + emp.empName);
        }
        System.out.println("----Sorted by id------");
        Collections.sort(empList, new CollectionEmployee(200, "hari"));
        for (CollectionEmployee emp : empList) {
            System.out.println("No: " + emp.empID + " Name: " + emp.empName);
        }
        System.out.println("----Sortd by name-----------");
        // Sort by name
        Collections.sort(empList, new CollectionEmployee(200, "hari") {

            @Override
            public int compare(CollectionEmployee o1, CollectionEmployee o2) {
                return o1.empName.compareTo(o2.empName);
            }
        });
        for (CollectionEmployee emp : empList) {
            System.out.println("No: " + emp.empID + " Name: " + emp.empName);
        }
    }

}
Output :
----list as it is ------
No: 100 Name: saurabh
No: 300 Name: Anirudh
No: 200 Name: Babu
----Sorted by id------
No: 100 Name: saurabh
No: 200 Name: Babu
No: 300 Name: Anirudh
----Sortd by name-----------
No: 300 Name: Anirudh
No: 200 Name: Babu
No: 100 Name: saurabh
Reference : [1]

Read more

Popular Posts

Enter your email address:

Buffs ...

Tags


Powered by WidgetsForFree

Archives