Monday, September 26, 2011

JUnit4 Test

Here's how a unit test can be written using Junit4.

class / test

Tip: look at the console output to follow the flow of execution

Sunday, September 25, 2011

Junit3 Tests

Here is an example of using Junit3 to unit test a class

class / test

Tip: look at the console output to follow the flow of execution (constructor / setup / test / teardown)

Friday, September 16, 2011

Enums and Singleton

Here is an example of using an enum

browse

Hash Map Example

here is an example of how to use a hash map

browse

Thursday, September 15, 2011

Hash Set Example

browse

Linked List Example

Here's an example of how to use a LinkedList. It's very similar to an ArrayList as both implement the List interface.

browse

Array List Example

An example that shows how to use the ArrayList class from java collections. Here we use a list backed by an array.

browse

Checked Exceptions

Checked exceptions must be declared on the method and must be caught (or allowed to raise up) by the caller. Here's an example that creates a checked exception (NoTicketsAvailableException) by extending Exception. The buyTicket() method in Theatre throws this exception when there are no tickets to sell.

browse

package org.megha.blog.example.part9;

/** An exception thrown when no tickets are available */
public class NoTicketsAvailableException extends Exception {
}

package org.megha.blog.example.part9;

/**
 * A theatre that sells tickets.
 */
public class Theatre {

	int availableTickets;

	/** creates a new theatre with a fixed number of tickets */
	public Theatre(int availableTickets) {
		this.availableTickets = availableTickets;
	}

	/**
	 * Sells a ticket to the buyer.
	 *
	 * @return a unique ticket id representing the ticket sold
	 * @throws NoTicketsAvailableException when all tickets are sold out
         */
	public int buyTicket() throws NoTicketsAvailableException {
		if (availableTickets == 0) {
			throw new NoTicketsAvailableException();
		}
		return availableTickets--;
	}

	public static void main(String args[]) {
		// create a new threatre with only 3 seats/tickets
		Theatre theatre = new Theatre(3);

		for (int i = 1; i <= 5; i++) {
			try {
				int ticketId = theatre.buyTicket();
				System.out.println("Ticket #" + i + " is " + ticketId);
			} catch (NoTicketsAvailableException e) {
				System.out.println("Could not buy ticket #" + i);
			}
		}
	}
}

Unchecked Exception

An example that shows how/where an un-checked exception can be thrown. IllegalArgumentException is a sub-class of RuntimeException.

browse

package org.megha.blog.example.part8;

public class MyMath {

	/**
	 * Calculates the average of the numbers provided.
	 *
	 * @param numbers the numbers to average over.
	 * @throws IllegalArgumentException if no numbers a specified
	 */
	public static double average(int... numbers) {
		// note the use of var-args above. java collapses all the arguments into an array
		if (numbers.length == 0) {
			throw new IllegalArgumentException("no numbers to average over!");
		}
		int sum = 0;
		for(int i : numbers) {
			sum = sum + i;
		}
		return ((double) sum) / numbers.length;
	}

	public static void main(String args[]) {

		// averaging works over any number of arguments
		System.out.println(MyMath.average(1, 2, 3, 7, 9, 10));
		System.out.println(MyMath.average(55, 77));
		System.out.println(MyMath.average(3));

		// but when it's called with no arguments, an unchecked exception is thrown.
		// ofcourse, we know about it already, so we have a try/catch block in place.
		// unchecked/runtime exceptions usually happen when some assumed condition, or
		// an api contract is not met by the programmer. eg passing in a null, where
		// null is not expected, or trying to lookup into an array beyond it's bounds.
		try {
			System.out.println(MyMath.average());
		} catch (IllegalArgumentException e) {
			System.out.println("Exception caught: " + e);
		}
		System.out.println("still running... :)");
	}
}

Overriding Methods

A derived class (Tiger) can override methods of a base class (Cat). The overridden methods are called even when a reference to an instance of the derived class (tiger1) is stored in a variable of the base class (cat2).

browse

package org.megha.blog.example.part7;

public class Cat {

    public String whoAmI() {
        return "I am a cat.";
    }
}

package org.megha.blog.example.part7;

public class Tiger extends Cat {
// a tiger is also a cat :)

    @Override
    public String whoAmI() {
        return "I am a tiger.";
    }
}

package org.megha.blog.example.part7;

public class Main {

    public static void main(String args[]) {

        Cat cat1 = new Cat();
        Tiger tiger1 = new Tiger();
        Cat cat2 = tiger1;

        System.out.println(cat1.whoAmI());
        // prints "I am a cat."

        System.out.println(tiger1.whoAmI());
        // prints "I am a tiger."

        System.out.println(cat2.whoAmI());
        // prints "I am a tiger."
    }
}

Abstract Classes

An abstract class for a three dimensional object (ThreeDObject) and two concrete classes (Sphere and Cylinder) derived from that abstract class. The abstract class defines the method getSurfaceToVolumeRatio() which uses the abstract methods getSurfaceArea() and getVolume(). Any ThreeDObject derived class can have it's own mechanism to calculate surface area and volume.

browse

package org.megha.blog.example.part6;

/** 
 * A 3-Dimensional object, which has a surface area, volume and
 * a surface area to volume ratio. This abstract class has a
 * concrete surface-area to volume ratio method implementation
 * which depends on the object specific surface-area and volume
 * definitions.
 */
public abstract class ThreeDObject {

    public abstract double getSurfaceArea();
    public abstract double getVolume();

    public double getSurfaceToVolumeRatio() {
        return getSurfaceArea()/getVolume();
    }
}

package org.megha.blog.example.part6;

/** A sphere with a volume and surface area */
public class Sphere extends ThreeDObject {

    double radius;

    public Sphere(double radius) {
        this.radius = radius;
    }

    @Override
    public double getSurfaceArea() {
        return (4 * Math.PI * radius * radius);
    }

    @Override
    public double getVolume() {
        // note that doing 4 / 3 * Math.PI * radius * radius * radius
        // yields a differnt result as
        // 4 / 3 (integer division) equals 1
                return (4 * Math.PI * radius * radius * radius) / 3;
        }

        @Override
        public String toString() {
                return "sphere radius(" + radius + ")";
        }
}

package org.megha.blog.example.part6;

/** A Cylinder 3-D object */
public class Cylinder extends ThreeDObject {

    private double height;
    private double radius;

    public Cylinder(double height, double radius) {
        this.height = height;
        this.radius = radius;
    }

    @Override
    public double getSurfaceArea() {
           return 2 * Math.PI * radius * (radius + height);
    }

    @Override
    public double getVolume() {
        return Math.PI * radius * radius * height;
    }

    @Override
    public String toString() {
        return "cylinder radius(" + radius + "), height(" + height + ")";
    }
}

package org.megha.blog.example.part6;

/** Creates some ThreeDObjects and prints their details */
public class Main {

    private static void printSurfaceAreaRatio(ThreeDObject obj) {
        System.out.println("------------------");
        System.out.println("for object " + obj);
        System.out.println("surface area " + obj.getSurfaceArea());
        System.out.println("volume " + obj.getVolume());
        System.out.println("surface area to volume ratio " + obj.getSurfaceToVolumeRatio());
    }

    public static void main(String args[]) {
        printSurfaceAreaRatio(new Sphere(1));
        printSurfaceAreaRatio(new Sphere(2));
        printSurfaceAreaRatio(new Cylinder(1, 1));
        printSurfaceAreaRatio(new Cylinder(1, 2));
        printSurfaceAreaRatio(new Cylinder(2, 1));
        printSurfaceAreaRatio(new Cylinder(2, 2));
    }
}

Interfaces

Here's an example to show how an interface (Shape) is defined, implemented (Square, Circle) and used (Main). Note: how Object.toString() is overriden and is used by printInfo()

browse

package org.megha.blog.example.part5;

/** An Interface for a shape that has an area and a perimeter */
public interface Shape {
	public double area();
	public double perimeter();
}

package org.megha.blog.example.part5;

/** A class that represents a circle */
public class Circle implements Shape {

	double radius;

	public Circle(double radius) {
		this.radius = radius;
	}

	public double area() {
		return Math.PI* radius*radius;
	}

	public double perimeter() {
		return 2*Math.PI*radius;
	}

	@Override
	public String toString() {
		return "circle of radius " + radius;
	}
}

package org.megha.blog.example.part5;

/** A square shape */
public class Square implements Shape {

	private double side;

	public Square(double side) {
		this.side = side;
	}

	public double area() {
		return side * side;
	}

	public double perimeter() {
		return 4 * side;
	}

	@Override
	public String toString() {
		return "square of side " + side;
	}
}

package org.megha.blog.example.part5;

/** Creates a square and a circle and prints their area and perimeter */
public class Main {

	private static void printInfo(Shape s) {
		System.out.println("for shape: " + s);
		System.out.println("area: " + s.area());
		System.out.println("perimeter: " + s.perimeter());
	}

	public static void main(String args[]) {
		Square square1 = new Square(5);
		printInfo(square1);

		Circle circle1 = new Circle(7);
		printInfo(circle1);
	}
}
Output of this program:
for shape: square of side 5.0
area: 25.0
perimeter: 20.0
for shape: circle of radius 7.0
area: 153.93804002589985
perimeter: 43.982297150257104

Overloaded Methods

Here's an example that shows how methods can be overloaded.

browse

package org.megha.blog.example.part4;

import org.megha.blog.example.part2.Circle;
import org.megha.blog.example.part3.Person;

/**
 * A printer that can print a {@link Circle} or a {@link Person} or both.
 */
public class Printer {

	public void print(Circle circle) {
		System.out.println("printing circle...");
		circle.print();
	}

	public void print(Person person) {
		System.out.println("printing person...");
		person.print();
	}

	public void print(Circle circle, Person person) {
		System.out.println("printing circle and person");
		person.print();
		circle.print();
	}

	public void print(Person person, Circle circle) {
		System.out.println("printing person and circle");
		person.print();
		circle.print();
	}

	public static void main(String args[]) {

		Printer printer = new Printer();

		Circle circle1 = new Circle(8);
		Person person1 = new Person("Samuel", "Engineer");

		printer.print(circle1);
		printer.print(person1);
		printer.print(circle1, person1);
		printer.print(person1, circle1);
	}
}

Overloaded Constructors

Here's how we can overload constructors - and use any one of them at create time.

browse

package org.megha.blog.example.part3;

/**
 * Represents a person, with a name and a title.
 */
public class Person {

	private String name;
	private String title;

	/** creates a {@link Person} with a name and a title */
	public Person(String name, String title) {
		this.name = name;
		this.title = title;
	}

	/** creates a {@link Person} with only a name (title is set to UNKNOWN) */
	public Person(String name) {
		this(name, "UNKNOWN"); // calls the previous constructor
                                       // with title as UNKNOWN
	}

	/** creates a {@link Person} without a name or a title */
	public Person() {
		this("NO_NAME"); 
                // note how the one-arg constructor is called, 
                // which calls the two arg constructor
	}

	public void print() {
		System.out.println("----------------------");
		System.out.println("Name = " + name);
		System.out.println("Title = " + title);
	}

	public static void main(String args[]) {
		// Person class has overloaded constructors,
                // and we can call any of these.
		Person person1 = new Person();
		Person person2 = new Person("Sam");
		Person person3 = new Person("Sam","Engineer");

		person1.print();
		person2.print();
		person3.print();
	}
}
Output of this program:
----------------------
Name = NO_NAME
Title = UNKNOWN
----------------------
Name = Sam
Title = UNKNOWN
----------------------
Name = Sam
Title = Engineer

Instantiation

This program shows how you create an object/instance of a class, and call methods in the created object.

browse

package org.megha.blog.example.part2;

/**
 * A Circle that can calculate it's area and perimeter.
 */
public class Circle {

	private double radius;

	/** 
	 * Constructor to create a circle of a given radius.
	 * Note: how you cannot create a Circle without specifying it's radius!
	 */
	public Circle(double radius) {
		this.radius = radius;
	}

	/** @return the radius of the circle */
	public double getRadius() {
		return radius;
	}

	/** @return the area of a circle (PI*r*r) */
	public double getArea() {
		double area = Math.PI*radius*radius;
		return area;
	}

	/** @return the perimeter of the circle (2*PI*r) */
	public double getPerimeter() {
		double perimeter = 2 * Math.PI * radius;
		return perimeter;
	}

	/** prints the radius, area and perimeter of this circle */
	public void print() {
		System.out.println("Circle, with radius  " + getRadius());
		System.out.println("Area = " + getArea());
		System.out.println("Perimeter = " + getPerimeter());
	}

	public static void main(String args[]) {
		// create a circle of radius 10
		Circle circle1 = new Circle(10);
		// print information about the circle we just created
		circle1.print();
	}
}

Wednesday, September 14, 2011

First Java Program

Get going with java! Start with this program that prints "Hello World".

browse

package org.megha.blog.example.part1;

/**
 * This class prints "Hello World".
 *
 * <p>
 * If you are not using eclipse or another IDE, 
 * here are the commands to execute to compile
 * and run your first java program.
 * <p>
 * To compile (run the command after $ 
 * in java-through-examples/ directory)
 * <pre>
 * $ javac -d bin -s src src/org/megha/blog/example/part1/*
 * </pre>
 * <p>
 * To run (from the same folder, ie. java-through-examples/)
 * <pre>
 * $ java -classpath bin \
 *      org.megha.blog.example.part1.HelloWorld
 * </pre>
 */
public class HelloWorld {

        public static void main(String args[]) {
                System.out.println("Hello World");
        }
}