Sunday, 20 October 2019

Difference between fail-safe and fail-fast iterator in Java

        In the current interview topic, we will discuss the difference between fail safe and fail fast iterators in Java. Basically this question is related to ConcurrentModificationException, means what are the scenario to throw this exception. The above iterator one it will throw exception and another one doesn't throw, this is the main difference. We can discuss few more differences and with examples as follows

Related topicDifference between HashSet and TreeSet in Java

Difference between fail-fast and fail-safe iterator:-
diff. between fail-fast and fail-safe
Difference between fail-fast and fail-safe iterator

Example of fail-fast iterator:-

         As we see the difference between fail-fast and fail-safe in the diagram, the mainly difference is to throw the ConcurrentModificationException. In any type of Collection, internally it will use an array of objects to store the elements. While iterating the collection, we can not modify the existing array. Internally collection will use flag to indicate whether the given collection is modified or not. Based on this flag it will throw the exception if flag is true.

FailFastIteratorExample.java,
package com.example.demo;

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

public class FailFastIteratorExample {

        public static void main(String[] args) {

                List<String> list = new ArrayList<String>();
                list.add("A");
                list.add("B");

                Iterator<String> iterator = list.iterator();

                while (iterator.hasNext()) {
                        iterator.next();
                        list.add("C");
                }
        }

}

Output:-
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at com.example.demo.FailFastIteratorExample.main(FailFastIteratorExample.java:17)


Example Of fail-safe iterator:-

           The fail-safe iterator doesn't throw any exception if the collection is modified while iterating over it. Internally it will copy the original collection object, and iterate over the copied collection object. Due to this internal behavior, if any modification done on collection, it doesn't impact on iterator.

FailSafeIteratorExample.java,
package com.example.demo;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class FailSafeIteratorExample {

        public static void main(String[] args) {

               List<String> list = new CopyOnWriteArrayList<String>();
               list.add("A");
               list.add("B");

               Iterator<String> iterator = list.iterator();

               while (iterator.hasNext()) {
                       iterator.next();
                       list.add("C");
               }

               list.forEach(str -> System.out.println(str));

       }

}

Output:-
A
B
C
C

Related Posts:-
1) Collection Hierarchy in Java
2) Collection Interview Questions and Answers in Java(List,Map & Set)
3) How to iterate the TreeMap in reverse order in Java
4) How to Remove duplicates from ArrayList in Java
5) Internal Implementation of TreeMap in Java
6) Internal implementation of ArrayList in Java
7) Internal Implementation of LinkedList in Java
8) Difference between HashSet and TreeSet in Java

Wednesday, 9 October 2019

UnsupportedOperationException when adding or removing element to a Collection in java

        In earlier article, we discussed the difference between HashSet and TreeSet and also covered sample example of TreeSet and HashSet.  In the current article, we will see one of important exception in collection i.e UnsupportedOperationException.


What is UnsupportedOperationException in collection?

       The name itself suggests provided operation can not be  supported i.e when you try to perform some operation on collection where it's not allowed and will throw UnsupportedOperationException. The UnsupportedOperationException is thrown at run time so it's RuntimeException i.e Unchecked Exception.

Throwable -> Exception -> RuntimeException -> UnsupportedOperationException


Scenario to throw UnsupportedOperationException:-

1) Update on list of Arrays.asList() 

      As we know that, Converting from Array to List we will use asList() method of Arrays(java.util.Arrays) class.  When you convert array to list using asList method, and try to add an element to a list then will throw UnsupportedOperationException as shown below code.

UnsupportedOpExceptionExample.java,
package com.example.demo;

import java.util.Arrays;
import java.util.List;

public class UnsupportedOpExceptionExample {

        public static void main(String[] args) {

                String[] arrayStr = { "Mechanical", "Computer Science" };
                List<String> list = Arrays.asList(arrayStr);
                list.add("ECE");

         }

}

Output:-
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at com.example.demo.UnsupportedOpExceptionExample.main(UnsupportedOpExceptionExample.java:12)


Solution:-

Pass Arrays.asList to the List constructor, so that will act as new ArrayList object, then you can modify the list without any exception.

UnsupportedOpExceptionExample.java
package com.example.demo;

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

public class UnsupportedOpExceptionExample {

       public static void main(String[] args) {

              String[] arrayStr = { "Mechanical", "Computer Science" };
              List<String> list = new ArrayList<String>(Arrays.asList(arrayStr));
              list.add("ECE");

              list.stream().forEach(str -> System.out.println(str));
       }
}

Output:-
Mechanical
Computer Science
ECE


2) Update on Unmodifiable collection

       You can create any Unmodifiable collection class using Collections.unmodifiableCollection (Collection obj) method. When you create unmodifiable collection, you can not modify i.e it's read only access. If you try to update on Unmodifiable collection, it will throw RuntimeException i.e UnsupportedOperationException.

  Sample java code to throw UnsupportedOperationException when try to update Unmodifiable collection,

UnsupportedOpExceptionExample.java
package com.example.demo;

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

public class UnsupportedOpExceptionExample {

        public static void main(String[] args) {

               List<String> list = new ArrayList<String>();
               list.add("Mechanical");
               list.add("ECE");
               Collection<String> strList = Collections.unmodifiableCollection(list);
               strList.add("CS");

               list.stream().forEach(str -> System.out.println(str));
        }

}

Output:-
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source) at com.example.demo.UnsupportedOpExceptionExample.main(UnsupportedOpExceptionExample.java:16)

   If really you are not doing any update on collection then use this method, otherwise don't use.

Thank you for visiting blog....

Related Posts:--
2) Collection Interview Questions and Answers in Java(List,Map & Set)
3) How to iterate the TreeMap in reverse order in Java
4) How to Remove duplicates from ArrayList in Java
5) Internal Implementation of TreeMap in Java
6) Internal implementation of ArrayList in Java
7) Internal Implementation of LinkedList in Java

8) Difference between HashSet and TreeSet in Java

Sunday, 6 October 2019

Why TreeSet does not allow null value in Java?

           TreeSet implements Set interface and maintains unique elements which means it doesn't allow duplicates. The elements in the TreeSet are sorted and in ascending order. In this post, we will discuss about why TreeSet doesn't allow to add null value ?

Example to add null value to TreeSet:--

TreeSetExample.java

package com.example.demo;

import java.util.TreeSet;

public class TreeSetExample {

         public static void main(String[] args) {

                 TreeSet<String> treeSet = new TreeSet<String>();
                  treeSet.add(null);

         }

}

Output:-
Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at com.example.demo.TreeSetExample.main(TreeSetExample.java:10)


Why TreeSet doesn't allow to add null value ?

TreeSet internally used Comparable interface to sort the elements in ascending order. In Comparable interface there is method called compareTo() used to compare one value with other to sort the elements. So null doesn't have any value because of this reason compareTo() method can not compare null with other value, giving NullPointerException.

add method declaration :-


public boolean add(E e) throws ClassCastException, NullPointerExeption;


Java 1.6 and earlier versions, TreeSet allow to add first element as null. From 1.7 onwards null is not accepted at all.


Related Posts:--
1) Collection Hierarchy in Java
2) Collection Interview Questions and Answers in Java(List,Map & Set)
3) How to iterate the TreeMap in reverse order in Java
4) How to Remove duplicates from ArrayList in Java
5) Internal Implementation of TreeMap in Java
6) Internal implementation of ArrayList in Java
7) Internal Implementation of LinkedList in Java

8) Difference between HashSet and TreeSet in Java

Saturday, 5 October 2019

Difference between HashSet and TreeSet in Java

        In the current post, we will see what are the differences between HashSet and TreeSet in Java. Both TreeSet and HashSet implements Set interface and doesn't contain duplicates.

Difference between HashSet and TreeSet:-

1) HashSet gives better performance compared to TreeSet for the operations like add, remove, contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations.

2) HashSet is implemented based on HashTable while TreeSet is implemented based on TreeMap. As we know that TreeMap uses a Red-Black algorithm to sort the elements.

3) HashSet does not maintain any order of elements while TreeSet elements are sorted by ascending order by default. Both HashSet and TreeSet doesn't contain duplicate elements.

4) HashSet allows null values but TreeSet doesn’t allow null values. If try to add null value in TreeSet will throw NullPointerException, because internally TreeSet uses compareTo() method to compare keys and compareTo() will throw NullPointerException.

     Use TreeSet if you need the inserted elements in sorted ascending order but performance wise HashSet is better.

HashSet and TreeSet examples:--

HashSetTreeSetExample.java
package com.example.demo;

import java.util.HashSet;
import java.util.TreeSet;

public class HashSetTreeSetExample {

       public static void main(String[] args) {

               HashSet<String> hashSet = new HashSet<String>();
               hashSet.add("Java");
               hashSet.add(".Net");
               hashSet.add("PHP");
               hashSet.add("Embedded C");

               System.out.println("HashSet elements are,");
               hashSet.stream().forEach(System.out::println);

               TreeSet<String> treeSet = new TreeSet<String>();
               treeSet.add("Java");
               treeSet.add(".Net");
               treeSet.add("PHP");
               treeSet.add("Embedded C");

               System.out.println("TreeSet elements are,");
               treeSet.stream().forEach(System.out::println);
       }
}

Output:--
HashSet elements are,
Java
Embedded C
.Net
PHP

TreeSet elements are,
.Net
Embedded C
Java
PHP


Related Posts:--
1) Collection Hierarchy in Java
2) Collection Interview Questions and Answers in Java(List,Map & Set)
3) How to iterate the TreeMap in reverse order in Java
4) How to Remove duplicates from ArrayList in Java
5) Internal Implementation of TreeMap in Java
6) Internal implementation of ArrayList in Java
7) Internal Implementation of LinkedList in Java

Thursday, 3 October 2019

Collection Hierarchy in Java

           A Collection is a group of objects represented as a single unit and which defines several classes and interfaces. Collection framework is very important topic for java interview questions, you can read usage, difference and advantages of all interfaces and classes .

In the current post, we will discuss collection hierarchy.

      All classes and interfaces related to Collection Framework are in java.util package. Collection interface is at the top of class hierarchy of Collection Framework as shown in below diagram.

Below diagram shows the class hierarchy of collection framework.
Collection Hierarchy in Java
Collection Hierarchy in Java

        The Collection Framework is divided into four interfaces(three interfaces inherits Collection interface, but map interface is not inherits Collection interface, this is a separate interface ).

  •  List 
      ArrayList, Vector and LinkedList classes implement this interface. It contains duplicates.

  • Queue
      It handles the special group of objects in which elements are removed only from the head. LinkedList and PriorityQueue classes implement this interface.

  • Set
      HashSet and LinkedHashSet classes implements Set interface and TreeSet class implements SortedSet interface which in turn, is extends Set interface. It doesn't contain duplicates.

  • Map
       This is the one interface in Collection Framework which is not inherited from Collection interface. It handles the group of objects as Key/Value pairs. It is implemented by HashMap and HashTable classes and extended by SortedMap interface which in turn is implemented by TreeMap.


Related Posts:--
1) Collection Interview Questions and Answers in Java
2) How to iterate the TreeMap in reverse order in Java
3) How to Remove duplicates from ArrayList in Java
4) Internal Implementation of TreeMap in Java
5) Internal implementation of ArrayList in Java
6) Internal Implementation of LinkedList in Java

Monday, 30 September 2019

How to Push an Existing Project to GitHub

         In daily basis developer work is to do code check in, check out, pull, fetch and so on. But in the current post, we will learn how to push the existing local project to GitHub 
repository.

For example:- I have a project EmployeeManagement(EMS) in my local but no one can able to access or modify code without creating and pushing code to GitHub repository.

The steps to push local project to GitHub repository as follows,

1) Create a repository on GitHub.

Create a GitHub account if you don't have.
Then Go to Account --> Your  repositories 
Click on New as shown in below screenshot. 
GitHub New Repo
Github New Repo Creation








When click on New button, will open Create New Repository page.
Create Repository
Create Repository

Provide repository name(Usually project name)

Select public or private repository option

     To avoid errors, do not initialize the new repository with README, 
license, or gitignore files. You can add these files after your project has been pushed to GitHub.
Click on Button/action ""Create repository"

2) Initialize the local directory as a Git repository.

    Change the current working directory to your local project and then initialize the local directory as a git repository using command "git init"

e.g your project directory is C:\\ProjectRepo\EMS
then 


C:\ProjectRepo\EMS>git init


3) Add the files in your new local repository(using git add command). This stages them for the first commit.

Add files to the GitHub,


C:\ProjectRepo\EMS>git add .



If you want to add each file, then use git add "file path" 


C:\ProjectRepo\EMS>git add "file path to add to git"


# Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.


4) Commit the files that you've staged in your local repository.

Use command -  git commit -m "First commit" to commit the added file to gitHub.


C:\ProjectRepo\EMS>git commit -m "First commit"


5) At the top of your GitHub repository's Quick Setup page, click  to copy the remote repository URL.

Copy below HTTPS or SSH Project URL

Remote Repo HTTPS o SSH URL
         In the Command prompt, add the URL for the remote repository where your local repository will be pushed.
>git remote add origin "remote repository URL"



C:\ProjectRepo\EMS>git remote add origin "remote repo HTTPS or SSH URL"


6) Push the changes in your local repository to GitHub.

 Using git push command, you can the committed files to the remote repository as follow,


C:\ProjectRepo\EMS>git push origin master


master - is the branch name.


Related Post:--
Permission denied(publickey), fatal:couldn't read from remote repository - Gihub Error

Saturday, 28 September 2019

Java Program to Perform Matrix Addition and Subtraction

          In the previous post, written code for matrix transpose. In the current post, I have written a java program to perform a simple matrix addition and subtraction. 

Below is the source code of the Java Program to Perform Matrix Multiplication,

MatrixAdditionSubtraction.java,

package com.example.demo;

public class MatrixAdditionSubtraction {

        public static void main(String[] args) {

                int[][] a = { { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
                int[][] b = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

                int rows = 3;
                int columns = 3;

                int[][] c = new int[rows][columns];

                for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < columns; j++) {
                              c[i][j] = a[i][j] + b[i][j];
                       }
                }

                System.out.println("The sum of the two matrices is");

                for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < columns; j++) {
                              System.out.print(c[i][j] + " ");
                       }
                       System.out.println();
                }

                for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < columns; j++) {
                               c[i][j] = a[i][j] - b[i][j];
                       }
                }

                System.out.println("The subtraction of the two matrices is");

                for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < columns; j++) {
                              System.out.print(c[i][j] + " ");
                       }
                       System.out.println();
                }

        }
}

Output:--
The sum of the two matrices is
5 7 9 
11 13 15 
17 19 21 
The subtraction of the two matrices is
3 3 3 
3 3 3 
3 3 3 

Related Posts:--
1) Java code to move all zero of an integer array to the end of the array
2) Java Program to Perform Matrix Multiplication
3) Write a Java program to print the Floyd's triangle
4) Java Code to Print the Numbers as Pyramid - Examples
5) Java Program to find the Missing Number in an Array
6) Java program to print the first n prime numbers
7) Swap two variables without using third variable in Java
8) Java program to find second largest number in an array
9) Sort a binary array using one traversal in Java
10) Difference between NoClassDefFoundError and ClassNotFoundException in Java