Monday, 29 August 2016

OOPs Concepts

A methodology or paradigm to design a program using classes and objects.

Object Oriented programming is a programming methodology that is associated with the concept of Class.

Objects and various other concepts revovling around these like Inheritance, Polymorphism, Abstraction, Encapsulation etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. Abstract class and interface can be used to achieve abstraction.
Example: watching TV, we don't know the internal processing.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
Example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Advantage of OOPs over Procedure-oriented programming language
1)OOPs makes development and maintenance easier where as it is not easy to manage the projects if code grows as project size grows.

2)OOPs provides data hiding whereas in Procedure-oriented programming language a global data can be accessed from anywhere.

3)OOPs provides ability to simulate real-world event much more effectively.

Thursday, 25 August 2016

How to ensure that the Parent thread will die after the Child thread?

In below given example, the Parent thread dies before the Child thread.
class ChildThread1 extends Thread {
     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
               
                System.out.println("Child thread closed");
               
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public class CloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
    System.out.println("Main thread start");
    ChildThread1 cThread = new ChildThread1();
   
        cThread.setName("Child Thread");
        cThread.start();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Main thread closed
Child thread start
Child thread closed

Ensure the parent dies after the Child thread?

1. Using join() method
class ChildThread1 extends Thread {
     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
               
                System.out.println("Child thread closed");
               
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public class CloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
    System.out.println("Main thread start");
    ChildThread1 cThread = new ChildThread1();
   
        cThread.setName("Child Thread");
        cThread.start();
       
        cThread.join();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Child thread start
Child thread closed
Main thread closed

Using CountDownLatch:
package com.thread;

import java.util.concurrent.CountDownLatch;
class ChildThread1 extends Thread {
     CountDownLatch latch;
     public ChildThread1(CountDownLatch latch) {
           this.latch = latch;
     }

     @Override
     public void run() {
           try {
                System.out.println("Child thread start");
                Thread th = Thread.currentThread();
               
                if("Child Thread".equals(th.getName())) {
                     Thread.sleep(1000);
                }
                System.out.println("Child thread closed");
                /* Count down when the run method execution finished. */
                latch.countDown();
           } catch(Exception e) {
                System.out.println("exception is" + e);
           }
     }
}

public class CloseChildThreadTest {
    public static void main(String args[]) throws InterruptedException {
        /*Set count 1 to CountDownLatch. */
        CountDownLatch latch = new CountDownLatch(1);
        System.out.println("Main thread start");
        ChildThread1 cThread = new ChildThread1(latch);

        cThread.setName("Child Thread");
        cThread.start();

        /* Await till the end of the Child thread. */
        latch.await();
        System.out.println("Main thread closed");
    }
}
Output:
Main thread start
Child thread start
Child thread closed
Main thread closed

Java Nested Interface

A nested interface is any regular interface whose declaration occurs within another class or interface. These interfaces are used to group related interfaces so that we can be easy to maintain.

Rules for Declaring Nested Interface
1. Nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class.

2. Nested interfaces are implicitly static regardless of where they are declared (inside class or another interface).

interface OuterInter {
     void outerMethod();
     interface InnerInter {
           void method();
     } 

class NestedInterface implements OuterInter.InnerInter {
     public void method() {
           System.out.println("Hello nested interface");
     }

     public static void main(String args[]) {
           OuterInter.InnerInter message = new NestedInterface();//up-casting here
           message.method();
     }
}

Output: Hello nested interface

Application Use of Nested Interfaces

A static nested interface serves a great advantage to namespace resolution. This is the basic idea behind introducing nested interfaces and nested classes in Java.

For example, if you have an interface with an exceedingly common name, and in a large project, it is quite possible that some other programmer has the same idea, and has an interface with the same name you had, then you can solve this potential name clash by making your interface a public static nested interface.

Your interface will be known as outer class or outer interface, followed by a period (.), and then followed by static nested interface name.

Longest Increasing Subsequence

LIS problem is to find the length of longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.

package com.dp;
import java.util.Stack;

public class LIS {
     private static int findLIS(int[] array) {
           int len = array.length;
           int[] lis = new int[len];

           /** Every itself a LIS. */
           for (int i = 0; i < len; i++) {
                lis[i] = 1;
           }

           /** Logic to update the lis sequence*/
           for (int i = 1; i < len; i++) {
                for (int j = 0; j < i; j++) {
                     if(array[i]>array[j]) {
                           lis[i] = Math.max(lis[j]+1, lis[i]);
                     }
                }
           }

           int max = Integer.MIN_VALUE;
           for (int i = 0; i < len; i++) {
                if(max<lis[i]) {
                     max = lis[i];
                }
           }
           printSequence(array,lis, max);
           return max;
     }

     /**
      * Print LIS sequence.
      * @param array
      * @param lis
      * @param max
      */
     private static void printSequence(int[] array, int[] lis, int max) {
           Stack<Integer> stack = new Stack<>();
          
           /** Print the sequence. */
           for(int i = array.length-1; i >= 0; i--) {
                if(lis[i] == max ) {
                     stack.push(array[i]);
                     -- max;
                }
           }
          
           while(!stack.isEmpty()) {
                System.out.print(" "+ stack.pop());
           }
           System.out.println();
     }

     public static void main(String[] args) {
           int [] array = {15, 27, 14, 38, 26, 55, 46, 65, 85};
          
           int seq = findLIS(array);
          
           System.out.println("Longest Sequence #"+ seq);
     }
}
Output:
15 27 38 46 65 85
Longest Sequence #6
Related Posts Plugin for WordPress, Blogger...