Tuesday 25 January 2022

Collection Classes and Interfaces in Java

Collection is an interface with generic methods like add, remove etc. Collection classes are iterable. Core interfaces of Collection framework are as follows:

1)List   2)Set  3)Queue

Map interface is not part of collection framework.Also map is not iterable.


Monday 24 January 2022

ClassNotFoundException Vs NoClassDefFoundError

 ClassNotFoundException : This is checked exception and occurs when class is not found at runtime.The reason for this could be classpath is not updated with required jars. 

// Java Program to Illustrate ClassNotFoundException

public class Demo {


// Main driver method

public static void main(String args[])

{


// Try block to check for exceptions

try {


Class.forName("ApachePOI");

}


// Catch block to handle exceptions

catch (ClassNotFoundException ex) {


// Displaying exceptions on console along with

// line number using printStackTrace() method

ex.printStackTrace();

}

}

}


NoClassDefFoundError: This is unchecked exception and occurs when class was present during compile time but absent during runtime. This generally happens when no .class file is present at runtime.This is kind of LinkageError.


Comparable and Comparator Interface

 Comparable interface is used to sort or order the elements on the basis of single field. Using this we can only sort using single field. Comparable interface is present in java.lang.comparable package.

package java.lang;

public interface Comparable<T> {
int compareTo(T var1);
}

Comparator interface is used to sort or order the elements on the basis of multiple fields. Using this we can create different comparator and sort elements on the basis of different fields. Comparator interface is present in java.util package.

package java.util;

import java.io.Serializable;
import java.util.Comparators.NaturalOrderComparator;
import java.util.Comparators.NullComparator;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;

@FunctionalInterface
public interface Comparator<T> {
int compare(T var1, T var2);

boolean equals(Object var1);

Observe that Comparator is marked functional interface . It may be because all classes which implement Comparator interface  by default will have equals implementation from default super class (Object).

Checked and Unchecked Exception

 Checked Exceptions are those which are checked by compiler during compile time only. These need to handled either by try catch block or by throwing the exception. Examples of same are ::

    ClassNotFoundException, InterruptedException, InstantiationException, IOException, 

    SQLException, IllegalAccessException, FileNotFoundException,CloneNotSupportedException.

All exceptions except RunTimeException and Error are checked Exception.

In case of checked exception Compiler  reports unhandled exception FileNotFoundException or must be caught or declared to be thrown during compiletime.

Unchecked Exceptions are those which are not checked by compiler and occurs due to error in programming logic.  Examples ClassCastException extends RunTimeException, ClassGenException extends RunTimeException ,ArithmeticException,IndexOutOfBoundsException extends RunTimeException, ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException, ConcurrentModification Exception, NumberFormatException.

All exceptions under (RuntimeException and Error ) are unchecked Exception.

     

Exception hierarchy

                                                            Object

                                                                 |

                                                           Throwable

                                                                 |

           Exceptions                                                                               Error

                 |                                                                                             |

I/O.    Runtime    CloneNotSupported.                           Linkage       Assertion    VirtualMachineError 

SOLID principle

 S: S stands for single responsibility principle.Each class is responsible for single responsibility.

 O: Class shall be open for extension but closed for modification.

 L: L stands for Liskov substitution.This means that objects of superclass shall be replaced with objects        of  subclasses without breaking the system.

 I: I stands for Interface segregation Principle. This means that Interface shall not have unnecessary             methods which need to be implemented by client forcefully. So if there are methods which are not         always required by clients so better would be to keep them in separate interface and the clients which         want those can override those methods by implementing different interface.

   

D: D stands for dependency inversion principle.It states that class shall depend on abstract                            reference(abstract class or interface) rather than concrete implementation(class) . Here , inversion      refers to the dependent classes on which another class depends. In simple terms we shall use abstract          classes or interface as dependency to one class not concrete classes.

     For eg

      Class Car{

      Engine engine// This Engine either has to be abstract class or interface.

         } 

Monday 10 January 2022

Generics in Java

Generics means parameterised types. With the help of parameterised types we can create classes, interfaces or methods in such a way that the type of the data on which they operate can be passed as a parameter.

Generic only works with object. 

Main advantage of generic

  a)Generic provide Type Safety :: This means that error can be detected during compile time only instead of runtime .

  b)Generic provide Code Reusability :: Since with generic we just need to create class once and we can use it for any type .

 c)Type casting is not needed.

 d)Helpful for making generic implementation.

 Generic class creation: It is very similar to normal class except that the declaration is followed by type parameter with diamond bracket.

     Class Dao<T>{//T is generic type parameter

      private  T t; //instance of generic type

      } 

     

   Class Matrix<T,S>{

     private T t;

     private S r;

      }


By convention ,type parameter are named as single uppercase letter. Commonly used Type parameter are:

      * T    :   First typed parameter

      * S.   :   Second type parameter

      * U   :   Third type parameter

      * V   :   Fourth type parameter

      * K   :   Key type parameter


Bounded Type:: 

        Bounded type is used to restrict type to a specific type or its subtype. In short in many cases we want the type to be restricted to specific types like  in case of sum we want that type should be restricted to Number or its type then in that scenario we can use Bounded type.


Bounded types are divided on 3 types based on wildcard:

1)Upper Bound Type :: This is implemented using ?(unknown type) wildcard followed by extends keyword and used to relax the restriction on any type which means we can pass any type which extends Type T.

     public void  addNumsDifferentTypes(List<? extends Number> list>{

}


2)Lower Bounded Type :: This is implemented using ? (unknown type) followed by super keyword and used to allow specific type passed in parameters. This means we can pass only pass or return type of specific type or it super type while using it. 


     public void passOnlyIntegerOrNumber(List<? super  Integer> list){}


3)Unbounded Type:: This is implemented using ? (unknown type) and is used to allow pass or return any type.

    public void printList(List <?> list){}