Postfix Calculator in Java

Element.java

package com.tutorial;

public interface Element {
}

NumberElement.java

package com.tutorial;

public class NumberElement implements Element {
	Double number;
	public Double getNumber() {
		return number;
	}

	public NumberElement(String number) {
		this.number = Double.parseDouble(number);
	}
	
	public String toString()
	{
		return ((Integer)number.intValue()).toString();
	}
}

OperatorElement.java

package com.tutorial;

public class OperatorElement implements Element{
	static public enum OperatorType {MULTIPLY, DIVIDE, ADD, SUBTRACT, EXPONENTIAL, OPAREN, CPAREN};
	OperatorType type;
	Character c;
	public OperatorElement(Character operator) {
		c = operator;
		if(operator == '+')
			type = OperatorType.ADD;
		else if(operator == '-')
			type = OperatorType.SUBTRACT;
		else if(operator == '*')
			type = OperatorType.MULTIPLY;
		else if(operator == '/')
			type = OperatorType.DIVIDE;
		else if(operator == '^')
			type = OperatorType.EXPONENTIAL;
		else if(operator == '(')
			type = OperatorType.OPAREN;
		else if(operator == ')')
			type = OperatorType.CPAREN;
	}
	
	public String toString()
	{
		return c.toString();
	}
}

Parser.java

package com.tutorial;

import java.util.Collection;
import java.util.Vector;

public class Parser {
	Vector <Element> e = new Vector<Element>();
	public Collection<Element> Parse(String s)
	{
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < s.length(); i++)
		{
			Character c = s.charAt(i);
			if(Character.isDigit(c))
				sb.append(c);
			if(i + 1 < s.length())
			{
				Character d = s.charAt(i + 1);
				if(Character.isDigit(d) == false && sb.length() > 0)
				{
					e.add(new NumberElement(sb.toString()));
					//clears stringbuilder
					sb.delete(0, sb.length());
				}
			}
			
			if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
					|| c == '(' || c == ')')
				e.add(new OperatorElement(c));
		}
		if(sb.length() > 0)
			e.add(new NumberElement(sb.toString()));
		
		return e;
	}
}

InfixToPostfix.java

package com.tutorial;

import java.util.Collection;
import java.util.Stack;
import java.util.Vector;

import com.tutorial.OperatorElement.OperatorType;

public class InfixToPostfix {
	Vector <Element> converted = new Vector<Element>();
	int Precedence(OperatorElement c)
	{
		if(c.type == OperatorType.EXPONENTIAL)
			return 2;
		else if(c.type == OperatorType.MULTIPLY || c.type == OperatorType.DIVIDE)
			return 3;
		else if(c.type == OperatorType.ADD || c.type == OperatorType.SUBTRACT)
			return 4;
		else
			return Integer.MAX_VALUE;
	}
	
	public void ProcessOperators(Stack<Element> st, Element element, Element top)
	{
		while(st.size() > 0 && Precedence((OperatorElement)element) >= Precedence((OperatorElement)top))
		{
			Element p = st.pop();
			if(((OperatorElement)p).type == OperatorType.OPAREN)
				break;
			converted.add(p);
			if(st.size() > 0)
				top = st.lastElement();
		}
	}
	public Collection<Element> ConvertFromInfixToPostFix(Collection<Element> e)
	{
		Vector <Element> stack1 = new Vector<Element>(e);
		Stack<Element> st = new Stack<Element>();
		for(int i = 0; i < stack1.size(); i++)
		{
			Element element = stack1.elementAt(i);
			if(element instanceof OperatorElement)
			{
				if(st.empty() ||
						((OperatorElement)element).type == OperatorType.OPAREN)
					st.push(element);
				else
				{
					Element top = st.lastElement();
					if(((OperatorElement)element).type == OperatorType.CPAREN)
						ProcessOperators(st, element, top);
					else if(Precedence((OperatorElement)element) < Precedence((OperatorElement)top))
						st.push(element);
					else
					{
						ProcessOperators(st, element, top);
						st.push(element);
					}
				}
			}
			else
				converted.add(element);
		}
		
		//pop all operators in stack
		while(st.size() > 0)
		{
			Element b1 = st.pop();
			converted.add(b1);
		}
		
		return converted;
	}
	
	public String toString()
	{
		StringBuilder s = new StringBuilder();
		for(int j = 0; j < converted.size(); j++)
			s.append(converted.elementAt(j) + " ");
		return s.toString();
	}
}

PostFixEvaluator.java

package com.tutorial;

import java.util.Collection;
import java.util.Stack;
import java.util.Vector;

import com.tutorial.OperatorElement.OperatorType;

public class PostFixEvaluator {
	Stack<Element> stack = new Stack<Element>();
	
	NumberElement calculate(NumberElement left, NumberElement right, OperatorElement op)
	{
		Double temp = Double.MAX_VALUE;
		if(op.type == OperatorType.ADD)
			temp = left.getNumber() + right.getNumber();
		else if(op.type == OperatorType.SUBTRACT)
			temp = left.getNumber() - right.getNumber();
		else if(op.type == OperatorType.MULTIPLY)
			temp = left.getNumber() * right.getNumber();
		else if(op.type == OperatorType.DIVIDE)
			temp = left.getNumber() / right.getNumber();
		else if(op.type == OperatorType.EXPONENTIAL)
			temp = Math.pow(left.getNumber(), right.getNumber());
		
		return new NumberElement(temp.toString());
	}
	public Double Evaluate(Collection<Element> e)
	{
		Vector <Element> v = new Vector<Element>(e);
		for(int i = 0; i < v.size(); i++)
		{
			Element element = v.elementAt(i);
			if(element instanceof NumberElement)
				stack.push(element);
			if(element instanceof OperatorElement)
			{
				NumberElement right = (NumberElement) stack.pop();
				NumberElement left = (NumberElement) stack.pop();
				NumberElement result = calculate(left, right, (OperatorElement)element);
				stack.push(result);
			}
		}
		return ((NumberElement)stack.pop()).getNumber();
	}
}

CalculatorTest.java

package com.tutorial;

import java.util.Collection;

public class CalculatorTest {

	public double Calculate(String s)
	{
		Parser p = new Parser();
		Collection<Element> e = p.Parse(s);
		InfixToPostfix i = new InfixToPostfix();
		e = i.ConvertFromInfixToPostFix(e);
		
		//debugging
		System.out.println("DEBUGGING: " + i.toString());
		//
		
		PostFixEvaluator pfe = new PostFixEvaluator();
		return pfe.Evaluate(e);
	}
	
	public static void main(String[] args) {
		CalculatorTest c = new CalculatorTest();
		double d = c.Calculate("4+6+9*8-(5*6+9)^2");
		System.out.println(d);
	}
}

CSV Parser (using State Machine) in Java

import java.util.ArrayList;

public class CSVParser {

	public enum OPstates
	{
		INITIAL(0),
		NORMAL(1),
		COMMA(2),
		OPEN_QUOTATION(9),
		CLOSE_QUOTATION(4),
		WHITE_SPACE(5),
		QUOTATION_IN_TOKEN(6),
		CLOSE_QUOTATION_IN_TOKEN(8),
		ERROR(-1),
		NEW_LINE(200);

		int i;
		private OPstates(int i) {
			this.i = i;
		}

		public int getValue()
		{
			return i;
		}
	}
	int [][] state = {	{1, 2, 3, 200, 5},      //0 initial state
						{1, 2, -1, 200, 1},     //1 normal character state
						{1, 2, 3, 200, 5},      //2 comma state
						{9, 9, 4, -1, 9},       //3 open quotation
						{-1, 2, 6, 200, 5},     //4 close quotation or quotation in token state
						{1, 2, 3, 200, 5},      //5 whitespace state
						{6, 6, 7, 200, 6},      //6 quotation in token
						{-1, -1, 8, -1, -1},    //7 close quotation
						{9, -1, 4, 200, 9},     //8 close quotation
						{9, 9, 4, -1, 9}        //9 open quotation state
					 };

	ArrayList<String> tokens = new ArrayList<String>();
	int TokenState(char token)
	{
		if(token == ',')
			return 1;
		else if(token == '"')
			return 2;
		else if(token == '\n')
			return 3;
		else if(token == ' ')
			return 4;
		else
			return 0;
	}

	void Parse(String input)
	{
		int curState = 0;
		StringBuilder sb = new StringBuilder();
		for(int i = 0; i < input.length(); i++)
		{
			char tokenChar = input.charAt(i);
			int tokenState = TokenState(tokenChar);
			curState = state[curState][tokenState];
			if(curState == OPstates.NORMAL.getValue() ||
					curState == OPstates.OPEN_QUOTATION.getValue() ||
					curState == OPstates.QUOTATION_IN_TOKEN.getValue() ||
					curState == OPstates.CLOSE_QUOTATION_IN_TOKEN.getValue())
				sb.append(tokenChar);

			if(curState == OPstates.COMMA.getValue() ||
					curState == OPstates.NEW_LINE.getValue())
			{
				tokens.add(sb.toString().trim());
				sb.delete(0, sb.length());

				if(curState == OPstates.NEW_LINE.getValue())
					break;
			}

			if(curState == OPstates.ERROR.getValue())
				throw new RuntimeException("Parse Error");
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();

		for(int i = 0; i < tokens.size(); i++)
			sb.append("Token: " + tokens.get(i) + "\n");

		return sb.toString().trim() + "\n";
	}

	public CSVParser(String input) {
		Parse(input);
	}

	public static void main(String[] args) {
		String s = "   \"a\" ,    \"b,cd\"      ,   c ,\"vb,  n\",\",\"\n";
		System.out.println(s + new CSVParser(s));

		s = "    ,   a,b,\"c, l\",d,,5\n";
		System.out.println(s + new CSVParser(s));

		s = "h,\"john, jr\",a,b,\"c, l\",d,,5,\"e, jr\"\n";
		System.out.println(s + new CSVParser(s));

		s = "\"h, jk\",\"john, jr\",a,b,\"c, l\",d,,5,\"e's, jr\"\n";
		System.out.println(s + new CSVParser(s));

		s = "\"  e   \"\"abc\"\" n \"\"def\"\" \"\"buddy\"\"d\",\"b, jr\",  c dj n\n";
		System.out.println(s + new CSVParser(s));
	}
}

CyclicBarrier in Java

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
	class runnable implements Runnable
	{
		int length;
		int id;
		public runnable(int id, int length) {
			this.length = length;
			this.id = id;
		}
		
		@Override
		public void run() {
			while(true)
			{
				try {
					System.out.println("Doing something for " + length + " seconds");
					Thread.sleep(length * 1000);
					System.out.println("Thread " + id + ": waiting");
					c.await();
				} catch (InterruptedException e) {
					return;
				} catch (BrokenBarrierException e) {
					return;
				}
				if(Thread.interrupted())
					return;
			}
		}
		
	}
	CyclicBarrier c = new CyclicBarrier(3);
	Thread t1;
	Thread t2;
	Thread t3;
	
	public CyclicBarrierTest()
	{
		t1 = new Thread(new runnable(1, 1));
		t2 = new Thread(new runnable(2, 3));
		t3 = new Thread(new runnable(3, 9));
		
		t1.start();
		t2.start();
		t3.start();
	}
	
	public void stop()
	{
		t1.interrupt();
		t2.interrupt();
		t3.interrupt();
	}
	public static void main(String[] args) {
		CyclicBarrierTest b = new CyclicBarrierTest();
		try {
			Thread.sleep(60000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		b.stop();
	}
}

CopyOnWriteArrayList in Java

import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayTest {
	CopyOnWriteArrayList<String> basket = new CopyOnWriteArrayList<String>();
	
	Thread fruit;
	Thread vegatable;
	Thread bean;
	Thread keepSize;
	Thread takeFromBasket;
	
	public CopyOnWriteArrayTest() {
		fruit = new Thread(new Runnable() {
			String [] fruit = {
					"Apple",
					"Apricot",
					"Avocado",
					"Banana",
					"Blackberry",
					"Orange"
			};
			@Override
			public void run() {
				while(true)
				{					
					try {
						for(int i = 0; i < fruit.length; i++)
							basket.add(fruit[i]);
						
						Thread.sleep(1);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		fruit.start();
		
		vegatable = new Thread(new Runnable() {
			String [] vegatable = {
					"Bok choy",
					"Cabbage",
					"Catsear",
					"Celery",
					"Spinach"
			};
			@Override
			public void run() {
				while(true)
				{	
					try {
						for(int i = 0; i < vegatable.length; i++)
							basket.add(vegatable[i]);
						
						Thread.sleep(1);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		vegatable.start();
		
		bean = new Thread(new Runnable() {
			String [] bean = {
					"pea",
					"ricebean",
					"black-eyed pea",
					"soybean",
					"peanuts"
			};
			@Override
			public void run() {
				while(true)
				{
					try {
						for(int i = 0; i < bean.length; i++)
						{
							if(bean[i] == "peanuts")
								System.out.println("Peanuts has been added.");
							basket.add(bean[i]);
						}
						
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		bean.start();
		
		keepSize = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true)
				{
					if(basket.size() > 20)
						basket.remove(0);
					
					if(Thread.interrupted())
						return;
				}
			}
		});
		keepSize.start();
		
		takeFromBasket = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true)
				{
					try {
						int i = basket.indexOf("peanuts");
						if(i != -1)
						{
							basket.remove("peanuts");
							System.out.println("Peanut is found. Size: " + basket.size());
						}
						
						Thread.sleep(1);
					} catch (InterruptedException e) {
						return;
					}
				}
			}
		});
		takeFromBasket.start();
	}
	
	void Stop()
	{
		fruit.interrupt();
		vegatable.interrupt();
		bean.interrupt();
		keepSize.interrupt();
		takeFromBasket.interrupt();
	}
	public static void main(String[] args) throws InterruptedException {
		CopyOnWriteArrayTest c = new CopyOnWriteArrayTest();
		Thread.sleep(120000);
		c.Stop();
	}

}

ArrayBlockingQueue in Java

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class ArrayBlockingQueueTest {
	ArrayBlockingQueue<String> b = new ArrayBlockingQueue<String>(10, true);
	Thread t1;
	Thread t2;
	String text = "India’s recent series of power blackouts, "
			+ "in which 600 million people lost electricity for "
			+ "several days, reminds us of the torrid pace at which "
			+ "populations in the developing world have moved onto "
			+ "the powergrid. Unfortunately, this great transition "
			+ "has been so rapid that infrastructure has mostly been "
			+ "unable to meet demand. India itself has failed to meets "
			+ "its own power capacity addition targets every year since "
			+ "1951. This has left roughly one quarter of the country’s "
			+ "population without any (legal) access to electricity. "
			+ "That’s 300 million people out of a population of 1.2 "
			+ "billion. Indeed, it is the daily attempt of the underserved "
			+ "to access power that may have led to India’s recent grid crash.";
	
	class Writing implements Runnable
	{
		@Override
		public void run() {
			int i = 0;
			String [] p = text.split(" ");
			while(true)
			{
				try {
					b.put(p[i]);
				} catch (InterruptedException e) {
					break;
				}
				i++;
				if(i == p.length)
					i = 0;
			}
		}
	}
	
	class Reading implements Runnable
	{
		@Override
		public void run() {
			while(true)
			{
				try {
					for(int i = 0; i < 5; i++)
					{
						String t = b.poll(500, TimeUnit.MILLISECONDS);
						System.out.print(t + " ");
					}
					Thread.sleep(500);
				} catch (InterruptedException e) {
					break;
				}
			}	
		}
	}
	
	public void Stop()
	{
		t1.interrupt();
		t2.interrupt();
	}
	public ArrayBlockingQueueTest() {
		t1 = new Thread(new Writing());
		t1.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t2 = new Thread(new Reading());
		t2.start();
	}
	
	public static void main(String[] args) throws InterruptedException {
		ArrayBlockingQueueTest a = new ArrayBlockingQueueTest();
		Thread.sleep(6000);
		a.Stop();
	}
}

Semaphore in Java

import java.util.concurrent.*;

public class SemaphoreThread {

	static public class runThreadClass implements Runnable
	{
		Semaphore s;
		int i, count;
		public runThreadClass(int i, Semaphore s) {
			this.i = i;
			count = i + 2;
			this.s = s;
		}
		public void run() {
			try {
				s.acquire();
				System.out.println("Thread " + i + ". Work for " + count + " seconds.");
				Thread.sleep(count * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			s.release();
		}
	}
	public static void main(String[] args) {
		final Semaphore s = new Semaphore(4);
		for(int i = 0; i < 10; i++)
			new Thread(new runThreadClass(i + 1, s)).start();
	}
}

CountDownLatch in Java

import java.util.concurrent.*;

public class CountdownThread {

	public static void main(String[] args) {
		final CountDownLatch signal = new CountDownLatch(4);
		
		class runnable implements Runnable
		{
			int id;
			int length;
			
			public runnable(int id, int length) {
				this.id = id;
				this.length = length;
			}

			@Override
			public void run() {
				try {
					System.out.println("Thread " + id + ". Doing something for " + length + " seconds.");
					Thread.sleep(length * 1000);
					signal.countDown();
					System.out.println("Thread " + id + ". Done. Waiting now.");
					signal.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				System.out.println("Thread " + id + " done.");
			}
		}
		
		new Thread(new runnable(1, 4)).start();
		new Thread(new runnable(2, 3)).start();
		new Thread(new runnable(3, 2)).start();
		new Thread(new runnable(4, 1)).start();
	}
}

Threads using Executors in Java

import java.util.concurrent.*;

public class ThreadsWithExecutor {
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		service.execute(new Runnable() {
			@Override
			public void run() {
				System.out.println("thread1");
			}
		});
		service.execute(new Runnable() {
			@Override
			public void run() {
				System.out.println("thread2");
			}
		});
		service.execute(new Runnable() {
			@Override
			public void run() {
				System.out.println("thread3");
			}
		});
		
		Future<Integer> f = service.submit(new Callable<Integer>() {

			@Override
			public Integer call() throws Exception {				
				return 100;
			}
		});
		
		try {
			System.out.println(f.get());
		} catch (Exception e) {
			e.printStackTrace();
		}

		service.shutdown();
		try {
			service.awaitTermination(100, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println("\nScheduling Thread");
		ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(10);
		scheduledExecutor.schedule(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("This thread runs after 5 seconds wait");
			}
		}, 5, TimeUnit.SECONDS);
		scheduledExecutor.schedule(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("This thread runs after 7 seconds wait");
			}
		}, 7, TimeUnit.SECONDS);
		scheduledExecutor.shutdown();
	}
}

Threading in Java

import java.util.Random;

public class ThreadTutorial {
	
	static class ThreadClass1
	{
		boolean stop = false;
		void DoSomething()
		{
			Random r = new Random();
			r.nextInt();
		}
		
		public synchronized void thinking() 
		{
			DoSomething();
			
			System.out.println("thinking for 2 seconds");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		public synchronized void reading()
		{
			DoSomething();
			
			System.out.println("reading for 1 seconds");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		public ThreadClass1()
		{
			Thread t1 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						thinking();
						if(stop != false)
							break;
					}
				}
			});
			t1.start();
			
			Thread t2 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						reading();
						if(stop != false)
							break;
					}
				}
			});
			t2.start();
			
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			stop = true;
			
			try {
				t1.join();
				t2.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	static class ThreadClass2
	{
		boolean stop = false;
		Object o1 = new Object();
		Object o2 = new Object();
		
		void DoSomething()
		{
			Random r = new Random();
			r.nextInt();
		}
		
		public void readingHarddrive() 
		{
			DoSomething();
			
			synchronized (o1) {
				System.out.println("reading hard drive for 2 seconds");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		public void writingHarddrive()
		{
			DoSomething();
			
			synchronized (o1) {
				System.out.println("writing hard drive for 1 seconds");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}	
			}
		}

		public void readingDatabase() 
		{
			DoSomething();
			
			synchronized (o2) {
				System.out.println("reading database for 5 seconds");
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}	
			}
		}
		public void writingDatabase()
		{
			DoSomething();
			
			synchronized (o2) {
				System.out.println("writing database for 4 seconds");
				try {
					Thread.sleep(4000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}				
			}
		}
		
		public ThreadClass2()
		{
			Thread t1 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						readingDatabase();
						if(stop != false)
							break;
					}
				}
			});
			t1.start();
			
			Thread t2 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						writingDatabase();
						if(stop != false)
							break;
					}
				}
			});
			t2.start();
			
			Thread t3 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						readingHarddrive();
						if(stop != false)
							break;
					}
				}
			});
			t3.start();
			
			Thread t4 = new Thread(new Runnable() {
				@Override
				public void run() {
					while(true)
					{
						writingHarddrive();
						if(stop != false)
							break;
					}
				}
			});
			t4.start();
			
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			stop = true;
			
			try {
				t1.join();
				t2.join();
				t3.join();
				t4.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) throws InterruptedException {
		new ThreadClass1();
		System.out.println("------------------------------------------------------");
		new ThreadClass2();
	}
}			

toString in Java

public class ToStringTest {
	static class Person
	{
		String fname;
		String lname;
		public Person(String fname, String lname) {
			this.fname = fname;
			this.lname = lname;
		}
		
		@Override
		public String toString()
		{
			return fname + " " + lname;
		}
	}
	public static void main(String[] args) {
		Person p = new Person("John", "Smith");
		System.out.println(p);
	}
}