Wednesday, July 25, 2018

What will be the output of the below code?

Problem statement:
What will be the output of the code when we override hashCode() & equals() in java

public class Employee {
    String name;
    int age;
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
import java.util.HashMap;
import java.util.Map;

public class HashMapMain {
    public static void main(String[] args) {
        Employee emp1=new Employee("Vikesh",21);
        Map<Employee,String> hm=new HashMap<Employee,String>();
        hm.put(emp1, "Verified");
        System.out.println("11: "+emp1.hashCode());
        emp1.setName("Ishaan");
        System.out.println("22: "+emp1.hashCode());
        System.out.println(hm.get(emp1));
    }
}
Output:
11: -1732600440
22: -2095637962
null

Saturday, July 21, 2018

What do you mean by BlockingQueue in java?

Problem statement:
How do you write a program to implement producer-consumer problem using BlockingQueue?

[1] Producer.java

import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
    BlockingQueue queue = null;
    Producer(BlockingQueue queue) {
        this.queue = queue;
    }
    @Override
    public void run() {
        for (int i = 1; i <= 12; i++) {
            System.out.println("Produced item " + i);
            try {
                queue.put("item " + i);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
    }
}

[2] Consumer.java

import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
    BlockingQueue queue = null;
    public Consumer(BlockingQueue queue) {
        super();
        this.queue = queue;
    }
    @Override
    public void run() {
        while (true) {
            try {
                System.out.println("Consumed " + queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

[3] BlockingQueueExecution.java

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueExecution {
    public static void main(String args[]) {
        BlockingQueue queue = new ArrayBlockingQueue(10); // here capacity= 10
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}

Output:
Produced item 1
Consumed item 1
Produced item 2
Consumed item 2
Produced item 3
Consumed item 3
Produced item 4
Produced item 5
Consumed item 4
Produced item 6
Consumed item 5
Produced item 7
Consumed item 6
Produced item 8
Consumed item 7
Produced item 9
Consumed item 8
Produced item 10
Consumed item 9
Produced item 11
Consumed item 10
Produced item 12
Consumed item 11
Consumed item 12

What do you know about CyclicBarrier in java?

Problem statement: Write a cab transport service where passengers will come one by one and join the queue but they can't board the cab or cab won't move until there are 3 passengers waiting in the queue.
  1. CyclicBarrier is one of the Java Concurrency Utility.
  2. It was introduced in java 5
  3. It falls under java.util.concurrency package
  4. Using this we can synchronised the threads which are processing through some algorithm
  5.  Using this we can make threads wait at a point of code until specific number of threads have reached that point of code.Threads will be ordered to wait on call of await() method
  6. CyclicBarrier can be instantiated as: CyclicBarrier obj = new CyclicBarrier(n) where n is an interger and also that specific number.
[1]:

import java.util.concurrent.CyclicBarrier;

public class CabBooking {
    public static void main(String args[]) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        Thread t1 = new Thread(new CabService(cyclicBarrier));
        t1.setName("Passenger-1");
        t1.start();
        Thread.sleep(5000);

        Thread t2 = new Thread(new CabService(cyclicBarrier));
        t2.setName("Passenger=-2");
        t2.start();
        Thread.sleep(5000);

        Thread t3 = new Thread(new CabService(cyclicBarrier));
        t3.setName("Passenger-3");
        t3.start();
        Thread.sleep(5000);
    }
}
[2]:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CabService implements Runnable {
    CyclicBarrier cyclicBarrier;
    public CabService(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }
    @Override
    public void run() {
        try {
            System.out.println("++++++ " + Thread.currentThread().getName() + " has arrived");
            try {
                cyclicBarrier.await();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("****** " + Thread.currentThread().getName() + " is going to board the cab");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Output:
++++++ Passenger-1 has arrived
++++++ Passenger=-2 has arrived
++++++ Passenger-3 has arrived
****** Passenger-3 is going to board the cab
****** Passenger-1 is going to board the cab
****** Passenger=-2 is going to board the cab
ref: click for oracle doc

What do you know about CountDownLatch in java?

  1. CountDownLatch is one of the Java Concurrency Utility.
  2. It was introduced in java 5
  3. It falls under java.util.concurrency package
  4. It is kind of synchronizer
  5. It makes 1 thread to wait until other threads have finished their job.
Important methods of CountDownLatch class
  1. await(): void
  2. countDown(): void
  3. getCount(): long
Problem statementI need to get an online food order having various food items i.e. Pizza, Pasta, Coke. Start tracking the processing of the food in another threads. Once all the food items are prepared, I need to notify the customer that food is prepared.

[1]

import java.util.concurrent.CountDownLatch;
public class Processor {
    public static void main(String args[]) {
     CountDownLatch countDownLatch = new CountDownLatch(args.length);
     Thread foodProcessorThread = new Thread(new FoodProcessor(countDownLatch, args));
        foodProcessorThread.start();
        System.out.println("Order is received and is being processed");
        try {
            countDownLatch.await();
            System.out.println("Order is processed successfully and is ready to get dispatched");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
[2]
import java.util.concurrent.CountDownLatch;
public class FoodProcessor implements Runnable {
    private final CountDownLatch latch;
    private final String items[];
    public FoodProcessor(CountDownLatch latch, String items[]) {
        this.latch = latch;
        this.items = items;
    }
    @Override
    public void run() {
        for (int i = 0; i < items.length; i++) {
            try {
                System.out.println("Before processing the item, value of CountDownLatch: " + latch.getCount());
                Thread.sleep(10000);
                System.out.println("items " + items[i] + " is prepared");
                latch.countDown();
                System.out.println("After processing the item, value of CountDownLatch: " + latch.getCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Output:
Order is received and is being processed
Before processing the item, value of CountDownLatch: 3
items Pizza is prepared
After processing the item, value of CountDownLatch: 2
Before processing the item, value of CountDownLatch: 2
items Pasta is prepared
After processing the item, value of CountDownLatch: 1
Before processing the item, value of CountDownLatch: 1
items Coke is prepared
After processing the item, value of CountDownLatch: 0

Order is processed successfully and is ready to get dispatched
ref: click for oracle CountDownLatch doc

    Friday, July 20, 2018

    Can we have different return type in method overriding in java?

    Problem statement: can we have different return type in method overriding in java

    Yes ! it may differ but their are some limitations. 

    Before Java 5.0, when you override method, both parameters and return type must match exactly
    In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
    For example:
    class OverridingExe2 {
        public Object run() {
            System.out.println("object");
            return null;
        }
    }
    public class OverridingExe1 extends OverridingExe2 {
        public String run() { // covariant return type from java 5.0
            System.out.println("string");
            return null;
        }
        public static void main(String args[]) throws Exception {
            OverridingExe2 r = new OverridingExe1();
            r.run();
        }
    }
    Output:
    string

    What do you mean by CountDownLatch in java?

    Problem statement:
    • Class CountDownLatch:
    1. java.util.concurrent
    2. java.util.concurrent.CountDownLatch extends java.lang.Object
    3. Since Java 1.5
    • Constructor Summary:
    1. CountDownLatch(int count)
    Constructs a CountDownLatch initialized with the given count.
    • Method Summary:
    1. await(): void
    2. await(long timeout, TimeUnit unit): boolean
    3. countDown(): void
    4. getCount(): long
    5. toString(): String

    Tuesday, July 17, 2018

    Monday, July 16, 2018

    Problem statement:
    There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neighbour). Each day, for each cell, if its neighbours are both active or both inactive, the cell becomes inactive the next day,. otherwise it becomes active the next day.

    Assumptions: The two cells on the ends have single adjacent cell, so the other adjacent cell can be assumsed to be always inactive. Even after updating the cell state. consider its pervious state for updating the state of other cells. Update the cell informationof allcells simultaneously.

    Write a fuction cellCompete which takes takes one 8 element array of integers cells representing the current state of 8 cells and one integer days representing te number of days to simulate. An integer value of 1 represents an active cell and value of 0 represents an inactive cell.

    TESTCASES 1:
    INPUT:
    [1,0,0,0,0,1,0,0],1
    EXPECTED RETURN VALUE:
    [0,1,0,0,1,0,1,0]

    TESTCASE 2:
    INPUT:
    [1,1,1,0,1,1,1,1,],2
    EXPECTED RETURN VALUE:
    [0,0,0,0,0,1,1,0]


    public class Colony {

        public static int[] cellCompete(int[] cells, int days) {

            int len = cells.length;
            int[] newCells = new int[cells.length];
            for (int k = 0; k < days; k++) {
                for (int i = 0; i < cells.length; i++) {
                    int cell = cells[i];
                    int nextCell;
                    int prevCell;
                    int activenumber;
                    if (i == 0) {
                        // edge cases
                        nextCell = cells[1];
                        prevCell = 0;
                    } else if (i == cells.length - 1) {
                        // edge case
                        prevCell = cells[cells.length - 2];
                        nextCell = 0;
                    } else {
                        nextCell = cells[i + 1];
                        prevCell = cells[i - 1];
                    }
                    if (nextCell == prevCell) {
                        // set it to inactive
                        activenumber = 0;
                    } else {
                        //set it to active
                        activenumber = 1;
                    }
                    newCells[i] = activenumber;
                }
                for (int i = 0; i < 8; i++) {
                    cells[i] = newCells[i];
                }
            }
            return newCells;
        }
        public static void main(String[] args) {
            int[] array = {1, 1, 1, 0, 1, 1, 1, 1};
            int days = 2;
            array = cellCompete(array, days);
            for (int i = 0; i < array.length; i++) {
                System.out.print(array[i]);
            }
        }
    }

    How do you calculate Square Root of a number in Java?

    Problem statement: Find the square root of a number in java !
    1st Approach:
    public class SquareRootExe {
        public static void main(String args[]) {
            double sqrRoot = squareRoot(4);
            System.out.println(sqrRoot);
        }
        public static double squareRoot(double n) {
            double t;
            double sqRoot = n / 2;
            do {
                t = sqRoot;
                sqRoot = (t + (nt)) / 2;
            } while ((t - sqRoot) != 0);
            return sqRoot;
        }
    }
    2nd Approach:
    public class SquareRootExe {
        public static void main(String args[]) {
            double sqrRoot = squareRoot(4);
            System.out.println(sqrRoot);
        }
        public static double squareRoot(double n) {
            double res = Math.sqrt(n);
            return res;
        }
    }
    Output:
    2.0

    How do you calculate Cube Root of a number in Java?

    Problem statement: Find the cube root of a number in java.
    public class CubeRootExe {
        public static void main(String args[]) {
            double cbRt = cubeRoot(8);
            System.out.println(cbRt);
        }
        public static double cubeRoot(double n) {
            return Math.cbrt(n);
        }
    }
    Output:
    2.0

    what is the code for cloning an object in java?

    class Human implements Cloneable {
        int age;
        long salary;

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    public class CloningExe {
        public static void main(String args[]) throws CloneNotSupportedException {
            Human h1 = new Human();
            h1.age = 21;
            h1.salary = 1200;
            System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
            Human h2 = (Human) h1.clone();
            System.out.println("-----------------------");
            System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
            System.out.println("h2 age: " + h2.age + ", h2 salary: " + h2.salary);
        }
    }
    Output:
    h1 age: 21, h1 salary: 1200
    -------------------------------
    h1 age: 21, h1 salary: 1200
    h2 age: 21, h2 salary: 1200

    2nd Approach:
    class Human implements Cloneable {
        int age;
        long salary;

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    public class CloningExe {
        public static void main(String args[]) throws CloneNotSupportedException {
            Human h1 = new Human();
            h1.age = 21;
            h1.salary = 1200;
            System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
            Human h2 = (Human) h1.clone();
            h2.salary = 1300;
            System.out.println("-----------------------");
            System.out.println("h1 age: " + h1.age + ", h1 salary: " + h1.salary);
            System.out.println("h2 age: " + h2.age + ", h2 salary: " + h2.salary);
        }
    }
    Output:
    h1 age: 21, h1 salary: 1200
    ------------------------------
    h1 age: 21, h1 salary: 1200
    h2 age: 21, h2 salary: 1300

    what is the code for deep copy in java?

    class Human {
        int age;
        long salary;
    }
    public class DeepCopyExe {
        public static void main(String args[]) {
            Human h1 = new Human();
            h1.age = 20;
            h1.salary = 1000;
            System.out.println("h1 age: "+h1.age+", h1 salary: "+h1.salary);
            Human h2 = new Human();
            h2.salary = 1200;
            System.out.println("h1 age: "+h1.age+", h1 salary: "+h1.salary);
            System.out.println("h2 age: "+h2.age+", h2 salary: "+h2.salary);
        }
    }
    Output:
    h1 age: 20, h1 salary: 1000
    h1 age: 20, h1 salary: 1000
    h2 age: 0, h2 salary: 1200

    what is the code for shallow copy in java?

    class Human {
        int age;
        long salary;
    }
    public class ShallowCopyExe {
        public static void main(String args[]) {
            Human h1 = new Human();
            h1.age = 20;
            h1.salary = 1000;
            System.out.println("h1 age: "+h1.age+", h1 salary: "+h1.salary);
            Human h2 = h1;
            h2.salary = 1200;
            System.out.println("h1 age: "+h1.age+", h1 salary: "+h1.salary);
            System.out.println("h2 age: "+h2.age+", h2 salary: "+h2.salary);
        }
    }
    Output:
    h1 age: 20, h1 salary: 1000
    h1 age: 20, h1 salary: 1200
    h2 age: 20, h2 salary: 1200

    what do you mean by Shallow Cloning and Deep Cloning in java?

    Problem statement: Shallow copy vs Deep copy.
    shallow = little depth
    Shallow copy [meaning reference copy]
    is method of copying an object and is followed by default in cloning. In this method the fields of an old object X are copied to the new object Y. While copying the object type field the reference is copied to Y i.e object Y will point to same location as pointed out by X. If the field value is a primitive type it copies the value of the primitive type

    Therefore, any changes made in referenced objects in object X or Y will be reflected in other object


    Deep copy [meaning object copy]

    If we want to create a deep copy of object X and place it in a new object Y then new copy of any referenced objects fields are created and these references are placed in object Y. This means any changes made in referenced object fields in object X or Y will be reflected only in that object and not in the other. In below example, we create a deep copy of object.

    A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

    Explanation with program:

    import java.util.ArrayList;
    class TestExe {
        int x, y;
    }
    // reference of TestExe and implements clone with deep copy
    class Test2 implements Cloneable {
        int a, b;
        TestExe c = new TestExe();
        public Object clone() throws CloneNotSupportedException {
            // Assign the shallow copy to new reference variable t
            Test2 t = (Test2) super.clone();
            t.c = new TestExe();
            return t;
        }
    }
    public class DeepCloning {
        public static void main(String args[]) throws CloneNotSupportedException {
            Test2 t1 = new Test2();
            t1.a = 10;
            t1.b = 20;
            t1.c.x = 30;
            t1.c.y = 40;
            Test2 t2 = (Test2) t1.clone();
            t2.a = 100;
            // Change in primitive type of t2 will not be reflected in t1 field
            t2.c.x = 300;
            // Change in object type field of t2 will not be reflected in t1(deep copy)
            System.out.println(t1.a + " " + t1.b + " " + t1.c.x + " " + t1.c.y);
            System.out.println(t2.a + " " + t2.b + " " +t2.c.x + " " + t2.c.y);
        }
    }
    Output:
    10 20 30 40
    100 20 300 0

    How do you write an algorithm for the multiplication of two matrix [2D array]?

    Problem statement:
    Given two matrices, the task is to multiply them. Matrices can either be square or rectangular.
    Example:
    Input: int m1[][] = {{2, 3, 4}, {5, 6, 7}}; // 2 X 3 matrix
    int m2[][] = {{1, 2}, {3, 4}, {5, 6}}; // 3 X 2 matrix
    Output: {{31, 40},{58,76}}
    1. public class MatrixMultiplication {
    2.     public static void main(String args[]) {
    3.         int m1[][] = {{2, 3, 4}, {5, 6, 7}};    // 2 X 3 matrix
    4.         int m2[][] = {{1, 2}, {3, 4}, {5, 6}};  // 3 X 2 matrix
    5.         int res[][] = new int[2][2];    // resultant matrix of 2 X 2
    6.         for (int i = 0; i < 2; i++) {   // i represent row
    7.             for (int j = 0; j < 2; j++) {   // j represent column
    8.                 res[i][j] = 0;  // assume res[0][0] = 0
    9.                 for (int k = 0; k < 3; k++) {
    10.                     // k represent first matrix i.e. m1 -> number of column for                        // counter sum
    11.                     res[i][j] = res[i][j] + m1[i][k] * m2[k][j];
    12.                 }
    13.             }
    14.         }
    15.         // printing the resultant matrix
    16.         for (int i = 0; i < 2; i++) {
    17.             for (int j = 0; j < 2; j++) {
    18.                 System.out.print(res[i][j] + " ");
    19.             }
    20.             System.out.println();
    21.         }
    22.     }
    23. }
    Method-II:
    1. public class MatrixMultiplication2D {
    2.     public static void main(String args[]) {
    3.         int m1[][] = {{2, 3, 4}, {5, 6, 7}};    // 2 X 3 matrix
    4.         int m2[][] = {{1, 2}, {3, 4}, {5, 6}};  // 3 X 2 matrix
    5.         int sum = 0;    // initial sum value is 0
    6.         int res[][] = new int[2][2];    // resultant matrix of 2 X 2
    7.         for (int i = 0; i < 2; i++) {   // i represent row
    8.             for (int j = 0; j < 2; j++) {   // j represent column
    9.                 res[i][j] = 0;  // assume res[0][0] = 0
    10.                 for (int k = 0; k < 3; k++) {
    11.                     // k represent first matrix i.e. m1 -> number of column for                        // counter sum
    12.                     sum = sum + m1[i][k] * m2[k][j];
    13.                 }
    14.                 res[i][j] = sum;    //  assigned sum value to resultant matrix
    15.                 sum = 0;    // reset to 0 for next iteration
    16.             }
    17.         }
    18.         // printing the resultant matrix
    19.         for (int i = 0; i < 2; i++) {
    20.             for (int j = 0; j < 2; j++) {
    21.                 System.out.print(res[i][j] + " ");
    22.             }
    23.             System.out.println();
    24.         }
    25.     }
    26. }
    Output:
    31 40
    58 76

    How to run standalone mock server on local laptop

     Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...