Wednesday, March 10, 2021

Java Interview Questions

 1. Fail Fast and Fail-Safe

      Ans- Fail Fast- iterator over-collection and removing the element from the collection.

       fail-safe is a concurrent package because use a copy of the collection


2. Why use generics

Ans- In Generics Type parameters provide a way for you to re-use the same code with different inputs


3. Comparable and Comparator

Comparable

Comparator

1) Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price.

The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.

2) Comparable affects the original class, i.e., the actual class is modified.

Comparator doesn't affect the original class, i.e., the actual class is not modified.

3) Comparable provides compareTo() method to sort elements.

Comparator provides compare() method to sort elements.

4) Comparable is present in java.lang package.

A Comparator is present in the java.util package.

5) We can sort the list elements of Comparable type by Collections.sort(List) method.

We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.

*image source- https://www.javatpoint.com/difference-between-comparable-and-comparator