How to create user defined immutable class in Java?

In this tutorial we will discuss about how to create immutable class in Java. When we say about immutable we will be remembered about important interview question like What is the difference between String and StringBuilder? We are familiar with String is a immutable and StringBuilder is mutable where values once assigned to String variable cannot the changed. 

Yes correct same way this is also interview question as how to create user defined immutable class in Java? Its simple just by Final modifier we can create our own immutable class. For this we need to make class, methods and member variable in the class as Final. By changing the modifier as final one cannot extend the class or override the methods and even cannot change the value once assigned to member variables. By this we can implement our own immutable class.

In below example code will show how to immutable class in Java.



public final class MyImmutableClass {
 
 private final String empName;
 
 public MyImmutableClass(String empName) {
  this.empName = empName;
 }
 
 public String getEmpName(){
  return this.empName;
 }
}



public class TestMyImmutable {
 public static void main(String[] args) {
  MyImmutableClass obj = new MyImmutableClass("Raj");
  
  /* 
   * Values once assigned cannot to changed by using set methods.
   * Just we can get the value assigned to the variable.
  */
  String empName = obj.getEmpName();
  System.out.println("Emp Name : "+empName);  
 }
}







TreeMap using custom object sorting

 
We know that by default TreeMap will sort the values using key. Suppose if we need to sort the TreeMap using object stored in key part then we need to implement the Comparator interface and we need to @Override compare() method which will sort 2 Objects of key path and will give us the sorted output. 

Below single example will show you how to use custom Object sorting in TreeMap. TreeMap will take "Worker class instance" as key and "String name" as value. Where we need to sort the values using key based on the member variables in the Worker class. 

Class "MyNameComp" which implements the Comparator interface on "Worker" class and used to sort TreeMap based on name or salary. Below example will gives you sort on salary. Suppose if we need output based on name sorted then we need to un-comment "return obj1.getName().compareTo(obj2.getName());"



public class TreeMapUsingObjectSorting {
 
 public static void main(String a[]){
  TreeMap<Worker,String> map = new TreeMap<Worker, String>(new MyNameComp());
  map.put(new Worker("david",5000), "david");
  map.put(new Worker("joy",2000), "joy");
  map.put(new Worker("abel",7000), "abel");
  map.put(new Worker("ruby",9000), "ruby");
  
  for (Map.Entry<Worker, String> entry : map.entrySet()) {
   System.out.println("KEY : "+ entry.getKey() +" \t VALUE : "+entry.getValue());
  }
 }
}




public class Worker{
    
    private String name;
    private int salary;
    
    public Worker(String name, int salary){
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    /* Called by entry.getKey() 
       Overriding toString() method from super class Object
       Since key is Object we are return our own key value
    */
    public String toString(){
     //return super.toString();
     return "("+this.name+":"+this.salary+")";
    }
}




public class MyNameComp implements Comparator<Worker>{

 @Override
 public int compare(Worker obj1, Worker obj2) {
        
  // Sort TreeMap based on name
  //return obj1.getName().compareTo(obj2.getName());
  
  // Sort TreeMap based on salary
  if(obj1.getSalary() > obj2.getSalary()) return 1;
  else if(obj1.getSalary() < obj2.getSalary()) return -1;
  else return 0;
    } 
}

OUTPUT:


KEY : (joy:2000)   VALUE : joy
KEY : (david:5000)   VALUE : david
KEY : (abel:7000)   VALUE : abel
KEY : (ruby:9000)   VALUE : ruby









How to create Factory Design Pattern in Java

Already we have seen Fully Singleton Design Pattern in our earlier tutorial, now we will see about Factory Design Pattern. 

Factory design pattern is one is the most important and widely used pattern every where in Java. The factory method pattern defines an interface for creating an object, but let sub-classes decide which class to instantiate based on the user requirement. JDK and most of all frameworks like Spring, Struts etc uses factory design pattern internally. Also factory design pattern can be classified into various types like Static Factory, Service Locator Factory and Abstract Factory. 

Lets see one simple example as getting various Computer instances based on the used requirement. As we already explained above we need to have a interface for creating and Object but sub-classes will decide which class need to be instantiated  As same way we are going to have interface called "Computer" and sub-classes like "Desktop", "WorkStation", "Server", "Laptop" and "SuperComputer" will implement "Computer" interface and will their own method definitions. 



public interface Computer {
 public String myComputerType();
}


public class Desktop implements Computer {
 public String myComputerType() {
  return "You have requested for Desktop";
 }
}


public class WorkStation implements Computer {
 public String myComputerType() {
  return "You have requested for WorkStation";
 }
}


public class Server implements Computer {
 public String myComputerType() {
  return "You have requested for Server";
 }
}


public class Laptop implements Computer {
 public String myComputerType() {
  return "You have requested for Laptop";
 }
}


public class SuperComputer implements Computer {
 public String myComputerType() {
  return "You have requested for SuperComputer";
 }
}



public public class FactoryPattern {
 
 public static void main(String[] args) {

  // Based on user requirement we will get the Object
  
  Computer obj = FactoryPattern.getComputerType("desktop");
  if(obj != null) 
   System.out.println(obj.myComputerType());
  
  obj = FactoryPattern.getComputerType("laptop");
  if(obj != null) 
   System.out.println(obj.myComputerType());
  
  obj = FactoryPattern.getComputerType("server");
  if(obj != null) 
   System.out.println(obj.myComputerType());
 }
 
 public static Computer getComputerType(String val){
  if(val.equalsIgnoreCase("desktop")) return new PC();
  else if(val.equalsIgnoreCase("workstation")) return new WorkStation();
  else if(val.equalsIgnoreCase("server")) return new Server();
  else if(val.equalsIgnoreCase("laptop")) return new Laptop();
  else if(val.equalsIgnoreCase("super")) return new SuperComputer();
  return null;
 }
}



OUTPUT:


You have requested for Desktop
You have requested for Laptop
You have requested for Server









How to Override equals() and hashcode() methods in Java?

In this tutorial we will see how to Override equals() and hashcode() method in our code. First up all lets see what is equals and hashcode method.
  • equals() method indicates whether other Object is equal to same class Object. It will return boolean value as true when both Objects are equal and false when both Objects are not equals.
  • hashcode() method returns the hashcode of the Object passed and will be called automatically first whenever we use equals() method to compare 2 Objects. 
Lets see java examples for Overriding equals and hashcode method. In this example we will use HashMap to store "MyObject" class instance in key part. 

We all knows that HashMap won't allow duplicate key. In that case first example we will see about storing Object in key without Overriding equals() and hashcode() methods and second example by Overriding equals() and hashcode() methods.

Without overriding equals() and hashcode() methods


class MyObject{

 String val;
 
 public MyObject(String val) {
  this.val = val;
 } 
}




public class MyTest {
 
 public static void main(String[] args) {
  
  MyObject obj1 = new MyObject("sunday"); // 1st 
  MyObject obj2 = new MyObject("monday"); // 2nd 
  MyObject obj3 = new MyObject("sunday"); // 3rd
  
  HashMap<MyObject, String> hm = new HashMap<MyObject, String>();
  hm.put(obj1, "1");
  hm.put(obj2, "2");
  hm.put(obj3, "3");
  hm.put(obj1, "4");
  hm.put(obj1, "5");
  
  System.out.println("HASHMAP SIZE : "+hm.size());
 } 
}


OUTPUT:


HASHMAP SIZE : 3

3 instance we have created and stored in HashMap.


With overriding equals() and hashcode() methods
class MyObject{
 String val;
 public MyObject(String val) {
  this.val = val;
 } 
 
 @Override
 public boolean equals(Object obj) {
  return ((MyObject)obj).val.equals(this.val);
 }
 
 @Override
 public int hashCode() {
  
  /*We will return same hashcode as 0 for 
  all Object since its same class Object
  */
  return 0;
 }
}


OUTPUT:

HASHMAP SIZE : 2


Same MyTest class and MyObject class Overrides equals() and hashcode() methods. In equals method we have compared 2 Objects of "MyObject" class member variable "val" and returned true when 2 objects have same value "sunday". Hence we have only 2 elements in HashMap. 







What is the difference between final, finally and finalize in Java?

 
In this tutorial we will see about difference between final, finally and finalize in Java. 

final - final is a keyword in Java used to indicate whether variable, method or class can be a final. 
Once a variable set as final then the value can't be changed. 
Once a method set as final then the method can't be override d.
Once a class set as final then the class can't be inherited or extended by other classes.

finally - finally is block used in exception handling. Finally can be followed by try-catch or without catch block. But once we place a finally block then it will be executed always. 

finalize - finalize is a method and used in garbage collection. finalize() method will be invoked just before the Object is garbage collected. It will be called automatically by the JVM on the basis of resource reallocating.  Even programmers can call finalize method by using System.gc(); but vendor to vendor (Different OS) will change and not sure 100% finalize method will be called. 

Lets see small program for final, finally and finalize



Example for final:


// Final class
public final class FinalTest {
 
 // Final member variable
 private final int id = 100; 
 
 // Final method
 public final void getValue(){
  System.out.println("Inside final method");
 }
}




Example for finally:


public final class FinallyTest {
 
 public int getValue1(){
  try{
   return 10;
  }catch(NumberFormatException e){
   e.printStackTrace();
  }finally{
   return 20;
  }
 }
 
 public int getValue2(){
  try{
   return 100;
  }finally{
   return 200;
  }
 }
 
 public static void main(String[] args) {
  FinallyTest obj = new FinallyTest();
  
  int val1 = obj.getValue1();
  int val2 = obj.getValue2();
  
  System.out.println("VALUE-1 : "+val1);
  System.out.println("VALUE-2 : "+val2);
 }
}




Example for finalize:


public final class FinalizeTest {
 
 @Override
 protected void finalize() throws Throwable {
  System.out.println("Inside Finalize method");
  super.finalize();
 }
 
 public static void main(String[] args) {
  try{
   FinalizeTest obj = new FinalizeTest();
  }catch (Exception e) {
   e.printStackTrace();
  }
  System.gc();
 }
}









Difference between Iterator and Enumeration in Java?

In our last tutorial we have seen difference between Iterator and ListIterator. In this tutorial we will see about difference between Iterator and Enumeration in Java. Both Iterator and Enumeration are used to traverse elements in the Collection Object. Differences are,
  • Enumeration are introduced in older Java version and Iterator introduced in later version with additional features.
  • By Enumeration allows only traverse through elements, where as by Iterator we can traverse and also we can remove elements from the Collection Object.
  • Iterator is more secure and safe compared to Enumeration since its thread safe and won't allow others threads to modify the elements in Collection Object while some Thread is Iterating. On that case it will give ConcurrentModificationException

Finally we can decide if we are going for Read-only then we can for Enumeration else we can go for Iterator.

Mainly there are two types of Iterator in Java and they fail-fast and fail-safe Iterators. fail-fast iterators are those who throw ConcurrentModificationException if collection Object is modified when other Thread iterating on same Object. Fail-safe Iterator works on copying collection Object and won't work on original Object and its safe compared to fail-fast.    

Lets see example for both Iterator and Enumeration in Java



public class IteratorEnumerationTest {
 
 public static void main(String[] args) {
  
  ArrayList<String> myList = new ArrayList<String>();
  
  myList.add("one");
  myList.add("two");
  myList.add("three");
  myList.add("four");
  myList.add("five");
  
  Iterator<String> itr = myList.iterator();
  System.out.println("THROUGH ITERATOR : ");
  while(itr.hasNext()){
   System.out.print(itr.next()+", ");   
  }
  
  Vector<String> vec = new Vector<String>(myList);

  Enumeration<String> enu = vec.elements();
  
  System.out.println("\n\nTHROUGH ENUMERATION : ");
  while(enu.hasMoreElements()){
   System.out.print(enu.nextElement()+", ");
  }
 } 
}



OUTPUT:


THROUGH ITERATOR : 
one, two, three, four, five, 

THROUGH ENUMERATION : 
one, two, three, four, five, 










Difference between Iterator and ListIterator in Java?

In this tutorial we will see about difference between java.util.Iterator and java.util.ListIterator interfaces. Both interface are used to traverse values from the collection Object. But the differences are 

  • Iterator can traverse only in forward direction, where as ListIterator can traverse in both (bidirectional). 
  • Iterator can be used to traverse values in List and Set collections, where as ListIterator is used to traverse only in List.
  • ListIterator derived from Iterator interface and contains functions like remove(), previous(), next(), nextIndex(), previousIndex() etc.,


Lets see examples for both Iterator and ListIterator as how its used on Collection Object. 

Iterator Example:


public class IteratorTest {
 
 public static void main(String[] args) {
  List<String> myList = new ArrayList<String>();
  myList.add("java");
  myList.add("collections");
  myList.add("API");
  myList.add("important");
  myList.add("interview");
  myList.add("questions");
  
  System.out.println("LIST BEFORE REMOVE : "+myList);
  
  Iterator<String> itr = myList.iterator();
  while(itr.hasNext()){
   String val = itr.next();
   if(val.equals("API")){
    // Removing "API" value from ArrayList
    itr.remove();
   }   
  }  
  System.out.println("LIST AFTER REMOVE : "+myList);
 } 
}

OUTPUT:


LIST BEFORE REMOVE : [java, collections, API, important, interview, questions]
LIST AFTER REMOVE : [java, collections, important, interview, questions]


ListIterator Example:


public class ListIteratorTest {
 
 public static void main(String[] args) {
  List<String> myList = new ArrayList<String>();
  myList.add("java");
  myList.add("collections");
  myList.add("API");
  myList.add("important");
  myList.add("interview");
  myList.add("questions");
  
  System.out.println("LIST : "+myList);
  
  ListIterator<String> itr = myList.listIterator();
  while(itr.hasNext()){
   String val=itr.next();   
   if(val.equals("API")){
    // moving to previous element
    itr.previous();
    System.out.println("PREVIOUS VALUE : "+myList.get(itr.previousIndex()));
    // moving to forward element
    itr.next();
    System.out.println("NEXT VALUE     : "+myList.get(itr.nextIndex()));
   }
  }
 } 
}

OUTPUT:


LIST : [java, collections, API, important, interview, questions]
PREVIOUS VALUE : collections
NEXT VALUE     : important









How to Create User Defined Exception in Java?

In this tutorial we will discuss about how to create User Defined Exception in Java. Since already Java contains all pre-defined Exceptions and why we need to create User Defined Exceptions in our Application?
To Handle our application specific Exceptions can be placed under User Defined Exception. 

To create our own Exception class we need to extend Exception class in our class. By this all base class (Throwable) methods will be extended to our Exception class.

Methods from Throwable class are


String toString()
String getMessage()
void printStackTrace()   
String getLocalizedMessage()
Throwable fillInStackTrace()   
void printStackTrace(PrintStream stream)   


For example in our online portal application users age should not be less than 18 and should not be greater than 35. So as per their age we need to allow users to access the application. So here we can create our own Exception to handle the users age from 18 to 35. If users age not matches the condition then we need throw a Exception.
 

Lets see small example Java code as how to write User Defined Exception in Java.

public class MyException extends Exception{

 public MyException(){
  super();
 }
 public MyException(String expSrt){
  super(expSrt);
 }
 public String toString(){
  return "Exception: Age should be 18 to 35 years only";
 }
}



public class MyApplication {
 public static void main(String[] args) {
  int age = 15;
  try{
   if(age < 18 || age > 35){
    throw new MyException(); // Line 8
   }else{
    System.out.println("Valid to access the application");
   }
  }catch (Exception e) {
   e.printStackTrace();
  } 
  
 }
}


OUTPUT:


Exception: Age should be 18 to 35 years only
 at com.test.MyApplication.main(MyApplication.java:8)


By above way we can define our own Exceptions for our application needs.