Java Programming Examples

X




Resources > Java Program Examples > {{currentSubTopic}}

Program to demonstrate Array sort and insert


 
import java.util.Arrays;

public class BloombenchArraySortAndInsert {
   public static void main(String args[]) throws Exception {
      int array[] = { 12,15, -22, 61, -13, 81, 0, -17, -91, 41 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 1);
      System.out.println("Didn't find 1 @ "
      + index);
      int newIndex = -index - 1;
      array = insertElement(array, 1, newIndex);
      printArray("With 1 added", array);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message
      + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if (i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);         
      }
      System.out.println();
   }
   private static int[] insertElement(int original[],
   int element, int index) {
      int length = original.length;
      int destination[] = new int[length + 1];
      System.arraycopy(original, 0, destination, 0, index);
      destination[index] = element;
      System.arraycopy(original, index, destination, index
      + 1, length - index);
      return destination;
   }
}

Output

Program to Merge two arrays


 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BloombenchMergeTwoArray {
   public static void main(String args[]) {
      String a[] = { "B", "L", "O","O", "M" };
      String b[] = { "B", "E","N", "C", "H" };
      List list = new ArrayList(Arrays.asList(a));
      list.addAll(Arrays.asList(b));
      Object[] c = list.toArray();
      System.out.println(Arrays.toString(c));
   }
}

Output

Program to Search min and max


 
import java.util.Arrays;
import java.util.Collections;

public class BloombenchSearchMinMax {
   public static void main(String[] args) {
      Integer[] numbers = { 18, 21, 17, 11, 14, 91, 15};
      int min = (int) Collections.min(Arrays.asList(numbers));
      int max = (int) Collections.max(Arrays.asList(numbers));
      System.out.println("Min number: " + min);
      System.out.println("Max number: " + max);
   }
}

Output

Program to Remove an array from another array


 
import java.util.ArrayList;

public class BloombenchRemoveArrayFromAnotherArray {
   public static void main(String[] args)  {
      ArrayList objArray = new ArrayList();
      ArrayList objArray2 = new ArrayList();
      objArray2.add(0,"common1");
      objArray2.add(1,"common2");
      objArray2.add(2,"notcommon");
      objArray2.add(3,"notcommon1");
      objArray.add(0,"common1");
      objArray.add(1,"common2");
      objArray.add(2,"notcommon2");
      System.out.println("Array elements of array1" +objArray);
      System.out.println("Array elements of array2" +objArray2);
      objArray.removeAll(objArray2);
      System.out.println("Array1 after removing array2 from array1"+objArray);
   }
}

Output

Program to format time


 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BloombenchDateFormatter{
   public static void main(String[] args){

        String startDateString = "1/1/2018";
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
        Date startDate;
        try {
            startDate = df.parse(startDateString);
            String newDateString = df.format(startDate);
            System.out.println(newDateString);
        } catch (Exception e) {
            e.printStackTrace();
        }

   }
}

Output

Program to solve Tower of Hanoi


 
public class BloombenchTowerOfHanoi {
   public static void main(String[] args) {
      int nDisks = 3;
      placeDisk(nDisks, 'A', 'B', 'C');
   }
   public static void placeDisk(int topN, char from,
   char inter, char to) {
      if (topN == 1){
         System.out.println("Disk 1 from "
         + from + " to " + to);
      }else {
         placeDisk(topN - 1, from, to, inter);
         System.out.println("Disk "
         + topN + " from " + from + " to " + to);
         placeDisk(topN - 1, inter, from, to);
      }
   }
}

Output

Program to calculate Fibonacci Series


 
public class BloombenchFibonacci {
   public static long fibonacci(long number) {
      if ((number == 0) || (number == 1))
         return number;
      else
         return fibonacci(number - 1) + fibonacci(number - 2);
   }
   public static void main(String[] args) {
      for (int counter = 10; counter <= 20; counter++){
         System.out.printf("Fibonacci of %d is: %d\n",
         counter, fibonacci(counter));
      }
   }
}

Output

Program to calculate Factorial


 
public class BloombenchFactorial {
   public static void main(String args[]) {
      for (int counter = 0; counter <= 10; counter++){
         System.out.printf("%d! = %d\n", counter,
         factorial(counter));
      }
   }
   public static long factorial(long number) {
      if (number <= 1)
         return 1;
      else
         return number * factorial(number - 1);
   }
}

Output

Program to demonstrate Use of break statement


 
public class BloombenchUseBreak {
   public static void main(String[] args) {
      int[] intary = { 1,3,22,15,45,11,33,9 };
      int no = 11;
      int i = 0;
      boolean found = false;
      for ( ; i < intary.length; i++) {
         if (intary[i] == no) {
            found = true;
            break;
         }
      }
      if (found) {
         System.out.println("Found the no: " + no 
         + " at  index: " + i);
      } 
      else {
         System.out.println(no + "not found  in the array");
      }
   }
}

Output

Program to demonstrate Use of continue


 
public class BloombenchUseContinue {
   public static void main(String[] args) {
      StringBuffer searchstr = new StringBuffer("At Bloombench each student gets personal attention and a customised learning experience.");
      int length = searchstr.length();
      int count = 0;
      
      for (int i = 0; i < length; i++) {
         if (searchstr.charAt(i) != 'h')
         continue;
         count++;
         searchstr.setCharAt(i, 'h');
      }
      System.out.println("Found " + count  + " h's in the string.");
      System.out.println(searchstr);
   }
}

Output

Program to Append String to a File


 
import java.io.*;

public class BloombenchAppendStringToFile {
   public static void main(String[] args) throws Exception {
      try {
         BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
         out.write("The two-way interaction between the teacher and ");
         out.close();
         out = new BufferedWriter(new FileWriter
         ("outfilename",true));
         out.write("the student provides for a true learning experience.");
         out.close();
         BufferedReader in = new BufferedReader
         (new FileReader("outfilename"));
         String str;
         while ((str = in.readLine()) != null) {
            System.out.println(str);
         }
          in.close();
      }
      catch (IOException e) {
         System.out.println("exception occoured"+ e);
      }
   }
}

Output

Program to Create directories recursively


 
import java.io.File;

public class BloombenchCreateDirectory {
   public static void main(String[] args) {
      String directories = "\\a\\b\\c\\d\\e\\f\\g\\h\\i";
      File file = new File(directories);
      boolean result = file.mkdirs();
      System.out.println("Status = " + result);
   }
}

Output

Program to demonstrate Directory Hierarchy


 
import java.io.File;
import java.io.IOException;

public class BloombenchDirHierarchy {
   public static void main(String[] a)throws IOException{
      showDir(1, new File("."));
   }
   static void showDir(int indent, File file) 
   throws IOException {
      for (int i = 0; i < indent; i++)
         System.out.print('-');
      System.out.println(file.getName());
      if (file.isDirectory()) {
         File[] files = file.listFiles();
         for (int i = 0; i < files.length; i++)
            showDir(indent + 4, files[i]);
      }
   }
}

Output

Program to demonstrate User defined Exception


 
class WrongInputException extends Exception {
   WrongInputException(String s) {
      super(s);
   }
}
class Input {
   void method() throws WrongInputException {
      throw new WrongInputException("Wrong input");
   }
}
public class BloombenchUserDefinedException {
   public static void main(String[] args){
      try {
         new Input().method();
      }
	  catch(WrongInputException wie) {
         System.out.println(wie.getMessage());
      }
   } 
}

Output

Program to demonstrate Use of Finally


 
public class BloombenchUseOfFinally {
   public static void main(String[] argv) {
      new BloombenchUseOfFinally().doTheWork();
   }
   public void doTheWork() {
      Object o = null;
      for (int i=0; i<5; i++) {
         try {
            o = makeObj(i);
         }
         catch (IllegalArgumentException e) {
            System.err.println
            ("Error: ("+ e.getMessage()+").");
            return;   
         }
         finally {
            System.err.println("All done");
            if (o==null)
            System.exit(0);
        }
        System.out.println(o); 
      }
   }
   public Object makeObj(int type) 
   throws IllegalArgumentException {
      if (type == 1)  
      throw new IllegalArgumentException
      ("Don't like type " + type);
      return new Object();
   }
}

Output

Program to demonstrate Runtime Exceptions


 
public class BloombenchNeverCaught {
   static void foo() {
      throw new RuntimeException("From foo()");
   }
   static void bar() {
      foo();
   }
   public static void main(String[] args) {
      bar();
   }
}

Output

Program to demonstrate Summation of Numbers


 
import java.io.IOException;

public class AdditionStack {
   static int num;
   static int ans;
   static Stack theStack;
   public static void main(String[] args)
   throws IOException {
      num = 50;
      stackAddition();
      System.out.println("Sum=" + ans);
   }
   public static void stackAddition() {
      theStack = new Stack(10000); 
      ans = 0; 
      while (num > 0) {
         theStack.push(num); 
         --num; 
      }
      while (!theStack.isEmpty()) {
         int newN = theStack.pop(); 
         ans += newN; 
      }
   }
}

class Stack {
   private int maxSize; 
   private int[] data;
   private int top; 
   public Stack(int s) {
      maxSize = s;
      data = new int[maxSize];
      top = -1;
   }
   public void push(int p) {
      data[++top] = p;
   }
   public int pop() {
      return data[top--];
   }
   public int peek() {
      return data[top];
   }
   public boolean isEmpty() {
      return (top == -1);
   }
}

Output

Program to demonstrate Infix to Postfix


 
import java.io.IOException;

public class InToPost {
   private Stack theStack;
   private String input;
   private String output = "";
   public InToPost(String in) {
      input = in;
      int stackSize = input.length();
      theStack = new Stack(stackSize);
   }
   public String doTrans() {
      for (int j = 0; j < input.length(); j++) {
         char ch = input.charAt(j);
         switch (ch) {
            case '+': 
            case '-':
            gotOper(ch, 1); 
            break; 
            case '*': 
            case '/':
            gotOper(ch, 2); 
            break; 
            case '(': 
            theStack.push(ch);
            break;
            case ')': 
            gotParen(ch); 
            break;
            default: 
            output = output + ch; 
            break;
         }
      }
      while (!theStack.isEmpty()) {
         output = output + theStack.pop();
      }
     // System.out.println(output);
      return output; 
   }
   public void gotOper(char opThis, int prec1) {
      while (!theStack.isEmpty()) {
         char opTop = theStack.pop();
         if (opTop == '(') {
            theStack.push(opTop);
            break;
         }
         else {
            int prec2;
            if (opTop == '+' || opTop == '-')
            prec2 = 1;
            else
            prec2 = 2;
            if (prec2 < prec1) { 
               theStack.push(opTop);
               break;
            }
		    else
            output = output + opTop;
         }
      }
      theStack.push(opThis);
   }
   public void gotParen(char ch){ 
      while (!theStack.isEmpty()) {
         char chx = theStack.pop();
         if (chx == '(') 
         break; 
         else
         output = output + chx; 
      }
   }
   public static void main(String[] args) 
   throws IOException {
      String input = "2+3*5/6-8+4/7";
      String output;
      InToPost theTrans = new InToPost(input);
      output = theTrans.doTrans(); 
      System.out.println("Postfix is " + output + '\n');
   }
   class Stack {
      private int maxSize;
      private char[] stackArray;
      private int top;
      public Stack(int max) {
         maxSize = max;
         stackArray = new char[maxSize];
         top = -1;
      }
      public void push(char j) {
         stackArray[++top] = j;
      }
      public char pop() {
         return stackArray[top--];
      }
      public char peek() {
         return stackArray[top];
      }
      public boolean isEmpty() {
         return (top == -1);
     }
   }
}

Output

Program to demonstrate Queue Implementation


 
import java.util.LinkedList;

class GenQueue<E> {
   private LinkedList<E> list = new LinkedList<E>();
   public void enqueue(E item) {
      list.addLast(item);
   }
   public E dequeue() {
      return list.poll();
   }
   public boolean hasItems() {
      return !list.isEmpty();
   }
   public int size() {
      return list.size();
   }
   public void addItems(GenQueue<? extends E> q) {
      while (q.hasItems())
         list.addLast(q.dequeue());
   }
}
public class GenQueueTest {
   public static void main(String[] args) {
      GenQueue<Employee> empList;
      empList = new GenQueue<Employee>();
      GenQueue<HourlyEmployee> hList;
      hList = new GenQueue<HourlyEmployee>();
      hList.enqueue(new HourlyEmployee("T", "D"));
      hList.enqueue(new HourlyEmployee("G", "B"));
      hList.enqueue(new HourlyEmployee("F", "S"));
      empList.addItems(hList);
      System.out.println("The employees' names are:");
      while (empList.hasItems()) {
         Employee emp = empList.dequeue();
         System.out.println(emp.firstName + " " 
         + emp.lastName);
      }
   }
}

class Employee {
   public String lastName;
   public String firstName;
   public Employee() {
   }
   public Employee(String last, String first) {
      this.lastName = last;
      this.firstName = first;
   }
   public String toString() {
      return firstName + " " + lastName;
   }
}

class HourlyEmployee extends Employee {
   public double hourlyRate;
   public HourlyEmployee(String last, String first) {
      super(last, first);
   }
}

Output

Program to demonstrate String reversal using stack


 
import java.io.IOException;

public class StringReverserThroughStack {
   private String input; 
   private String output;
   public StringReverserThroughStack(String in) {
      input = in;
   }
   public String doRev() {
      int stackSize = input.length(); 
      Stack theStack = new Stack(stackSize); 
      for (int i = 0; i < input.length(); i++) {
         char ch = input.charAt(i); 
         theStack.push(ch); 
      }
      output = "";
      while (!theStack.isEmpty()) {
         char ch = theStack.pop(); 
         output = output + ch; 
      }
      return output;
   }
   public static void main(String[] args) 
   throws IOException {
      String input = "Bloombench - Personalized Learning";
      String output;
      StringReverserThroughStack theReverser = 
      new StringReverserThroughStack(input);
      output = theReverser.doRev();
      System.out.println("Reversed: " + output);
   }
   class Stack {
      private int maxSize;
      private char[] stackArray;
      private int top;
      public Stack(int max) {
         maxSize = max;
         stackArray = new char[maxSize];
         top = -1;
      }
      public void push(char j) {
         stackArray[++top] = j;
      }
      public char pop() {
         return stackArray[top--];
      }
      public char peek() {
         return stackArray[top];
      }
      public boolean isEmpty() {
         return (top == -1);
      }
   }
}

Output

Program to demonstrate Read-only Collection


 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ReadOnlyCollection {
   public static void main(String[] argv) 
   throws Exception {
      List stuff = Arrays.asList(new String[] { "a", "b" });
      List list = new ArrayList(stuff);
      list = Collections.unmodifiableList(list);
      try {
         list.set(0, "new value");
      } 
	  catch (UnsupportedOperationException e) {
      }
      Set set = new HashSet(stuff);
      set = Collections.unmodifiableSet(set);
      Map map = new HashMap();
      map = Collections.unmodifiableMap(map);
      System.out.println("Collection is read-only now.");
   }
}

Output

Program to Iterate through HashMap


 
import java.util.*;

public class BloombenchHashMapIterator {
   public static void main(String[] args) {
      HashMap< String, String> hMap = new HashMap< String, String>();
      hMap.put("1", "One");
      hMap.put("2", "Two");
      hMap.put("3", "Three");
      Collection cl = hMap.values();
      Iterator itr = cl.iterator();
      while (itr.hasNext()) {
         System.out.println(itr.next());
     }
   }
}

Output

Program to Use Collections


 
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;


public class UseAllCollection {
   public static void main(String[] args) {
      List lnkLst = new LinkedList();
      lnkLst.add("element1");
      lnkLst.add("element2");
      lnkLst.add("element3");
      lnkLst.add("element4");
      displayAll(lnkLst);
      List aryLst = new ArrayList();
      aryLst.add("A");
      aryLst.add("B");
      aryLst.add("C");
      aryLst.add("D");
      displayAll(aryLst);
      Set hashSet = new HashSet();
      hashSet.add("set1");
      hashSet.add("set2");
      hashSet.add("set3");
      hashSet.add("set4");
      displayAll(hashSet);
      SortedSet treeSet = new TreeSet();
      treeSet.add("11");
      treeSet.add("12");
      treeSet.add("13");
      treeSet.add("14");
      displayAll(treeSet);
      LinkedHashSet lnkHashset = new LinkedHashSet();
      lnkHashset.add("one");
      lnkHashset.add("two");
      lnkHashset.add("three");
      lnkHashset.add("four");
      displayAll(lnkHashset);
      Map map1 = new HashMap();
      map1.put("key1", "W");
      map1.put("key2", "X");
      map1.put("key3", "Y");
      map1.put("key4", "Z");
      displayAll(map1.keySet());
      displayAll(map1.values());
      SortedMap map2 = new TreeMap();
      map2.put("key1", "ABCD");
      map2.put("key2", "EFGH");
      map2.put("key3", "IJKL");
      map2.put("key4", "MNOP");
      displayAll(map2.keySet());
      displayAll(map2.values());
      LinkedHashMap map3 = new LinkedHashMap();
      map3.put("key1", "1234");
      map3.put("key2", "5678");
      map3.put("key3", "9999");
      map3.put("key4", "0000");
      displayAll(map3.keySet());
      displayAll(map3.values());
   }
   static void displayAll(Collection col) {
      Iterator itr = col.iterator();
      while (itr.hasNext()) {
         String str = (String) itr.next();
         System.out.print(str + " ");
      }
      System.out.println();
   }
}

Output

Program to Host Specific IP Address


 
import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIP {
   public static void main(String[] args) {
      InetAddress address = null;
      try {
         address = InetAddress.getByName
         ("www.google.com");
      }
	  catch (UnknownHostException e) {
         System.exit(2);
      }
      System.out.println(address.getHostName() + "="
      + address.getHostAddress());
      System.exit(0);
   }
}

Output

Program to get connected to Server


 
import java.net.InetAddress;
import java.net.Socket;

public class WebPing {
   public static void main(String[] args) {
      try {
         InetAddress addr;
         Socket sock = new Socket("www.google.com", 80);
         addr = sock.getInetAddress();
         System.out.println("Connected to " + addr);
         sock.close();
      } catch (java.io.IOException e) {
         System.out.println("Can't connect to " + args[0]);
         System.out.println(e);
      }
   }
}

Output

Program to solve Deadlock


 
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;

public class DeadlockDetectingLock extends ReentrantLock {
   private static List deadlockLocksRegistry 
   = new ArrayList();
   private static synchronized void 
   registerLock(DeadlockDetectingLock ddl) {
      if (!deadlockLocksRegistry.contains(ddl)) 
      deadlockLocksRegistry.add(ddl);
   }
   private static synchronized void 
   unregisterLock(DeadlockDetectingLock ddl) {
      if (deadlockLocksRegistry.contains(ddl))
      deadlockLocksRegistry.remove(ddl);
   }
   private List hardwaitingThreads = new ArrayList();
   private static synchronized void 
   markAsHardwait(List l, Thread t) {
   if (!l.contains(t))
   l.add(t);
}

private static synchronized void 
freeIfHardwait(List l, Thread t) {
   if (l.contains(t))
   l.remove(t);
}

private static Iterator getAllLocksOwned(Thread t) {
   DeadlockDetectingLock current;
   ArrayList results = new ArrayList();
   Iterator itr = deadlockLocksRegistry.iterator();
   while (itr.hasNext()) {
      current = (DeadlockDetectingLock) itr.next();
      if    (current.getOwner() == t)
      results.add(current);
   }
   return results.iterator();
}

private static Iterator 
getAllThreadsHardwaiting(DeadlockDetectingLock l) {
   return l.hardwaitingThreads.iterator();
}

private static synchronized boolean canThreadWaitOnLock
(Thread t,DeadlockDetectingLock l) {
   Iterator locksOwned = getAllLocksOwned(t);
   while (locksOwned.hasNext()) {
      DeadlockDetectingLock current 
      = (DeadlockDetectingLock) locksOwned.next();
      if (current == l)
      return false;
      Iterator waitingThreads 
      = getAllThreadsHardwaiting(current);
      while (waitingThreads.hasNext()) {
         Thread otherthread = (Thread) waitingThreads.next();
         if (!canThreadWaitOnLock(otherthread, l)) {
            return false;
         }
      }
   }
   return true;
}

public DeadlockDetectingLock() {
   this(false, false);
}

public DeadlockDetectingLock(boolean fair) {
   this(fair, false);
}

private boolean debugging;

public DeadlockDetectingLock(boolean fair, boolean debug) {
   super(fair);
   debugging = debug;
   registerLock(this);
}

public void lock() {
   if (isHeldByCurrentThread()) {
      if (debugging)
      System.out.println("Already Own Lock");
      super.lock();
      freeIfHardwait(hardwaitingThreads, 
      Thread.currentThread());
      return;
   }
   markAsHardwait(hardwaitingThreads, 
   Thread.currentThread());
   if (canThreadWaitOnLock(Thread.currentThread(), this)) {
      if (debugging)
      System.out.println("Waiting For Lock");
      super.lock();
      freeIfHardwait(hardwaitingThreads, 
      Thread.currentThread()); 
      if (debugging)
      System.out.println("Got New Lock");
   }
   else {
      throw new DeadlockDetectedException("DEADLOCK");
   }
}

public void lockInterruptibly() throws InterruptedException {
   lock();
}


public class DeadlockDetectingCondition implements Condition {
   Condition embedded;
   protected DeadlockDetectingCondition(ReentrantLock lock,
   Condition embedded) {
      this.embedded = embedded;
   }

   public void await() throws InterruptedException {
      try {
         markAsHardwait(hardwaitingThreads, 
         Thread.currentThread());
         embedded.await();
      }
      finally {
         freeIfHardwait(hardwaitingThreads, 
         Thread.currentThread());
      }
   }

   public void awaitUninterruptibly() {
      markAsHardwait(hardwaitingThreads, 
      Thread.currentThread());
      embedded.awaitUninterruptibly();
      freeIfHardwait(hardwaitingThreads, 
      Thread.currentThread());
   }

   public long awaitNanos(long nanosTimeout) 
      throws InterruptedException {
      try {
         markAsHardwait(hardwaitingThreads, 
         Thread.currentThread());
         return embedded.awaitNanos(nanosTimeout);
      }
      finally {
         freeIfHardwait(hardwaitingThreads, 
         Thread.currentThread());
      }
   }

   public boolean await(long time, TimeUnit unit)
   throws InterruptedException {
      try {
         markAsHardwait(hardwaitingThreads, 
         Thread.currentThread());
         return embedded.await(time, unit);
      }
      finally {
         freeIfHardwait(hardwaitingThreads, 
         Thread.currentThread());
      } 
   }

   public boolean awaitUntil(Date deadline) 
   throws InterruptedException {
      try {
         markAsHardwait(hardwaitingThreads, 
         Thread.currentThread());
         return embedded.awaitUntil(deadline);
      }
      finally {
         freeIfHardwait(hardwaitingThreads, 
         Thread.currentThread());
      }
   }

   public void signal() {
      embedded.signal();
   }

   public void signalAll() {
      embedded.signalAll();
   }
}

public Condition newCondition() {
   return new DeadlockDetectingCondition(this, 
   super.newCondition());
}

private static Lock a = new DeadlockDetectingLock(false, true);
private static Lock b = new DeadlockDetectingLock(false, true);
private static Lock c = new DeadlockDetectingLock(false, true);
private static Condition wa = a.newCondition();
private static Condition wb = b.newCondition();
private static Condition wc = c.newCondition();
private static void delaySeconds(int seconds) {
   try {
      Thread.sleep(seconds * 1000);
   }
   catch (InterruptedException ex) {
   }
}

private static void awaitSeconds(Condition c, int seconds) {
   try {
      c.await(seconds, TimeUnit.SECONDS);
   }
   catch (InterruptedException ex) {
   }
}

private static void testOne() {
   new Thread(new Runnable() {
      public void run() {
         System.out.println("thread one grab a");
         a.lock();
         delaySeconds(2);
         System.out.println("thread one grab b");
         b.lock();
         delaySeconds(2);
         a.unlock();
         b.unlock();
      }
   }).start();
   new Thread(new Runnable() {
      public void run() {
         System.out.println("thread two grab b");
         b.lock();
         delaySeconds(2);
         System.out.println("thread two grab a");
         a.lock();
         delaySeconds(2);
         a.unlock();
         b.unlock();
      }
   }).start();
}

private static void testTwo() {
   new Thread(new Runnable() {
      public void run() {
         System.out.println("thread one grab a");
         a.lock();
         delaySeconds(2) ;
         System.out.println("thread one grab b");
         b.lock();
         delaySeconds(10); 
         a.unlock();
         b.unlock();
      }
   }).start();
   new Thread(new Runnable() {
      public void run() {
         System.out.println("thread two grab b");
         b.lock();
         delaySeconds(2);
         System.out.println("thread two grab c");
         c.lock();
         delaySeconds(10);
         b.unlock();
         c.unlock();
      }
   }).start();
   new Thread(new Runnable() {
      public void run() {
         System.out.println("thread three grab c");
         c.lock();
         delaySeconds(4);
         System.out.println("thread three grab a");
         a.lock();
         delaySeconds(10);
         c.unlock();
         a.unlock();
      }
   }).start();
}

private static void testThree() {
   new Thread(new Runnable() {
      public void run() {
         System.out.println("thread one grab b");
         b.lock();
         System.out.println("thread one grab a");
         a.lock();
         delaySeconds(2);
         System.out.println("thread one waits on b");
         awaitSeconds(wb, 10);
         a.unlock();
         b.unlock();
      }
   }).start();
   new Thread(new Runnable() {
      public void run() {
         delaySeconds(1);
         System.out.println("thread two grab b");
         b.lock();
         System.out.println("thread two grab a");
         a.lock();
         delaySeconds(10);
         b.unlock();
         c.unlock();
      }
   }).start();
}

public static void main(String args[]) {
   int test = 1;
   if (args.length > 0)
   test = Integer.parseInt(args[0]);
   switch (test) {
      case 1:
      testOne();
      break;
      case 2:
      testTwo(); 
      break; 
      case 3:
      testThree();
      break;
      default:
      System.err.println("usage: java  DeadlockDetectingLock [ test# ]");
   }
   delaySeconds(60);
   System.out.println("--- End Program ---");
   System.exit(0);
   }
}

class DeadlockDetectedException extends RuntimeException {
   public DeadlockDetectedException(String s) {
      super(s);
   }
}

Output

Program to demonstrate Producer Consumer Problem


 
public class ProducerConsumerTest {
   public static void main(String[] args) {
      CubbyHole c = new CubbyHole();
      Producer p1 = new Producer(c, 1);
      Consumer c1 = new Consumer(c, 1);
      p1.start(); 
      c1.start();
   }
}
class CubbyHole {
   private int contents;
   private boolean available = false;
   public synchronized int get() {
      while (available == false) {
         try {
            wait();
         }
         catch (InterruptedException e) {
         }
      }
      available = false;
      notifyAll();
      return contents;
   }
   public synchronized void put(int value) {
      while (available == true) {
         try {
            wait();
         }
         catch (InterruptedException e) { 
         } 
      }
      contents = value;
      available = true;
      notifyAll();
   }
}

class Consumer extends Thread {
   private CubbyHole cubbyhole;
   private int number;
   public Consumer(CubbyHole c, int number) {
      cubbyhole = c;
      this.number = number;
   }
   public void run() {
      int value = 0;
         for (int i = 0; i < 10; i++) {
            value = cubbyhole.get();
            System.out.println("Consumer #" 
			
+ " got: " + value);
		}
	}
}

class Producer extends Thread {
	private CubbyHole cubbyhole;
	private int number;

	public Producer(CubbyHole c, int number) {
		cubbyhole = c;
		this.number = number;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			cubbyhole.put(i);
			System.out.println("Producer #" 
			+ " put: " + i);
			try {
				sleep((int)(Math.random() * 100));
			} catch (InterruptedException e) { }
		}
	}
}

Output

Program to Validate email address format


 
public class validateEmail {
   public static void main(String[] args) {
      String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
      String email1 = "user@xyz.com";
      Boolean b = email1.matches(EMAIL_REGEX);
      System.out.println("is e-mail: "+email1+" :Valid = " + b);
      String email2 = "user^xyz.co.in";
      b = email2.matches(EMAIL_REGEX);
      System.out.println("is e-mail: "+email2+" :Valid = " + b);
   }
}

Output

Program to demonstrate Generics


 
public class GenericMethodTest
{
   // generic method printArray                         
   public static < E > void printArray( E[] inputArray )
   {
      // Display array elements              
         for ( E element : inputArray ){        
            System.out.printf( "%s ", element );
         }
         System.out.println();
    }

    public static void main( String args[] )
    {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 1, 2, 3, 4, 5 };
        Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
        Character[] charArray = { 'B', 'L', 'O', 'O', 'M', 'B', 'E', 'N', 'C', 'H' };

        System.out.println( "Array integerArray contains:" );
        printArray( intArray  ); // pass an Integer array

        System.out.println( "\nArray doubleArray contains:" );
        printArray( doubleArray ); // pass a Double array

        System.out.println( "\nArray characterArray contains:" );
        printArray( charArray ); // pass a Character array
    } 
}

Output

Program to name


 
code

Output