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.






How to convert HashMap to Synchronized Map ?

In this tutorial we will see about how to convert HashMap to synchronized Map. As we know already that HashMap is not synchronized by default.

Synchronize is nothing but making the HashMap to thread safe and by multi-threading environment only one user can remove or edit the Map values. For example if we are using HashMap only for read operation then making synchronized Map is not necessary. Only when multi users or more threads tries to update or remove same key or value from HashMap then we need to make HashMap synchronized for thread safe purpose.

In Java we can do this very easily by using java.util.Collections class as like give below.



Map<String, Object> myMap = new HashMap<String, Object>();
.
.
.  
.
myMap = Collections.synchronizedMap(myMap);


From above code snippet we have declared myMap as HashMap and later in below code we have converted same HashMap instance to synchronized Map. Since this is a simple interview question which asked in 2 to 3 yrs experience level. Hope you are clear now how to convert HashMap to synchronized Map.

Above we have seen how to convert HashMap to SynchronizedMap. Even by converting SynchronizedMap its not guarantee that values will be thread safe we are editing or removing on same Object using multiple Thread. As per  Collections#synchronizedMap() in Oracle docs we need to make operations on Map with synchronized block as mentioned in Oracle docs.  

Lets see all scenarios with details example of 

  1. Accessing updated HashMap without converting to SynchronizedMap under Multi Threading.
  2. Accessing updated HashMap just converting to SynchronizedMap under Multi Threading.
  3. Accessing updated HashMap with converted to SynchronizedMap & Synchronized block under Multi Threading.

Example - 1 : Accessing updated HashMap without converting to SynchronizedMap under Multi Threading.


public class HashMapTest implements Runnable{
 
 // Initializing new HashMap
 private Map<String, String> myMap = new HashMap<String, String>();
 
 public void run() {
  String threadName = Thread.currentThread().getName();
  String oldValue = myMap.get("myKey");
  String newValue = oldValue+threadName;
  myMap.put("myKey", newValue);
  System.out.println(threadName+" : "+myMap.get("myKey"));
 }
 
 public static void main(String[] args) {
  HashMapTest obj = new HashMapTest();
  
  // Adding values into HashMap
  obj.addValues();
  
  // Creating multiple Thread and starting
  for(int i=0;i<5;i++){
   new Thread(obj).start();
  }
  
 }
 public void addValues(){
  myMap.put("myKey", "Java Discover - ");
 }
}


OUTPUT:


Thread-0 : Java Discover - Thread-3
Thread-1 : Java Discover - Thread-3
Thread-2 : Java Discover - Thread-3
Thread-3 : Java Discover - Thread-3
Thread-4 : Java Discover - Thread-3




In above example we have placed 1 value in HashMap and in run() method we trying to upend Thread name to existing value. Each thread names need to be upended in the value, where as we can see only Thread-3 has upended with original value. Remaining 4 Thread names are not updated correctly. Next example lets see just by converting HashMap to SynchronizedMap.



Example - 2 : Accessing updated HashMap just converting to SynchronizedMap under Multi Threading.


public class HashMapTest implements Runnable{
 
 // Initializing new HashMap
 private Map<String, String> myMap = new HashMap<String, String>();
 
 public void run() {
  String threadName = Thread.currentThread().getName();
  String oldValue = myMap.get("myKey");
  String newValue = oldValue+threadName;
  myMap.put("myKey", newValue);
  System.out.println(threadName+" : "+myMap.get("myKey"));
 }
 
 public static void main(String[] args) {
  HashMapTest obj = new HashMapTest();
  
  // Adding values into HashMap
  obj.addValues();
  
  // Converting HashMap to Synchronized Map 
  obj.convertMapToSynMap();
  
  // Creating multiple Thread and starting
  for(int i=0;i<5;i++){
   new Thread(obj).start();
  }
  
 }
 public void convertMapToSynMap(){
  myMap = Collections.synchronizedMap(myMap);
 }
 public void addValues(){
  myMap.put("myKey", "Java Discover - ");
 }
}


OUTPUT:


Thread-0 : Java Discover - Thread-1
Thread-1 : Java Discover - Thread-1
Thread-2 : Java Discover - Thread-1Thread-2
Thread-3 : Java Discover - Thread-1Thread-2Thread-3
Thread-4 : Java Discover - Thread-1Thread-2Thread-3Thread-4



Even by making SynchronizedMap we are getting wrong output when mutiple thread trying to update same Map key value. In above code we can see Thread-0 is missing. Next lets see how to thread safe when we edit under multi threading on same object. 

Example - 3 : Accessing updated HashMap with converted to SynchronizedMap & Synchronized block under Multi Threading.


public class HashMapTest implements Runnable{
 
 // Initializing new HashMap
 private Map<String, String> myMap = new HashMap<String, String>();
 
 public void run() {
  String threadName = Thread.currentThread().getName();
  // Synchronized block 
  synchronized (myMap) {
   String oldValue = myMap.get("myKey");
   String newValue = oldValue+threadName;
   myMap.put("myKey", newValue);
  }  
  System.out.println(threadName+" : "+myMap.get("myKey"));
 }
 
 public static void main(String[] args) {
  HashMapTest obj = new HashMapTest();
  
  // Adding values into HashMap
  obj.addValues();
  
  // Converting HashMap to Synchronized Map 
  obj.convertMapToSynMap();
  
  // Creating multiple Thread and starting
  for(int i=0;i<5;i++){
   new Thread(obj).start();
  }
  
 }
 public void convertMapToSynMap(){
  myMap = Collections.synchronizedMap(myMap);
 }
 public void addValues(){
  myMap.put("myKey", "Java Discover - ");
 }
}

OUTPUT:


Thread-0 : Java Discover - Thread-0Thread-1
Thread-1 : Java Discover - Thread-0Thread-1
Thread-2 : Java Discover - Thread-0Thread-1Thread-2Thread-3
Thread-3 : Java Discover - Thread-0Thread-1Thread-2Thread-3
Thread-4 : Java Discover - Thread-0Thread-1Thread-2Thread-3Thread-4

Now we see all Thread names are upended correctly from 0 to 5. Order doesn't matter since Thread will called according priority. 









How to Create, Write/Append, Read, Delete and Rename a file in Java?

 


We can see in all applications and programs we may need to write or edit file. File operations like creating, deleting, append etc., So in this tutorial we will see about Create, Write, Read and Delete a file using Java code. Each file operations we will discuss with separate program and lets see the output. 
NOTE: File name, path and folder names can vary accordingly. 


1. How to create a file in Java?


public class CreateFile {
    public static void main(String[] args) {
        File myFile = new File("javadiscover.txt");
        try{
        if(!(myFile.exists())){ // checking file exist or not
            myFile.createNewFile(); // Creating new file
            System.out.println("New File created....");
        }else{
            System.out.println("File already exisit....");
        }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}



OUTPUT:


New File created....




2. How to Write/ Append a text into a file in Java ?

public class WriteFile {
    public static void main(String[] args) {
        
        FileWriter fWrite = null;
        BufferedWriter bWrite = null;
        
        String content = "Hi All, Welcome to Java Discover";
        File myFile = new File("javadiscover.txt");
        
        try{
            if(!(myFile.exists())){
                myFile.createNewFile();
        }
        fWrite = new FileWriter(myFile, true); // true for appending content to the existing file
            bWrite = new BufferedWriter(fWrite);
            bWrite.write(content);
            bWrite.close();
            
            System.out.println("File write complete.....");
            
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fWrite != null
                try { fWrite.close(); } catch (IOException e) { e.printStackTrace(); }
            if(bWrite != null
                try { bWrite.close(); } catch (IOException e) { e.printStackTrace(); }            
        }
    }
}



OUTPUT:

Console

File write complete.....


File


3. How to read a file in Java ?


public class ReadFile {
    public static void main(String[] args) {
        BufferedReader br = null;
        try{
            FileReader myFile  = new FileReader("javadiscover.txt");
            br = new BufferedReader(myFile);
            String line = null
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(br != null
                try{ br.close(); }catch(IOException e){e.printStackTrace();}
        }        
    }
}


OUTPUT:


Hi All, Welcome to Java Discover
Blog about Java questions and answers


4. How to delete a file in Java ?



public class DeleteFile {
    public static void main(String[] args) {
        try{
            File myFile = new File("javadiscover.txt");
            if(myFile.exists()){
                myFile.delete();
                System.out.println("File deleted successfully....");
            }else{
                System.out.println("File NOT Exisit....");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}



OUTPUT:


File deleted successfully....





5. How to rename a file in Java ?

public class RenameFile {
    public static void main(String[] args) {
        File oriFile = new File("java.txt");
        File newFile = new File("javadiscover.txt");
        if(oriFile.exists()){
            oriFile.renameTo(newFile);
            System.out.println("File rename completed....");
        }else{
            System.out.println("Original file not exist for renaming....");
        }
    }
}



OUTPUT:


File rename completed....





Apart from these examples various file operations which you can refer to Oracle docs.