Wednesday, 16 March 2022

Friday, 11 February 2022

Different services running on MAC or not.

 Check below services are running or not on MAC.

 1)Mongodb

      ps -ef | grep mongod | grep -v grep | wc -l | tr -d ' '

This will get you the number of MongoDB processes running, thus if it is other than 0, then you have MongoDB running on your system.

2)Elasticsearch 



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. It means if we are getting new type or behaviour changes we should not do the changes on same class instead shall extend those to new classes. And have strategy interface which will pull concrete implementation depending upon need.


 This way we can achieve separation on concerns, existing  tested code does not have any issues.


Like we have discount that need to be offered to customer class.

Now depending upon customer we have to provide discount.

Bad approach will be 

 get discount( String customer type) {

  If (type.equals("vip"){

 }else (type.equals("premium"){

}


Now in future if more type introduced don't modify existing class instead create 2 separate implementation from day one so that they have their own responsibility.



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

     Let say we have Bird as super class and has fly() method and penguin and sparrow as sub class but in penguin we have thrown exception saying it does not fly. This is violation of Liskov substitution principle becoz 

    We can't assign 

         Bird b = new Penguin()

       Becoz b.fly() will not work as expected.

How to resolve this?

    Create subclasses from Bird and only keep those functionality which will be common to all birds at top level . Down the line can add new classes which have different nature .

 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.

         }