Sunday, 29 July 2018

synchronized Method and block

Problem without Synchronization

package threads;


public class Two {
    public static void main(String args[]) {
        One obj = new One();
        Thread th1 = new Thread(new t1(obj));
        Thread th2 = new Thread(new t2(obj));
        th1.start();
        th2.start();
    }
}

class t1 implements Runnable{
   
    One one;
    public t1(One one) {
     this.one = one;
    }
    @Override
    public void run() {
             one.add();
    }
   
}

class t2 implements Runnable{
    One one;
    public t2(One one) {
     this.one = one;
    }
    @Override
    public void run() {
             one.add();
    }
   
}



package threads;


public class One {
    int count;
    public void add() {
        for(int i=0;i<5;i++) {
            this.count =get()+1;
            System.out.println(count);
             try{ 
                  Thread.sleep(400); 
                 }catch(Exception e){System.out.println(e);} 
               }
        }

    public int get() {
        return count;
    }
}



output:

2
1
3
4
5
6
7
8
9
9


Note: every time we will get different output.


Solution with  Synchronization

change in class one as below:

package threads;


public class One {
    int count;
    public synchronized void add() {
        for(int i=0;i<5;i++) {
            this.count =get()+1;
            System.out.println(count);
             try{
                  Thread.sleep(400);
                 }catch(Exception e){System.out.println(e);}
               }
        }

    public int get() {
        return count;
    }
}


Now out put is below:
1
2
3
4
5
6
7
8
9
10

Use synchronized block:

public void add() {
        for(int i=0;i<5;i++) {
            synchronized (this) {
                this.count =get()+1;
                System.out.println(count);
            }

             try{ 
                  Thread.sleep(400); 
                 }catch(Exception e){System.out.println(e);} 
               }
        }

output:
1
2
3
4
5
6
7
8
9
10


Notice how the Java synchronized block construct takes an object in parentheses. In the example "this" is used, which is the instance the add method is called on( One obj = new One();). The object taken in the parentheses by the synchronized construct is called a monitor object. 



Sunday, 8 July 2018

CheckNumberPalindrom

    public static void main(String args[]) {
        int val  =121;
        int revNum = reverse(val);
        if(val ==revNum) {
            System.out.println("palindrom");
        }else {
            System.out.println("not palindrom");
        }
    }
   
   
    static int reverse(int val) {
        int revNum = 0;
        while(val>0) {
        int temp = val%10;
        val = val/10;
        revNum = revNum*10+temp;
        }
        return revNum;
    }
}

Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character

both string length should equal for check anagram

public class AnagramDiff {
    public static void main(String args[]) {
        int count = 0;
        String s1 = "spot";
        String s2 = "poat";
        int[] arr = new int[26];
        for(int i=0;i<s1.length();i++) {
            arr[s1.charAt(i)-'a']++;
        }
       
        for(int i=0;i<s2.length();i++) {
            if(--arr[s2.charAt(i)-'a'] <0) {
                count++;
            }
        }
       
        System.out.println("number of manipulation required:"+count);
       
    }
}

Tuesday, 26 June 2018

forEach() vs forEachOrdered() in java 8 stream

forEach() method performs an action for each element of this stream. For parallel stream, this operation does not guarantee to maintain order of the stream.
forEachOrdered() method performs an action for each element of this stream, guaranteeing that each element is processed in encounter order for streams that have a defined encounter order.
take below example:
    String str = "sushil mittal";
    System.out.println("****forEach without using parallel****");
    str.chars().forEach(s -> System.out.print((char) s));
    System.out.println("\n****forEach with using parallel****");

    str.chars().parallel().forEach(s -> System.out.print((char) s));
    System.out.println("\n****forEachOrdered with using parallel****");

    str.chars().parallel().forEachOrdered(s -> System.out.print((char) s));
Output:
****forEach without using parallel****
sushil mittal
****forEach with using parallel****
mihul issltat
****forEachOrdered with using parallel****
sushil mittal

Friday, 15 June 2018

Inheritance vs Composition in java


They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".


In the composition approach, the subclass becomes the "front-end class," and the superclass becomes the "back-end class." With inheritance, a subclass automatically inherits an implemenation of any non-private superclass method that it doesn't override. With composition, by contrast, the front-end class must explicitly invoke a corresponding method in the back-end class from its own implementation of the method. This explicit call is sometimes called "forwarding" or "delegating" the method invocation to the back-end object.

The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class. 

Inheritance Example:
class Fruit {

// Return int number of pieces of peel that // resulted from the peeling activity. public int peel() {
System.out.println("Peeling is appealing."); return 1; } }
class Apple extends Fruit { }
class Example1 {
public static void main(String[] args) {
Apple apple = new Apple(); int pieces = apple.peel(); } }

if we want to change return type to peel() then it will effect to main method also so solution is composition as below:

Composition Example:
class Fruit {

// Return int number of pieces of peel that // resulted from the peeling activity. public int peel() {
System.out.println("Peeling is appealing."); return 1; } }
class Apple {
private Fruit fruit = new Fruit();
public int peel() { return fruit.peel(); } }
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple(); int pieces = apple.peel(); } }

ref: https://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html

Abstraction vs Encapsulation java

Difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.

Encapsulation is also called data hiding.

Encapsulation:
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism for wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
● Declare the variables of a class as private.
● Provide public setter and getter methods to modify and view the variables values.

 Abstraction:
Likewise in Object-oriented programming, abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.

Java Default Method



public interface A {
    void print();
    default void display() {
        System.out.println("A");
    }
}

public interface B {
    void print();
    default void display() {
        System.out.println("B");
    }
}

If implement single interface

public class Testing    implements A {

    public static void main(String args[]) {
        Testing obj= new Testing();
        obj.display();
    }

    @Override
    public void print() {
         System.out.println("print");
       
    }

}

If implement multiple interface with same default method

public class Testing    implements A,B {

    public static void main(String args[]) {
        Testing obj= new Testing();
        obj.display();
    }

    @Override
    public void display() {
        B.super.display(); //if we want call A class then A.super.display
    }

    @Override
    public void print() {
         System.out.println("print");
       
    }

}

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...