Thursday, March 23, 2017

BlockingQueue in java

BlockingQueue is an interface and it was introduced in java 1.5 .BlcokingQueue is part of java.util.concurrent package 

Tuesday, March 21, 2017

Producer Consumer problem using wait() and notify() methods

As per the wiki,In computer,The Producer-Consumer problem also known as the Bounded-buffer problem is classic example of a multi-process synchronization problem. The problem describes two processes.The producer and the Consumer,Who share a common,fixed size buffer used as a queue,The producer's job is to produce/generate the data,put it into buffer,and start again.At the same time,the consumer is consuming the data (i.e removing it from buffer), one peice at a time. The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer

The solution for the Producer is to either go to sleep or discard if the buffer is full.Next time the consumer removes an item from the buffer,it notifies the Producer,who starts to fill the buffer again.In the same way,the consumer can go to sleep if it finds the buffer to be empty.The next time the producer puts data into the buffer,its wakes up the sleeping consumer. The solution can be reached by means of inter process communication.

Java program to solve the Producer consumer problem in java 

Here is complete java program to solve the Producer consumer problem in java programming language.In the program we have using wait() and notify methods from java.lang.Object class.
import java.util.Vector;
class Producer implements Runnable {
  private Vector sharedQueue;
  private int MAX_VALUE = 5;
  private int i = 0;

  public Producer(Vector sharedQueue) {
    super();
    this.sharedQueue = sharedQueue;
  }

  @Override
  public void run() {
    while (true) {
      try {
        produce(i++);
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    }
  }

  public void produce(int i) throws InterruptedException {
    synchronized (sharedQueue) {
      while (sharedQueue.size() == MAX_VALUE) {
        System.out.println("SharedQueue is full.Waiting for Consumer  to consume the object");
        sharedQueue.wait();
      }
    }
    synchronized (sharedQueue) {
      System.out.println("Produce the produced element " + i);
      sharedQueue.add(i);
      Thread.sleep(1000);
      sharedQueue.notify();
    }
  }
}

class Consumer implements Runnable {
  private Vector sharedQueue;

  public Consumer(Vector sharedQueue) {
    super();
    this.sharedQueue = sharedQueue;
  }

  @Override
  public void run() {
    while (true) {
      try {
        consume();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    }
  }
  private void consume() throws InterruptedException {
    synchronized (sharedQueue) {
      while (sharedQueue.isEmpty()) {
        System.out.println("SharedQueue is empty.Waiting for Producer to produce the Object");
        sharedQueue.wait();
      }
    }
    synchronized (sharedQueue) {
      Thread.sleep(500);      
      System.out.println("Consumed the element :" + sharedQueue.remove(0));
      sharedQueue.notify();
    }
  }
}

public class ProducerConsumerManager {
  public static void main(String[] args) {
    Vector sharedQueue = new Vector<>();
    Thread producer = new Thread(new Producer(sharedQueue));
    Thread consumer = new Thread(new Consumer(sharedQueue));
    producer.start();
    consumer.start();
  }
}
Output:
Produce the produced element 0
Produce the produced element 1
Consumed the element :0
Consumed the element :1
SharedQueue is empty.. Waiting for Producer to produce the Object
Produce the produced element 2
Produce the produced element 3
Produce the produced element 4
Produce the produced element 5
Produce the produced element 6
SharedQueue is full... Waiting for Consumer  to consume the object
Consumed the element :2
Consumed the element :3
Consumed the element :4
Consumed the element :5
Consumed the element :6
SharedQueue is empty.. Waiting for Producer to produce the Object
Produce the produced element 7
Produce the produced element 8
Produce the produced element 9
Produce the produced element 10
Produce the produced element 11
SharedQueue is full... Waiting for Consumer  to consume the object
Consumed the element :7
Consumed the element :8
Consumed the element :9
Consumed the element :10
Produce the produced element 12
Produce the produced element 13
Produce the produced element 14
There are many other way to solve the Producer Consumer problem using java .We will discuss upcoming blogs.
That's all about Producer Consumer problem using wait() and notify() methods.Please write your valuable comments below .

Tuesday, March 7, 2017

Print Fibonacci series in a diamond shape (Using Java)

Question:: The user will enter the number and the output should contain those many rows printing the Fibonacci (Exactly as shown in the below examples).

Example: 
Input :7 (Number of rows)
Output:
                                1
                              1+2
                            3+5+8
                          13+21+3
                            4+55+
                              89+
                                1
Note: To form a prefect diamond split the numbers of the Fibonacci series to next row and for the last number of the Fibonacci series, discard any remaining digit after the split, to print a prefect diamond shape (In example: "34" was split to place "4" into the next row to form a diamond and "144" is split place "1" in the last row and remaining digit "44" is discarded).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FibonacciSeriesInDiamondShape {

 // Formula for the n-th Fibonacci number
 private static int fibonacci(int n) {
  if (n == 1) {
    return 1;
  }
  if (n == 2) {
   return 1;
  }
  return fibonacci(n - 1) + fibonacci(n - 2);
  }

  // returns a string of all Fibonacci numbers upto the nth Fibonacci number  concatenated with "+"
  private static String concatFibSeries(int n) {
   StringBuilder sb = new StringBuilder();
   for (int i = 1; i <= n; i++) {
     sb.append(fibonacci(i)).append("+");
   }
   return sb.toString();
  }

  // cuts the string returned by the method concatFibSeries(int n) into small
  // chunks returns a list of strings with list.size equal to given rows the
  // length of the strings beginns by one and increases by two on each step
  // till the middle row is reached and decreases by two till the end of rows is reached
  private static List chopper(String concatenatedString, int rows) {
   List list = new ArrayList<>();
   for (int i = 1, j = 1; i <= rows; i++, j = (i <= Math.ceil(rows / 2.)) ? j + 2 : j - 2) {
     list.add(concatenatedString.substring(0, j));
     concatenatedString = concatenatedString.substring(j);
     if (concatenatedString.startsWith("+")) {
       concatenatedString = concatenatedString.substring(1);
     }
   }
   return list;
  }

  // adds the required space before and after each string and prints the string
   private static void printDiamond(List list) {
    final int listSize = list.size();
     for (int i = 0; i < listSize; i++) {
      String str = "";
      for (int j = 0; j < (Math.abs(list.size() - Math.ceil(list.size() / 2.) - i)); j++) {
        str += " ";
      }
      System.out.println(str + list.get(i) + str);
    }
  }

  public static void main(String[] args) {
   try (Scanner scanner = new Scanner(System.in);) {
    System.out.println("Enter number of rows:");
    int noOfRows = scanner.nextInt();
    String str = concatFibSeries(noOfRows * 2);
    List list = chopper(str, noOfRows);
    printDiamond(list);
    }
  }
}

Thursday, March 2, 2017

A Few Hidden Treasures in Java 8 --StringJoiner and String.join()

In day-to-day programming, it is quite common to join the Strings. Suppose if you have array or list elements. Let us say 
{“January”, February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} 
and you want to join them by comma to produce another String  
“JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER”
There is no easy way to do in java. Let us try with programmatically this.
import java.util.Arrays;
import java.util.List;
public class Manager {
 public static void main(String[] args) {
  List months = Arrays.asList("January", "February", "March", "April",
  "May", "June", "July", "August","September", "October", "November", "December");
  for(Object month:months){
   System.out.print(month.toString().toUpperCase() + ", ");
  }
 }
}
Output: JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER,
If you observe the output of the above program there is one stupid comma present in the output.
We need to iterate through array or list and then use a StringBuilder to append a comma after each element
and finally we need to remove the last comma because we don't want a comma after the last element
import java.util.Arrays;
import java.util.List;
public class Manager {
 public static String join(List list, String delimeter) {
  StringBuilder builder = new StringBuilder();
  boolean firstPosition = true;
  for (Object item : list) {
   if (firstPosition) {
    firstPosition = false;
   } else {
    builder.append(delimeter);
   }
   GUava.append(item.toString().toUpperCase());
  }
 return builder.toString();
}
 public static void main(String[] args) {
  List months = Arrays.asList("January", "February", "March", "April", 
  "May", "June", "July", "August","September", "October", "November", "December");
  System.out.println(join(months, ","));
 }
}
Output: JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER
Like Javascript Array.join() we dont have any readymade API in java before java 8 .We need to depend on 3rd party APIs like  Apache Commons ,Google Guava .Before going to discuss java 8 join method and String.join method will see few examples with Apache commons and Guava .

Apache commons StringUtils.join() method:

import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class Manager{
 public static void main(String[] args) {
  List months = Arrays.asList("January", "February", "March", "April",
 "May", "June", "July", "August", "September", "October", "November", "December");
  System.out.println(StringUtils.join(months, "|"));
 } 
}
Output:January|February|March|April|May|June|July|August|September|October|November|December
For more details about StringUtils.join() method, I'd really recommend taking a closer look: http://commons.apache.org/lang/api-3.1/org/apache/commons/lang3/StringUtils.html

Guava Joiner :

import java.util.Arrays;
import java.util.List;
import com.google.common.base.Joiner;
public class Manager{
 public static void main(String[] args) {
  List months = Arrays.asList("January", "February", "March", "April",
 "May", "June", "July", "August", "September", "October", "November", "December");
  System.out.println(Joiner.on(",").join(months));
 } 
}
For more details about Guava Joiner I'd really recommand taking a closer look : https://google.github.io/guava/releases/16.0/api/docs/index.html?com/google/common/base/Joiner.html

How to use String.join() method:

There are two overloaded join methods in String class,
public static String join(CharSequence delimiter,CharSequence... elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example,
 String message = String.join("-", "Java", "is", "cool"); // message returned is: "Java-is-cool"
Note that if an element is null, then "null" is added.
Parameters:
delimiter - the delimiter that separates each element
elements - the elements to join together.
Returns: a new String that is composed of the elements separated by the delimiter
Throws: NullPointerException - If delimiter or elements is null

public static String join(CharSequence delimiter, Iterable elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
For example,
 List strings = List.of("Java", "is", "cool");
 String message = String.join(" ", strings); //message returned is: "Java is cool"
 Set strings = new LinkedHashSet<>(List.of("Java", "is", "very", "cool"));
 String message = String.join("-", strings);//message returned is: "Java-is-very-cool"
Note that if an individual element is null, then "null" is added.
Parameters:
delimiter - a sequence of characters that is used to separate each of the elements in the resulting String
elements - an Iterable that will have its elements joined together.
Returns: a new String that is composed from the elements argument
Throws: NullPointerException - If delimiter or elements is null
Let's see Example for String.join() method
import java.util.Arrays;
import java.util.List;
public class Manager{
 public static void main(String[] args) {
  String join = String.join("|", "January", "February", "March", "April",
  "May", "June", "July", "August", "September", "October", "November", "December");
  System.out.println(join);
  List months = Arrays.asList("January", "February", "March", "April",
  "May", "June", "July", "August","September", "October", "November", "December");
  String joiner = String.join(",", months);
  System.out.println(joiner);
 }
}
OutPut:
January|February|March|April|May|June|July|August|September|October|November|December
January,February,March,April,May,June,July,August,September,October,November,December

How to use StringJoiner class in java:

StringJoiner is part of java.util packege.it is avaiable from java 8 onwards.
Here is what the new Java class says Here.
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
There are two constructors available from StringJoiner class
public StringJoiner(CharSequence delimiter)
public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
One is taking delimiter and other one allowing a prefix and suffix values .
import java.util.StringJoiner;
public class Manager {
 public static void main(String[] args) {
  StringJoiner joiner = new StringJoiner(",");
  String join = joiner.add("January").add("February").add("March")
    .add("April").add("May").toString();
  System.out.println(join);
 }
}
OutPut : January,February,March,April,May
import java.util.StringJoiner;
public class Manager {
 public static void main(String[] args) {
  StringJoiner joiner = new StringJoiner(",","[","]");
  String join = joiner.add("January").add("February").add("March")
    .add("April").add("May").toString();
  System.out.println(join);
 }
}
OutPut : [January,February,March,April,May]
Lets look at the StringJoiner methods once
public StringJoiner add(CharSequence newElement)
public StringJoiner merge(StringJoiner other)
public int length()
public String toString()
public StringJoiner setEmptyValue(CharSequence emptyValue)

But the real missing thing from the StringJoiner, A method to add multiple elements at once to the joiner. Every time i want to join,I have a list,set,or Iterable StringUtils from the comons lang or Guava or String.join() saperate methods.But it is missing from the StringJoiner.
String join = String.join(", ", list);
String join = Joiner.on(", ").join(list);
String join = StringUtils.join(list,",")
StringJoiner has no equivalent method. You have to add the elements one by one using add(CharSequence)!
StringJoiner joiner = new StringJoiner(", ");
 for (String str : list) {
   joiner.add(str);
 }
String join = joiner.toString();

Other why to join the String in java 8 using lambdas:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StringUtilsManager {
 public static void main(String[] args) {
  List months = Arrays.asList("January", "February", "March", "April",
  "May", "June", "July", "August", "September", "October", "November", "December");
  String join = months.stream()
 .map(String::toUpperCase)
 .collect(Collectors.joining(", "));
  System.out.println(join);
 }
}
Output: JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER

That's all about StringJoiner and String.join method in java 8.If your not using java 8 you can use 3rd party APIs like Guava,or Apache common lang (StringUtils.join) for the same purpose .
If you find any other ways to join the String please update your comments below .


Friday, February 24, 2017

How to find Even and Odd number in java

There are many ways to find the given number is Even or Odd in any programming languages.Before going to discuss technical details of Even and Odd numbers.
Let's see what is Even and Odd numbers in mathematics.
Even Number: Any Integer that can be divided exactly by 2. The last digit should be – 0,2,4,6,8 Ex: -24,4,16,28
Odd Number: Any integer that cannot be divided exactly by 2. The last digit should be – 1,3,5,7,9 Ex: -13,5,7,17,21
There are different ways to find even and odd number programmatically, we will discuss one by one 

Even or Odd number using modulus (%) operator:

One way is in case of the remainder.Even numbers, the remainder will be 0 and for Odd numbers, the remainder will be 1. We can use this way to find the even and odd number in java. Java had a remainder operator called modulus operation denoted by % which does exactly same, as described above. We will illustrate this example with the program below.
import java.util.Scanner;
public class Manager {
 public static void main(String[] args) {
  try (Scanner scanner = new Scanner(System.in)) {
   System.out.println("Enter the number :");
   int value = scanner.nextInt();
   if (value % 2 == 0) {
    System.out.println("The given number  :: " + value + " is Even Number");
   } else {
    System.out.println("The given number  :: " + value + " is Odd Number");
   }
  } catch (Exception ex) {
   System.out.println("Exception occurred :: " + ex.getMessage());
  }
 }
}

Even or Odd number using bitwise (&) operator:

A bitwise AND takes two equal-length binary representations and performs the logical AND operation on each pair of the corresponding bits, by multiplying them. Thus, if both bits in the compared position are 1, the bit in the resulting binary representation is 1 (1 × 1 = 1); otherwise, the result is 0 (1 × 0 = 0 and 0 × 0 = 0). For example:
0101 (decimal 5)
AND 0011 (decimal 3)
  = 0001 (decimal 1)
The operation may be used to determine whether a particular bit is set (1) or clear (0). For example, given a bit pattern 0011 (decimal 3), to determine whether the second bit is set we use a bitwise AND with a bit pattern containing 1 only in the second bit:
0011 (decimal 3)
AND 0010 (decimal 2)
  = 0010 (decimal 2)
Because the result 0010 is non-zero, we know the second bit in the original pattern was set. This is often called bit masking. (By analogy, the use of masking tape covers, or masks, portions that should not be altered or portions that are not of interest. In this case, the 0 values mask the bits that are not of interest.)
The bitwise AND may be used to clear selected bits (or flags) of a register in which each bit represents an individual Boolean state. This technique is an efficient way to store a number of Boolean values using as little memory as possible.
For example, 0110 (decimal 6) can be considered a set of four flags, where the first and fourth flags are clear (0), and the second and third flags are set (1). The second bit may be cleared by using a bitwise AND with the pattern that has a zero only in the second bit:
0110 (decimal 6)
AND 1101 (decimal 13)
  = 0100 (decimal 4)
Because of this property, it becomes easy to check the parity of a binary number by checking the value of the lowest valued bit. Using the example above:
0110 (decimal 6)
AND 0001 (decimal 1)
  = 0000 (decimal 0)
Because 6 AND 1 is zero, 6 is divisible by two and therefore even.
import java.util.Scanner;
public class Manager{
 public static void main(String[] args) {
  try (Scanner scanner = new Scanner(System.in)) {
   System.out.println("Enter the number :");
   int value = scanner.nextInt();
   if ((value & 1) == 0) {
    System.out.println("The given number  :: " + value + " is Even Number");
   } else {
    System.out.println("The given number  :: " + value + " is Odd Number");
   }
  } catch (Exception ex) {
   System.out.println("Exception occurred :: " + ex.getMessage());
  }
 }
}

Even or Odd number using division (/) operator:

import java.util.Scanner;
public class Manager{
 public static void main(String[] args) {
  try (Scanner scanner = new Scanner(System.in)) {
   System.out.println("Enter the number :");
   int value = scanner.nextInt();
   int quotient = value / 2;
   if (quotient * 2 == value) {
    System.out.println("The given number  :: " + value + " is Even Number");
   } else {
    System.out.println("The given number  :: " + value + " is Odd Number");
   }
  } catch (Exception ex) {
   System.out.println("Exception occurred :: " + ex.getMessage());
  }
 }
}

Now will see few interview question related to Even and Odd numbers in java :

  • How to find given number is even or odd number in java 
  • Find Odd numbers between two numbers in java 
  • Find Even numbers between two numbers in java 
  • Calculate the total number of Odd and Even numbers in java 
  • Print the Even and Odd numbers in an array 

How to find given number is Even or Odd number in java :

import java.util.Scanner;
public class Manager {
 public static void main(String args[]) {
  try (Scanner scanner = new Scanner(System.in)) {
   System.out.println("Check Even or Odd ");
   System.out.println("Enter the number : ");
   int num = scanner.nextInt();
   if ((num % 2) == 0) {
    System.out.println(num + " is Even number");
   } else {
     System.out.println(num + " is Odd number");
   }
  }
 }
}

Find Odd numbers between two numbers in java :

import java.util.Scanner;
public class Manager {
 public static void main(String args[]) {
  try (Scanner scanner = new Scanner(System.in)) {
    System.out.println("Find Odd numbers between two numbers");
     System.out.println("Enter the Starting value : ");
     int start = scanner.nextInt();
     System.out.println("Enter the End value : ");
     int end = scanner.nextInt();
     System.out.println("Odd number:: ");
     for (int i = start; i <= end; i++) {
     if ((i % 2) != 0) {
      System.out.print(i + " ");
     }
    }
  }
 }
}

Find Even numbers between two numbers in java :

import java.util.Scanner;
public class Manager {
 public static void main(String args[]) {
   try (Scanner scanner = new Scanner(System.in)) {
     System.out.println("Find Even numbers between two numbers");
     System.out.println("Enter the Starting value : ");
     int start = scanner.nextInt();
     System.out.println("Enter the End value : ");
     int end = scanner.nextInt();
     System.out.println("Even Numbers:: ");
     for (int i = start; i <= end; i++) {
      if ((i % 2) == 0) {
        System.out.print(i + " ");
      }
    }
   }
  }
}

Calculating the total number of Odd and Even numbers in java:

import java.util.Scanner;
public class Manager {
 public static void main(String args[]) {
  try (Scanner scanner = new Scanner(System.in)) {
  System.out.println("Total number of " + "Odd & Even numbers between two numbers");
   System.out.println("Enter the Starting value : ");
   int start = scanner.nextInt();
   System.out.println("Enter the End value : ");
   int end = scanner.nextInt();
   int odd = 0;
   int even = 0;
   for (int i = start; i <= end; i++) {
    if ((i % 2) == 0) {
     even++;
    } else {
    odd++;
   }
  }
  System.out.println("\nTotal number of Odd number is " + odd);
  System.out.println("Total number of Even number is " + even);
  }
 }
}

Print the Even and Odd number in an array :

Enter the size of an array and then enter all the elements of that array. Now using for loop and if condition we use to distinguish whether given integer in the array is odd or even.Here is the source code of the Java Program to Print the Odd & Even Numbers in an Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

import java.util.Scanner;
public class Manager {
 public static void main(String[] args) {  
  try (Scanner scanner = new Scanner(System.in)) {
   System.out.print("Enter no. of elements you want in array:");
   int number = scanner.nextInt();
   int a[] = new int[number];
   System.out.println("Enter all the elements:");
   for (int i = 0; i < number; i++) {
    a[i] = scanner.nextInt();
   }
   System.out.print("Odd numbers:");
   for (int i = 0; i < number; i++) {
    if (a[i] % 2 != 0) {
     System.out.print(a[i] + " ");
    }
   }
   System.out.println("");
   System.out.print("Even numbers:");
   for (int i = 0; i < number; i++) {
    if (a[i] % 2 == 0) {
     System.out.print(a[i] + " ");
    }
   }
  }
 }
}
Output:
Enter no. of elements you want in array:10
Enter all the elements:
20
27
23
67
48
12
69
25
48
35
Odd numbers:27 23 67 69 25 35 
Even numbers:20 48 12 48 

That's all about How to find Even and Odd numbers in java using different ways. If you find any other ways to find the Even and Odd numbers, Please update your comments below.