Wednesday, 27 September 2017

JAVA : Difference between JDK,JRE and JVM

JAVA : Difference between JDK,JRE and JVM










JAVA : How Class Loader works

JAVA : How Class Loader works







JAVA : Locks in Java

JAVA : ClassNotFoundException vs. NoClassDefFoundError

JAVA : ClassNotFoundException vs. NoClassDefFoundError



ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime. However, they occur at different scenarios.

ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath.

NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.

ClassNotFoundException



For example, the below program will throw ClassNotFoundException if the mentioned class “oracle.jdbc.driver.OracleDriver” is not found in the classpath.
public class MainClass
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }
}



java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

NoClassDefFoundError

class A
{
  // some code
}
public class B
{
    public static void main(String[] args)
    {
        A a = new A();
    }
}

When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:
Exception in thread "main" java.lang.NoClassDefFoundError: A


OR 

java TestTestTest
-> if TestTestTest.class is not there then also we get.


JAVA : Comparable vs Comparator

JAVA : Comparable vs Comparator

#########################  Shortcut rememberance  ################################################
Comparable - compareTo(o)  - API person or who develop the object will write, 
JVM will call internally when treeSet.add(o) does, 
Dont pass any thing in Constructor, so that JVM will call compareTo(o) method.
Comparator - compare(o1,o2) - equals() - Who uses API class or developed class will write
JVM will call internally when treeSet.add(o) does.
Pass MyComparator object in constructor, so that JVM will call compare(o1,o2) method.

#########################################################################




Comparable


- When default sorting is needed, means JVM will call automatically when we try to add objects to TreeSet, that is with default constructor.

- The person who develops the class is responsible to implement Comparable and write logic inside compareTo() method.
Eg: Person1 develops Employee class, so he is responsible to write compareTo().


Comparator


- When we want customized sorting based on our logic, then just pass MyComparator class in the constructor, so that JVM will not call compareTo method instead it calls our compare() method which is inside MyComparator class.

- need to pass MyComparator class in constructor - so that JVM will understand to call compare()

- The person who uses the class can write his own MyComparator and implement inside compare().
Eg : Person2 is using Employee class developed by Person1, so Person2 can write MyComparator and compare() to change the sorting order.







Comparable Example

public class Employee implements Comparable<Employee> {

    private int id;
    private String name;
    private int age;
    private long salary;

//getter and setter......

    @Override
    public int compareTo(Employee emp) {
        return (this.id - emp.id);
    }

}
In Main method 
Employee[] empArr = new Employee[4];                           empArr[0] = new Employee(10, "Mikey", 25, 10000);
empArr[1] = new Employee(20, "Arun", 29, 20000);
empArr[2] = new Employee(5, "Lisa", 35, 5000);
empArr[3] = new Employee(1, "Pankaj", 32, 50000);

//sorting employees array using Comparable interface implementation
Arrays.sort(empArr);

Comparator Example

class HDTV implements Comparator{
 private int size;
 private String brand;
 
 public HDTV(int size, String brand) {
  this.size = size;
  this.brand = brand;
 }
 
 public int getSize() {
  return size;
 }
 
 public void setSize(int size) {
  this.size = size;
 }
 
 public String getBrand() {
  return brand;
 }
 
 public void setBrand(String brand) {
  this.brand = brand;
 }
}

@Override
 public int compare(HDTV tv1, HDTV tv2) {
  int tv1Size = tv1.getSize();
  int tv2Size = tv2.getSize();
 
  if (tv1Size > tv2Size) {
   return 1;
  } else if (tv1Size < tv2Size) {
   return -1;
  } else {
   return 0;
  }
 }
In Main method  
                                                                  
HDTV tv1 = new HDTV(55, "Samsung");
  HDTV tv2 = new HDTV(60, "Sony");
  HDTV tv3 = new HDTV(42, "Panasonic");
 
  ArrayList<HDTV> al = new ArrayList<HDTV>();
  al.add(tv1);
  al.add(tv2);
  al.add(tv3);
Collection.sort(al, HDTV);
OR
public class Employee implements Comparator {

    private int id;
    private String name;
    private int age;
    private long salary;

/**
     * Comparator to sort employees list or array in order of Salary
     */
    public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return (int) (e1.getSalary() - e2.getSalary());
        }
    };
    /**
     * Comparator to sort employees list or array in order of Age
     */
    public static Comparator<Employee> AgeComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return e1.getAge() - e2.getAge();
        }
    };
    /**
     * Comparator to sort employees list or array in order of Name
     */
    public static Comparator<Employee> NameComparator = new Comparator<Employee>() {

        @Override
        public int compare(Employee e1, Employee e2) {
            return e1.getName().compareTo(e2.getName());
        }
    };
}
In main method                                                      //sort employees array using Comparator by Salary Arrays.sort(empArr, Employee.SalaryComparator);
System.out.println("Employees list sorted by Salary:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Age
Arrays.sort(empArr, Employee.AgeComparator);
System.out.println("Employees list sorted by Age:\n"+Arrays.toString(empArr));

//sort employees array using Comparator by Name
Arrays.sort(empArr, Employee.NameComparator);
System.out.println("Employees list sorted by Name:\n"+Arrays.toString(empArr));
https://www.journaldev.com/780/comparable-and-comparator-in-java-example

JAVA : STATIC

JAVA : STATIC



static is a non-access modifier in Java which is applicable for the following:
  1. variables
  2. blocks
  3. methods
  4. nested classes



JAVA : REST implementation in Eclipse

JAVA : REST implementation in Eclipse






Tuesday, 26 September 2017

Java : Program to Find Maximum Element in an Array using Binary Search

Java : Program to Find Maximum Element in an Array using Binary Search



  1. import java.util.Random;
  2.  
  3. public class Maximum_Using_Binary 
  4. {
  5.     static int N = 20;
  6.     static int []sequence = new int[N];
  7.  
  8.     public static void sort()
  9.     {
  10.        int i, j, temp;
  11.         for (i = 1; i< N; i++) 
  12.         {
  13.             j = i;
  14.             temp = sequence[i]; 
  15. //check next number is less than previous number, assume temp = 69, sequence[j-1] = 99
    //40 60 99(sequence[j-1]) 69(temp) 71 90 33 83 7 79 49 67 24 23 36 46 55 13 98 8  
  16.             while (j > 0 && temp < sequence[j-1]) 
  17.             {
  18.     //If it is less, then get previous number(99) to next number location(69)
  19.                 sequence[j] = sequence[j-1];  
  20.                 j = j-1;  //Point j to 60th location, bez to check in next loop 69 with 60
  21.             }
  22.             sequence[j] = temp;    //checking number finally add it to current location        
  23.         }        
  24.     }
  25.  
  26.     public static void main(String args[])
  27.     {
  28.         Random random = new Random();
  29.  
  30.         for(int i=0; i<N; i++)
  31.             sequence[i] = Math.abs(random.nextInt(100));
  32.         System.out.println("The sequence is :");
  33.         for(int i=0; i<N; i++)
  34.             System.out.print(sequence[i] + " ");     
  35.  
  36.         sort();
  37.  
  38.         System.out.println("\nThe maximum element in the sequence is : " + sequence[N-1]);
  39.     }
  40. }


Output:

The sequence is :
40 60 99 69 71 90 33 83 7 79 49 67 24 23 36 46 55 13 98 8 
The miaximum element in the sequence is : 99