Java 8 - StringJoiner

In Java-8 we got new class called StringJoiner to join multiple strings. Nothing new in StringJoiner class when we compare with already existing classes like StringBuffer and StringBuilder. Only the difference here we can set prefix and suffix along with delimiter, or we can set only delimiter by using different constructor. Lets see simple example as how to use StringJoiner from Java-8.
Java 8 - StringJoiner

public class StringJoinerExample {

 public static void main(String[] args) {
  
  StringJoiner sJoin = new StringJoiner(",");
  
  sJoin.add("java");
  sJoin.add("python");
  sJoin.add("C#");
  sJoin.add("scala");
    
  System.out.println(sJoin);
 }
}

OUTPUT:

java,python,C#,scala




public class StringJoinerExample {

 public static void main(String[] args) {
  
  StringJoiner sJoin = new StringJoiner("," ,"{" ,"}");
  
  sJoin.add("java");
  sJoin.add("python");
  sJoin.add("C#");
  sJoin.add("scala");
    
  System.out.println(sJoin);  
 }
}

OUTPUT:
{java,python,C#,scala}

Print Odd and Even number in sequence using two threads

 
One of the interview question on Thread to Print Odd and Even number in sequence using two threads. Below program will print odd and even numbers in sequential order using 2 threads. 1st thread will take care of printing odd numbers and 2nd thread will take care of printing even numbers. Here 1st thread will print odd number and go for waiting state after notifying to 2nd thread to print even number. Next 2nd thread will print even number and go for waiting state after notifying to 1st thread. Its goes on...
Print Odd and Even number in sequence using two threads



class Numbers implements Runnable{

 private int number = 1;

 @Override
 public void run() {
  
  Object lock = Thread.currentThread().getClass();
  
  if(Thread.currentThread().getName().equals("odd")){
   
   synchronized (lock) {
    while(true){
     System.out.println("ODD  : "+number++);
     lock.notify();
     try {
      Thread.sleep(100);// Just to print slowly
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
   
  }else{
   synchronized (lock) {
    while(true){
     try {
      Thread.sleep(100);
      lock.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println("EVEN : " + number++);
     lock.notify();
    }
   } 
  }  
 }
}

public class SequenceNumber {
 
 public static void main(String[] args) throws InterruptedException {
  Numbers obj = new Numbers();

  Thread t1 = new Thread(obj, "even");
  Thread t2 = new Thread(obj, "odd");
  t1.start();
  Thread.sleep(500);
  t2.start();
 } 
}

OUTPUT:

ODD  : 1
EVEN : 2
ODD  : 3
EVEN : 4
ODD  : 5
EVEN : 6
ODD  : 7
EVEN : 8
ODD  : 9
EVEN : 10
ODD  : 11
EVEN : 12
ODD  : 13
EVEN : 14
ODD  : 15
EVEN : 16
ODD  : 17
EVEN : 18
ODD  : 19
EVEN : 20
ODD  : 21
EVEN : 22
ODD  : 23
EVEN : 24
ODD  : 25