Tuesday 30 July 2013

How to get and put value in HashMap in Generic way

1. Creating a class with main method, and defining your own method to put and get value from hashmap. HashMap as we know is a pair of key and values so K is as Key and V is representing Value with correspondent key.


package tts.test.hashmap;

import java.util.HashMap;
import java.util.Map;

public class TestMap<K, V> {

Map<K, V> map = new HashMap<>();
public V putInToHashMap(K key, V value) {
return map.put(key, value);

}
public V getValueFromHashMap(K key) {
return map.get(key);

}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
TestMap map= new TestMap<>();
map.putInToHashMap("Bharat", 11223344);
map.putInToHashMap("KDS", 22334455);
map.putInToHashMap("Dipak", 33445566);
map.putInToHashMap("Santosh", 44556677);
map.putInToHashMap("Umesh", 55667788);
System.out.println("Element  is :"+map.getValueFromHashMap("Bharat"));
}

}


2. Output
Element  is :11223344

Thank You

Thursday 11 July 2013

Creating Custom exception in java

1. Define a class and extend Throwable or Exception class


package tts.test.exception;
public class InvalidAmountException extends Throwable {
private static final long serialVersionUID = 1L;
public InvalidAmountException(String message) {
super(message);
}
}


2. To test user defined exception create a main class and use throw your own defined exception inside try block and can be handled inside catch another way is to handle inside header of main method here example showing handling inside header of main method
NOTE: User defined exception are mostly checked exception unless you will not categorized any run time exception

package tts.test.exception;

import java.util.Scanner;
public class TestCustomException {
public static void main(String[] args) throws InvalidAmountException {
double acc_balance = 50_000;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your amount to withdraw:");
double withdraw_amount = scanner.nextDouble();
if (acc_balance < withdraw_amount) {
throw new InvalidAmountException(
"Sorry! Your amount is invalid or exceding limit.");
}
System.out.println("Thank for using Personal Bank!!!");
}
}


3 Out put 

If entered amount is less then 50000

Enter your amount to withdraw:
1000
Thank for using Personal Bank!!!
-------------------------------------------------------

If amount is greater than 50000

Enter your amount to withdraw:
600000
Exception in thread "main" tts.test.exception.InvalidAmountException: Sorry! Your amount is invalid or exceding limit.
at tts.test.exception.TestCustomException.main(TestCustomException.java:11)


3. Now lets  dig more into java exceptions from  the above class extending InputMismatchException and see there is no need of adding throws or try catch at compile or declaration time means exception will be fire at run time only if any condition violates. Lets see  what is happening here at run time




package tts.test.exception;
import java.util.InputMismatchException;
public class InvalidAmountException extends InputMismatchException {
private static final long serialVersionUID = 1L;
public InvalidAmountException(String message) {
super(message);
}
}


Now  test the new custom exception class 



package tts.test.exception;
import java.util.Scanner;
public class TestnputMismatchException {
public static void main(String[] args) {
double acc_balance = 50_000;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your amount to withdraw:");
double withdraw_amount = scanner.nextDouble();
if (acc_balance < withdraw_amount) {
throw new InvalidAmountException(
"Sorry! Your amount is invalid or exceding limit.");
}
System.out.println("Thank for using Personal Bank!!!");
}
}


4. Out put


When input is: 

Enter your amount to withdraw:
1000
Thank for using Personal Bank!!!
----------------------------------------
When input contain ant illegal  number as any character

Enter your amount to withdraw:
111a12
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)

at tts.test.exception.TestnputMismatchException.main(TestnputMismatchException.java:10)



Hope it will be usefull

Thank You



Singleton pattern in java

1. Singleton means sharing only one instance of a class in whole application, Singleton is a behavior  of an instance of a class to extremely extract implementing polymorphic concept. Below example show only one instance will created at class load time and it's declared as final so there is no way to create another one this is default thread safe singleton class and recommended by most of the java experts.


public class TestSingleton  {

private static final TestSinglton TEST_SINGLETON = new TestSinglton();

private TestSingleton  () {

// Stop Polymorphic behaviour 

}

public static TestSingleton  getInsSingleton () 

{ 

return TEST_SINGLETON;

}

}


2. Another way of creating single instance  of a class, Instance will be created only once whenever it required this is also called laze initialization 

public class TestSingleton {

private static  TestSingleton TEST_SINGLETON = null;

private TestSinglton() {

// Stop Polymorphic behaviour

}

public static TestSingleton getInsTestSingleton () {

if(TEST_SINGLETON == null){

TEST_SINGLETON =  new TestSingleton ();

}

return TEST_SINGLETON;

}

}


3. This is not thread safe so programmer have to make explicitly thread safe 


public class TestSingleton {

private static TestSingleton  TEST_SINGLETON = null;

private TestSingleton () {

// Stop Polymorphic behaviour
}
public static TestSingleton getInsTestSingleton () {

if (TEST_SINGLETON == null) {
synchronized (TestSingleton.class) {
TEST_SINGLETON = new TestSingleton ();

}
}
return TEST_SINGLETON;
}
}

4. Still clone of  Singleton class can be create and a duplicate instance can be obtained to resolve this problem need to override clone() method of object class see example


public class TestSingleton {

private static TestSingleton TEST_SINGLETON = null;

private TestSingleton() {

// Stop Polymorphic behaviour

}

public static TestSingleton getInsTestSingleton() {

if (TEST_SINGLETON == null) {

synchronized (TestSingleton.class) {

TEST_SINGLETON = new TestSingleton();

}

System.out.println(" I am created only  once");

}

return TEST_SINGLETON;

}

public Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}

public static void main(String[] args) {

TestSingleton.getInsTestSingleton();

}

}

5. Out put

 I am created only  once


NOTE: One more important things is to notice here i am calling getInsTestSingleton() method five times and out put is same see  example

public class TestSingleton {

private static TestSingleton TEST_SINGLETON = null;

private TestSingleton() {

// Stop Polymorphic behaviour

}

public static TestSingleton getInsTestSingleton() {

if (TEST_SINGLETON == null) {

synchronized (TestSinglton.class) {

TEST_SINGLETON = new TestSingleton();

}

System.out.println(" I am created only  once");

}

return TEST_SINGLETON ;

}

public Object clone() throws CloneNotSupportedException {

throw new CloneNotSupportedException();

}

public static void main(String[] args) {

TestSingleton.getInsTestSingleton();//1

TestSingleton.getInsTestSingleton();//2

TestSingleton.getInsTestSingleton();//3

TestSingleton.getInsTestSingleton();//4

TestSingleton.getInsTestSingleton();//5

}

}


6. Out put

 I am created only  once



Hope this will useful.
Thank You

Wednesday 3 July 2013

How serialization works in java and what is importance serialVersionUID

1.  Lets has a Class User and implements Serializable Interface, When we serialize an class in java then  serialVersionUID  is very important during reading serialized data.

Note:  Run this code only in java7 or remove multiexception  handling catch


package com.test.serilizable;

import java.io.Serializable;

public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int userId;
private String userName;
private String fullName;
private transient int deviceId;     // This field will not be   participate in serialization process

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getFullName() {
return fullName;
}

public void setFullName(String fullName) {
this.fullName = fullName;
}

public int getDeviceId() {
return deviceId;
}

public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}

}

2. Here take another  class as SerializationDemo with main method. To serialize object we need the class as ObjectOutputStream which has method  writeObject to write data in for of stream lets  how it works here...


package com.test.serilizable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializationDemo {
public static void main(String[] args) throws IOException {
ObjectOutputStream objectOutputStream = null;
try {
User user = new User();
user.setUserId(1);
user.setUserName("ramu");
user.setFullName("Ramesh Chandra Srivastava");
user.setDeviceId(1001);
File dir = new File("C:/Serialization");
if (!dir.exists()) {
dir.mkdir(); // Create directory(folder) in C drive if doesn't exist
}
objectOutputStream = new ObjectOutputStream(new FileOutputStream(
dir + "/user.ser"));
objectOutputStream.writeObject(user);
System.out.println("Object has been  written successfully!!!!!!");

} catch (Exception ex) {
ex.printStackTrace();
} finally {
objectOutputStream.close();
System.out.println("ObjectOutputStream has been closed successfully");
}
}
}

3. Out put


Object has been  written successfully!!!!!!
ObjectOutputStream has been closed successfully


4. Now see to to deserialize data  from serialized to accomplish this process  we need ObjectInputStream class which has method readObject used to reform object again


package com.test.serilizable;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializationDemo {
public static void main(String[] args) throws IOException {
ObjectInputStream objectInputStream= null;
try{
objectInputStream = new ObjectInputStream(new FileInputStream("C:/Serialization/user.ser"));
User user= (User) objectInputStream.readObject();
System.out.println(user.getUserId() +"  "+user.getUserName()+"  "+user.getUserName() +"  "+ user.getDeviceId());
} catch (FileNotFoundException | ClassNotFoundException ex){
ex.printStackTrace();
} finally{
objectInputStream.close();
System.out.println("ObjectInputStream has been closed");
}
}

}

5 Out put


1  ramu  ramu  0
ObjectInputStream has been closed



6.  Here the deviceId is has value 1001 and still in output is 0 means the transient  fields aren't serialized.
What is role of  serialVersionUID here in User class lets have  some practical. After serialized Here i am updating User class and comment the  serialVersionUID  lets see what is its difference...



package com.test.serilizable;

import java.io.Serializable;

public class User implements Serializable {
//private static final long serialVersionUID = 1L;
private int userId;
private String userName;
private String fullName;
private transient int deviceId;
private String address;                        // Recently addded after seralized class

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getFullName() {
return fullName;
}

public void setFullName(String fullName) {
this.fullName = fullName;
}

public int getDeviceId() {
return deviceId;
}

public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}

}


6.  Executing DeserializationDemo  again



package com.test.serilizable;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializationDemo {
public static void main(String[] args) throws IOException {
ObjectInputStream objectInputStream= null;

try{
objectInputStream = new ObjectInputStream(new FileInputStream("C:/Serialization/user.ser"));
User user= (User) objectInputStream.readObject();
System.out.println(user.getUserId() +"  "+user.getUserName()+"  "+user.getUserName() +"  "+ user.getDeviceId());
} catch (FileNotFoundException | ClassNotFoundException ex){
ex.printStackTrace();

} finally{
objectInputStream.close();
System.out.println("ObjectInputStream has been closed");
}
}

}


7. Output


ObjectInputStream has been closedException in thread "main"
java.io.InvalidClassException: com.test.serilizable.User; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 7164343529204429975
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.test.serilizable.DeserializationDemo.main(DeserializationDemo.java:14)


Oh!!! what is here an Exception, So serialVersionUID really important in serialization  its check the version of the class, If you write the serialVersionUID  the there is no error means it tell the JVM  that the updated  User class is new version of User class. 

Hope you understand the serialization process in java.

Thank You


Saturday 29 June 2013

Searching an element in HashMap in java

1. Creating a java class with main method and implementing map collection

package map.search.value;

import java.util.HashMap;
import java.util.Map;

public class TestHashMapSearch {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Amir", 65676665);
map.put("Samma", 97653244);
map.put("Qunal", 011563435);
map.put("Nibbil", 88088099);
map.put("Suprema", 342267788);
map.put("Janiya", 990099434);
//If there is multiple kay as Amir then it will pick up last value
System.out.println("Value with correspondent key is: "+map.get("Amir"));
}

}

2. Out put


Value with correspondence key is: 65676665

Tuesday 25 June 2013

Removing duplicate data from ArrayList stores List of User objects

1. Create User class and @Override equals method to check duplicate user object

package tts.remove.duplicate;

public class User {
private int userId;
private String userName;
private String firstName;
private String lastName;

public User() {
// TODO Auto-generated constructor stub
}

public User(int id, String username, String fName, String lName) {
this.userId = id;
this.userName = username;
this.firstName = fName;
this.lastName = lName;
}

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

@Override
public boolean equals(Object obj) {
//System.out.println("Equals is calling...");
if (obj.getClass() != getClass()) {
return false;
}
User user = (User) obj;
if (this.userName.equalsIgnoreCase(user.userName)
&& this.userId == user.userId) {
return true;
}
return false;
}

@Override
public int hashCode() {

int hashCode = 31;
hashCode = hashCode + this.userName != null ? this.userName.hashCode() : null;
return hashCode;
}

}

2. Create a class as RemoveDuplicateUsers to remove duplicate data from User objecj

package tts.remove.duplicate;

import java.util.ArrayList;
import java.util.List;

public class RemoveDuplicateUsers {
public static void main(String[] args) {
List<User> userList = new ArrayList<User>();
userList.add(new User(1, "santoshtts", "Santosh", "Srivastava"));
userList.add(new User(1, "santoshtts", "Santosh", "Srivastava"));
userList.add(new User(2, "dipakdwivedi", "Dipak", "Dwivedi"));
userList.add(new User(2, "dipakdwivedi", "Dipak", "Dwivedi"));
userList.add(new User(3, "umeshyadav", "Umesh", "Yadav"));
userList.add(new User(3, "umeshyadav", "Umesh", "Yadav"));
userList.add(new User(4, "sonumandal", "Sonu", "Mandal"));
userList.add(new User(4, "sonumandal", "Sonu", "Mandal"));
userList.add(new User(5, "binodsoni", "Vinod", "Soni"));
userList.add(new User(5, "binodsoni", "Vinod", "Soni"));
System.out.println("Before removing duplicate list size is: "
+ userList.size() + "\n Data in list ");
List<User> uniqueList = new ArrayList<User>();
System.out.println("----------------------------------------------");
for (User user2 : userList) {
if (!uniqueList.contains(user2)) {
uniqueList.add(user2);

}
System.out.println(user2.getUserId() + " " + user2.getUserName()
+ " " + user2.getFirstName() + " " + user2.getLastName());
}
System.out
.println("_______________________________________________ \n");
System.out.println("After removing duplicate list size is: "
+ uniqueList.size() + "\n Data in list ");
System.out.println("----------------------------------------------");
for (User user : uniqueList) {
System.out.println(user.getUserId() + " " + user.getUserName()
+ " " + user.getFirstName() + " " + user.getLastName());
}

}

}

3. Output

Before removing duplicate list size is: 10
 Data in list 
----------------------------------------------
1 santoshtts Santosh Srivastava
1 santoshtts Santosh Srivastava
2 dipakdwivedi Dipak Dwivedi
2 dipakdwivedi Dipak Dwivedi
3 umeshyadav Umesh Yadav
3 umeshyadav Umesh Yadav
4 sonumandal Sonu Mandal
4 sonumandal Sonu Mandal
5 binodsoni Vinod Soni
5 binodsoni Vinod Soni
_______________________________________________ 

After removing duplicate list size is: 5
 Data in list 
----------------------------------------------
1 santoshtts Santosh Srivastava
2 dipakdwivedi Dipak Dwivedi
3 umeshyadav Umesh Yadav
4 sonumandal Sonu Mandal
5 binodsoni Vinod Soni


Here you can also use  Set<User> uniqueList = new HashSet<User>();  instead  List<User> uniqueList = new ArrayList<User>();

Thursday 13 June 2013

Sorting Object in ArrayList on the bases of field as name and id in java using comperator

Step 1: Create a Bean class

public class CommonPojo {
private int empId;
private String empName;
public CommonPojo() {
// TODO Auto-generated constructor stub
}
public CommonPojo(int id, String name) {
this.empId=id;
this.empName= name;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}

}

Step 2: Writing an UniversalSorting class to sort the objects


import java.util.Comparator;

public class UniversalSorting {
public static enum CommonSort implements Comparator<CommonPojo> {
BY_NAME {
@Override
public int compare(CommonPojo commonPojo1, CommonPojo commonPojo2) {

return commonPojo1.getEmpName().compareTo(commonPojo2.getEmpName());
}
},
BY_ID {
@Override
public int compare(CommonPojo commonPojo1, CommonPojo commonPojo2) {

return commonPojo1.getEmpId() - commonPojo2.getEmpId();

}

}
}
}

Step 3:  Create an universal method in TestCommonSort  class to sort the objects and test it



import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestCommonSort {
public static void main(String[] args) {
sortEmployee(UniversalSorting.CommonSort.BY_NAME);
//sortEmployee(UniversalSorting.CommonSort.BY_ID);

}
public static void sortEmployee(UniversalSorting.CommonSort sorting){
try{

List<CommonPojo> listPojo= new ArrayList<CommonPojo>();
listPojo.add(new CommonPojo(1, "Sumit"));
listPojo.add(new CommonPojo(1, "Kuldeep"));
listPojo.add(new CommonPojo(1, "Sanjay"));
listPojo.add(new CommonPojo(31, "Umesh"));
listPojo.add(new CommonPojo(4, "Abhishek"));
listPojo.add(new CommonPojo(6, "Santosh"));
listPojo.add(new CommonPojo(7, "Bharat"));
listPojo.add(new CommonPojo(88, "Dipak"));
Collections.sort(listPojo, sorting);
for(CommonPojo commonPojo: listPojo){
System.out.println(commonPojo.getEmpName());
}

} catch (Exception ex){
ex.printStackTrace();
}
}
}

Step 4: Output

Bharat
Dipak
Kuldeep
Sanjay
Santosh
Sumit
Umesh