Testing java code
public class Test{<br> String test;<br>}Another test code
public String stringMethod(){
int number;
return number;
}
public int numberPaw(){
return numPaw;
}Another on
public class cat{
String paw;
}
Testing java code
public class Test{<br> String test;<br>}Another test code
public String stringMethod(){
int number;
return number;
}
public int numberPaw(){
return numPaw;
}Another on
public class cat{
String paw;
}
What Is Agile?
The Agile movement proposes alternatives to traditional project management. Agile approaches are typically used in software development to help businesses respond to unpredictability.
What is Scrum?
Scrum is the most popular way of introducing Agility due to its simplicity and flexibility.
Product Owner
The Product Owner is responsible for continuously communicating the vision and priorities to the development team.
Scrum Master
Team
Ref:
Scrum methodology
http://www.scrummethodology.com/
115 Java Interview Questions and Answer – Core
Strive for highly cohesive and loosely couple solution, code or design.
Degree to which the elements of a module belong together. Degree to which a class has a single, well-focused purpose. Higher the cohesiveness of the class, better is the OO design.
Example high cohesive
class MyReader{
public MyData readFromDisk(Parameter fileName){...};
public MyData readFromWeb(Parameter url){...};
public MyData readFromNetwork(Parameter networkLoc){...};
}Look how well-focused the class is in its purpose. The class is named “MyReader” and its intended purpose is to read the resource, and it does only so. It does not implement other things.
Example lower cohesive.
/*
* lower cohesion example (probably)
*/
class MyReader{
//validate the resource path
public boolean validateLocation(String path){
return ping(pathIP) && checkFTP(path);
}
private static boolean ping(String path){...};
private static boolean checkFTP(String path){...};
//read the resource
public MyData readFromDisk(String fileName){...};
public MyData readFromWeb(String url){...};
public MyData readFromNetwork(String networkAddress){...};
}Read operations are well defined, but it also implements logic to validate path. This is just an example and describes lower cohesion, wherein, a class intended for a specific functionality is also involved in other operations.
Benefits of higher cohesion:
Degree to which one class knows about another class. Spring promotes loosely coupled class because you don’t have to use new to instantiate another class that is needed.
Ref:
10 Best object oriented Design Principles
http://www.javacodegeeks.com/2012/08/10-object-oriented-design-principles.html
High cohesive and loose coupling examples
http://javabambino.blogspot.com/2013/06/loose-coupling-and-high-cohesion-in-java.html
4 OOP principal concepts: A-PIE: Abstraction, Polymorphism, Inheritance and Encapsulation.
Ref: http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep
In effect, polymorphism trims down the work of the developer because he can now create a sort of general class with all the attributes and behaviors that he envisions for it. When the time comes for the developer to create more specific subclasses with certain unique attributes and behaviors, the developer can simply alter code in the specific portions where the behaviors will differ. All other portions of the code can be left as is.
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name.
Parent class reference is used to reference to child class Object.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
// A Deer IS-A Animal
// A Deer IS-A Vegetarian
// A Deer IS-A Deer
// A Deer IS-A Object
// The following are legal (object = same level or lower object)
Deer d = new Deer();
Animal a = d; // Upcast same as Animal a=(Animal) d but Upcast always legal and do not need to specify any casting.
Vegetarian v = d; // Upcast
Object o = d; // Upcast
Deer d2=(Deer) new Animal(); // Downcast. This will cause run time ClassCastException.
Deer d3=(Deer) a; // Downcast. This will be correct since a is really pointing to object d which is a Deer.Java does not support multiple inheritances. Multiple inheritances could lead to diamond problem. Let’s say A is the super class of B and C & D is a subclass of both B and C. D inherits properties of A from two different inheritance paths i.e. via both B & C. This leads to ambiguity and related problems, so multiple inheritances is not allowed in Java.
Interface
Simulated with the use of interface, not a true multiple inheritances since the class has to implement the methods from the interfaces.
MixIn: Using Program to Interfaces, Object Composition, Method Delegation.
package com.pifl.exercise.multipleinheritance;
/**
* Java Multiple Inheritance (Mix In) using Program to Interfaces, Object Composition, Method Delegation.
* http://codeoftheday.blogspot.com/2013/07/emulating-multiple-inheritance-in-java.html
*/
public class MultipleInheritanceMixin {
interface Employee{
public Integer getEmployeeId();
public void setEmployeeId(Integer id);
}
class EmployeeImpl implements Employee{
Integer id;
@Override
public Integer getEmployeeId() {
return id;
}
@Override
public void setEmployeeId(Integer id) {
this.id=id;
}
}
interface Architect{
public void design();
}
class ArchitectImpl extends EmployeeImpl implements Architect{
@Override
public void design() {
// Architect design activity
}
}
interface Developer{
public void develop();
}
class DeveloperImpl extends EmployeeImpl implements Developer{
@Override
public void develop() {
// Developer activity
}
}
/**
* ArchitectDeveoper consists of Architect and Developer roles.
*/
interface ArchitectDeveloper extends Architect, Developer{};
/**
* Multiple inheritance using Interfaces, Composition and Delegation.
*/
class ArchitectDeveloperImpl extends EmployeeImpl implements ArchitectDeveloper{
// Composition
private Architect architect;
private Developer developer;
@Override
public void design() {
// Delegate design to architect object.
architect.design();
}
@Override
public void develop() {
// Delegate developer to developer object.
developer.develop();
}
public Architect getArchitect() {
return architect;
}
public void setArchitect(Architect architect) {
this.architect = architect;
}
public Developer getDeveloper() {
return developer;
}
public void setDeveloper(Developer developer) {
this.developer = developer;
}
}
}
Ref:
http://codeoftheday.blogspot.com/2013/07/emulating-multiple-inheritance-in-java.html
http://hannesdorfmann.com/android/java-mixins
AKA Information Hiding. Packing of properties and methods into a single unit/ class. It allows selective hiding of these properties and methods to avoid corruptions. Access control can be achieved by the following access specifiers:
| Abstraction | Encapsulation |
| 1. Abstraction solves the problem in the design level. | 1. Encapsulation solves the problem in the implementation level. |
| 2. Abstraction is used for hiding the unwanted data and giving relevant data. | 2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world. |
| 3. Abstraction lets you focus on what the object does instead of how it does it | 3. Encapsulation means hiding the internal details or mechanics of how an object does something. |
| 4. Abstraction– Outer layout, used in terms of design.
For Example: Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number. | 4. Encapsulation– Inner layout, used in terms of implementation.
For Example: Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits. |
| Implement in Java using interface and abstract class | Implement in Java using private, package private and protected access modifier. AKA data hiding. |
Rules for overriding:
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}
b.bark() will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark.public class Animal{
void move(){…} // This has default access modifier (no private, public etc. before void)
}
/* Java program to show that if static methods are redefined by
a derived class, then it is not overriding but hidding. */
// Superclass
class Base {
// Static method in base class which will be hidden in subclass
public static void display() {
System.out.println("Static or class method from Base");
}
// Non-static method which will be overridden in derived class
public void print() {
System.out.println("Non-static or Instance method from Base");
}
}
// Subclass
class Derived extends Base {
// When static is removed here, it will cause Compiler Error.
public void display() {
System.out.println("Non-static method from Derived");
}
// When Static is added here, it will cause Compiler Error.
public static void print() {
System.out.println("Static method from Derived");
}
}class Base {
private void fun() {
System.out.println("Base fun");
}
}
class Derived extends Base {
private void fun() {
System.out.println("Derived fun");
}
public static void main(String[] args) {
Base obj = new Derived();
obj.fun();
}
}
//We get compiler error “fun() has private access in Base”./* Java program to demonstrate whether we can override private method
of outer class inside its inner class */
class Outer {
private String msg = "GeeksforGeeks";
private void fun() {
System.out.println("Outer fun()");
}
class Inner extends Outer {
private void fun() {
System.out.println("Accessing Private Member of Outer: " + msg);
}
}
public static void main(String args[]) {
// In order to create instance of Inner class, we need an Outer
// class instance. So, first create Outer class instance and then
// inner class instance.
Outer o = new Outer();
Inner i = o.new Inner();
// This will call Inner's fun and will access private members of
// Outer's msg.
i.fun();
System.out.println("-------------------------");
// o.fun() calls Outer's fun (No run-time polymorphism).
o = i;
o.fun();
}
}
/*
The output:
Accessing Private Member of Outer: GeeksforGeeks
-------------------------
Outer fun()
*/In the above program, we created an outer class and an inner class. We extended Inner from Outer and created a method fun() in both Outer and Inner.
If we observe our output, then it is clear that the method fun() has not been overriden.
It is so because private methods are bonded during compile time and it is the type of the reference variable – not the type of object that it refers to – that determines what method to be called.
As a side note, private methods may be performance-wise better (compared to non-private and non-final methods) due to static binding.
public abstract class Employee{
private String name;
public Employee(){}; // constructor
abstract public void setBadge(int number); // abstract method
public void setName(String name){
this.name=name;
}
}public abstract class A extends B implements IA{
}
public class B extends C{
}
public class C{
}A contract between objects on how to communicate with each other. AKA “pure abstraction” since it does not have concrete methods, only definition of it.
Usage:
public interface InterestingEvent{
public void interestingEvent ();
}
public class EventNotifier{
private InterestingEvent ie;
private Boolean somethingHappened;
public EventNotifier (InterestingEvent event){
// Save the event object for later use.
ie = event;
// Nothing to report yet.
somethingHappened = false;
}
public void doWork (){
if (somethingHappened){
// Signal the even by invoking the interface's
// method.
ie.interestingEvent ();
}
//...
}
// ...
}
public class CallMe implements InterestingEvent{
private EventNotifier en;
// Define the actual handler for the event.
public void interestingEvent () {
// Do something...
}
//...
}
// Main class to call all classes
public class MainClass{
public static void main(String[] args) {
CallMe me = new CallMe();
EventNotifier eventNotifier = new EventNotifier(me);
While(waiting for event)
eventNotifier.doWork();
}
}
Characteristic:
public interface IA extends IB{
}
public interface IB{
}
E.x. of interface:
//Any number of import statements
import java.lang.*;
public interface NameOfInterface{
//Any number fields which will be implicitly public static final
String COLOR=”BLUE”;
//Any number of abstract method declarations
abstract public void addToCart(String stockNumber, int quantity);
// Does not have to have abstract keyword
public void goToAddToCart();
}
| Abstract Class | Interface |
| Methods can be implemented. | Pure abstraction, all methods are abstracts and cannot be implemented. |
| Can have constructor. | Cannot have constructor |
| Can have private, default, protected and public modifier. | Methods’ modifier is by default public. Attributes/ fields modifiers is by default public, static and final. |
| Sub-class cannot extends multiple abstract classes. | Sub-class can implement multiple interfaces. |
| Usable for code re-use | Usable for type declaration |
| New methods can be added as default and will not brake sub-classes. | New methods will required all sub-classes to implements the methods. |
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components:
Favor composition over inheritance is one of the popular object oriented design principal. Reasons:
1 . Inheritance can breaks the encapsulation (weak encapsulation). If a subclass depends its behavior on super class and when the behavior of the super class change, the functionality in the sub class is broken. For example we want to have a class which will encrypt an object before putting it in the HashSet. We can do it 2 ways shown below. Both will involved creating our custom class EncryptedHashSet.
Inheritance (is-a relationship): Override add()
public class EncryptedHashSet extends HashSet{
.....
@Override
public boolean add(Object o) {
return super.add(encrypt(o));
}
}
Composition (has-a relationship): Contains HasSet as member variable.
public class EncryptedHashSet implements Set{
private HashSet container;
public boolean add(Object o) {
return container.add(encrypt(o));
}
public boolean addAll(Collection c) {
return conatainer.add(encrypt(c));
}
.......
}
Suppose HashSet has the following where addAll() will use add()
public class HashSet implements set{
...
public boolean add(Object 0){
...
}
public boolean addAll(Collection c){
...
for(Object o: c){
...
if(! add(o))
return false;
}
}
}If nothing change in the HashSet then the inheritance implementation is good but let’s say the super class HashSet addAll() do not call add() anymore then the implementation using inheritance will break since now calling addAll() will not use the encryption.
2. Simulate multiple inheritance. Since you can only extend one class in Java, but if you need multiple functionality like e.g. for reading and writing character data into file, you need Reader and Writer functionality and having them as private members makes your job easy.
3. Composition offers better unit test-ability than inheritance. If one class is composed of another class, you can easily create Mock Object representing composed class for sake of testing. Inheritance doesn’t provide this luxury. In order to test derived class, you must need its super class.
4. Flexibility. If you use Composition you are flexible enough to replace implementation of Composed class with better and improved version. One example is using Comparator class which provides compare functionality. if your Container object contains a Comparator instead of extending a particular Comparator for comparing , its easier to change the way comparison is performed by setting different type of Comparator to composed instance, while in case of inheritance you can only have one comparison behavior on runtime, You can not change it runtime.
If you are looking for code reuse and “has-a” relationship the use composition.
Example: Decorator Pattern
GC Eligibility:
References in Java:
Example program for GC scope
Class GCScope {
GCScope t;
static int i = 1;
public static void main(String args[]) {
GCScope t1 = new GCScope();
GCScope t2 = new GCScope();
GCScope t3 = new GCScope();
// No Object Is Eligible for GC
t1.t = t2; // No Object Is Eligible for GC
t2.t = t3; // No Object Is Eligible for GC
t3.t = t1; // No Object Is Eligible for GC
t1 = null;
// No Object Is Eligible for GC (t3.t still has a reference to t1)
t2 = null;
// No Object Is Eligible for GC (t3.t.t still has a reference to t2)
t3 = null;
// All the 3 Object Is Eligible for GC (None of them have a reference.
// only the variable t of the objects are referring each other in a
// rounded fashion forming the Island of objects with out any external
// reference)
}
protected void finalize() {
System.out.println("Garbage collected from object" + i);
i++;
}
}

Primitives in Memory
Thread
In a multi-threaded application each thread will have its own stack but will share the same heap. Stack is thread safe because each thread has its own stack but heap is not thread safe unless guarded with synchronization.
Ref: http://www.youtube.com/watch?v=VQ4eZw6eVtQ
Stack and Heap
http://www.wordesign.com/java/edp306704/session7.htm
Primitives Hash Codes and Equals
/**
* Show hashcode() for primitives are always the value of the primitives.
* Show equals() for primitives are always true for the same value.
* Also include examples for String
*
*/
public class HashCodeAndEqualsForPrimitives {
public static void main (String [] argv){
Integer int1=2;
Integer int2=2;
Util.println("int1 hash code: "+int1.hashCode());
Util.println("int2 hash code: "+int2.hashCode());
Util.println("Is int1 equals to int2? "+int1.equals(int2));
Long long1=new Long(6);
Long long2=new Long(6);
Util.println("long1 hash code: "+long1.hashCode());
Util.println("long2 hash code: "+long2.hashCode());
Util.println("Is long1 equals to long2? "+long1.equals(long2));
Character char1='a';
Character char2='a';
Util.println("char1 hash code: "+char1.hashCode());
Util.println("char2 hash code: "+char2.hashCode());
Util.println("Is char1 equals to char2? "+char1.equals(char2));
String str1="abc";
String str2="abc";
Util.println("str1 hash code: "+str1.hashCode());
Util.println("str22 hash code: "+str2.hashCode());
Util.println("Is str1 equals to str2? "+str1.equals(str2));
}
}
// Output
int1 hash code: 2
int2 hash code: 2
Is int1 equals to int2? true
long1 hash code: 6
long2 hash code: 6
Is long1 equals to long2? true
char1 hash code: 97
char2 hash code: 97
Is char1 equals to char2? true
str1 hash code: 96354
str22 hash code: 96354
Is str1 equals to str2? true


Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements.
Set — a collection that cannot contain duplicate elements.
List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position).
Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements’ natural ordering.
Map — an object that maps keys to values. Map is not collections and collections are not Map. A Map cannot contain duplicate keys; each key can map to at most one value. E.g. HashTable
HashSet<String> stateSet = new HashSet<String>();
stateSet.add ("CA");
stateSet.add ("WI");
stateSet.add ("NY");
if (stateSet.contains("PB")) /* if CA, it will not add but shows following message*/
System.out.println("Already found");
else
stateSet.add("PB");
Ref: http://www.pakzilla.com/2009/08/24/hashmap-vs-hashtable-vs-hashset/
Ref: http://hashfold.com/techfold/comparison-of-java-map-vs-hashmap-vs-hashtable-vs-hashset/
Map<String, Integer> m = new HashMap<String, Integer>();
HashMap<Integer,String> productMap = new HashMap<Integer,String>();
productMap.put(1, "Keys");
productMap.put(2, null);How does HashMap works:
Put:

Get:
As we already know how Entry objects are stored in a bucket and what happens in the case of Hash Collision it is easy to understand what happens when key object is passed in the get method of the HashMap to retrieve a value.
Using the key again hash value will be calculated to determine the bucket where that Entry object is stored, in case there are more than one Entry object with in the same bucket stored as a linked-list equals() method will be used to find out the correct key. As soon as the matching key is found get() method will return the value object stored in the Entry object.
Null Key:
As we know that HashMap also allows null, though there can only be one null key in HashMap. While storing the Entry object HashMap implementation checks if the key is null, in case key is null, it always map to bucket 0 as hash is not calculated for null keys.
Hashtable<Integer,String> cityTable = new Hashtable<Integer,String>();
cityTable.put(1, "New York");
cityTable.put(2, "San Franscisco");
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/
System.out.println(cityTable.get(1));
System.out.println(cityTable.get(2));
System.out.println(cityTable.get(3));Ref: http://www.interview-questions-java.com/java-collections.htm
http://linux4genext.blogspot.com/2011/07/collections-in-java.html
In Java, generics helps to avoid insertion of wrong type at compile time. But generics do not guarantee correct object type insertion at run time. Checked collections come to the rescue to enforce restrictions on type inserted to a collection. E.g. Collections.checkedCollection, Collections.checkedList, Collections.checkedMap, Collections.checkedSet etc.
/**
* Shows how Collections.Checked*() enforce restriction to have correct object type added to
* a collection. Any attempt to insert an element of the wrong type will result in an
* immediate ClassCastException.
*/
public class CheckedCollections {
public static void main(String [] argv){
// Normally we do
List<Integer> num=new ArrayList<>();
num.add(1);
num.add(2);
// num.add("a"); // If you try to add this compiler will complaint.
// However try this
List numRaw=new ArrayList(); // Compiler will throw raw type warning, but sometimes this is ignored
numRaw.add(1); // Compiler raw type warning but insertion is successful.
numRaw.add(2); // Compiler raw type warning but insertion is successful.
numRaw.add("a"); // Compiler raw type warning, insertion is successful
// but this is totally different type than we expect.
Util.println(Arrays.toString(numRaw.toArray()));
// Checked collection
Collection chkNum=Collections.checkedCollection(num, Integer.class);
chkNum.add(10); // 10 will be added successfully
Util.println(Arrays.toString(chkNum.toArray()));
chkNum.add("a"); // Class cast exception is thrown
}
}
// Output
[1, 2, a]
[1, 2, 10]
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.String element into collection with element type class java.lang.Integer
at java.util.Collections$CheckedCollection.typeCheck(Collections.java:3037)
at java.util.Collections$CheckedCollection.add(Collections.java:3080)
at com.pifl.exercise.sandbox.CheckedCollections.main(CheckedCollections.java:35)
A few ways to achieve:
Collection<Type> c = Collections.synchronizedCollection(myCollection);
synchronized(c) {
for (Type e : c)
foo(e);
}
Map<KeyType, ValType> m = Collections.synchronizedMap(new HashMap<KeyType, ValType>());
...
Set<KeyType> s = m.keySet();
...
// Synchronizing on m, not s!
synchronized(m) {
while (KeyType k : s)
foo(k);
}
// Or
Map m = Collections.synchronizedMap(new HashMap());
...
Set s = m.keySet(); // Needn't be in synchronized block
...
synchronized(m) { // Synchronizing on m, not s!
Iterator i = s.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
Map<String,String> map = new HashMap<String,String>();
// populate the map
map.put("1","TP");
map.put("2","IS");
map.put("3","BEST");
// create a synchronized map
Map<String,String> synmap = Collections.synchronizedMap(map);
Iterator: Iterate collection forward. Used in Map, List, Set implementation.
ArrayList al=new ArrayList();
al.add("C");
al.add("A");
al.add("E");
// use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}For HashMap:
Map<String, Integer> mp=new HashMap<String, Integer>();
mp.put("bob",1); // add more items
Iterator<Integer> it=mp.values().iterator();
// Or can be used with key
Iterator<Integer> it=mp.keySet().iterator();
ListIterator: Access collection back and forward.
Used only with List object.
public class MyListIterator {
public static void main(String a[]){
List<Integer> li = new ArrayList<Integer>();
ListIterator<Integer> litr = null;
li.add(23);
li.add(98);
li.add(29);
li.add(71);
li.add(5);
litr=li.listIterator();
System.out.println("Elements in forward directiton");
while(litr.hasNext()){
System.out.println(litr.next());
}
System.out.println("Elements in backward directiton");
while(litr.hasPrevious()){
System.out.println(litr.previous());
}
}
}
// Output
Elements in forward directiton
23
98
29
71
5
Elements in backward directiton
5
71
29
98
23Methods of ListIterator
1) void add(E e): Inserts the specified element into the list (optional operation).
2) boolean hasNext(): Returns true if this list iterator has more elements when traversing the list in the forward direction.
3) boolean hasPrevious(): Returns true if this list iterator has more elements when traversing the list in the reverse direction.
4) E next(): Returns the next element in the list and advances the cursor position.
5) int nextIndex(): Returns the index of the element that would be returned by a subsequent call to next().
6) E previous(): Returns the previous element in the list and moves the cursor position backwards.
7) int previousIndex(): Returns the index of the element that would be returned by a subsequent call to previous().
8) void remove(): Removes from the list the last element that was returned by next() or previous() (optional operation).
9) void set(E e): Replaces the last element returned by next() or previous() with the specified element (optional operation).
Foreach (Java 1.5): Makes code look better, easier to read.
for (Iterator i = suits.iterator(); i.hasNext(); ) {
Suit suit = (Suit) i.next();
for (Iterator j = ranks.iterator(); j.hasNext(); )
sortedDeck.add(new Card(suit, j.next()));
}
Vs.
for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
Fail-fast iterator can throw ConcurrentModificationException in two scenarios :
After the creation of the iterator , structure is modified at any time by any method other than iterator’s own remove method.
If one thread is modifying the structure of the collection while other thread is iterating over it .
Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.Any structural modification done to the iterator affects the copied data structure. So , original data structure remains structurally unchanged .Hence , no ConcurrentModificationException throws by the fail safe iterator.
Two issues associated with Fail Safe Iterator are :
| Fail Fast Iterator | Fail Safe Iterator | |
|---|---|---|
| Throw ConcurrentModification Exception | Yes | No |
| Clone object | No | Yes |
| Memory Overhead | No | Yes |
| Examples | HashMap,Vector,ArrayList,HashSet | CopyOnWriteArrayList, ConcurrentHashMap |
Fail-fast example: Using HashMap. For each looping will be fail-fast as well.
public class FailFastExample{
public static void main(String[] args){
Map<String,String> premiumPhone = new HashMap<String,String>();
premiumPhone.put("Apple", "iPhone");
premiumPhone.put("HTC", "HTC one");
premiumPhone.put("Samsung","S5");
Iterator iterator = premiumPhone.keySet().iterator();
while (iterator.hasNext()){
System.out.println(premiumPhone.get(iterator.next()));
premiumPhone.put("Sony", "Xperia Z");
}
}
}
// Output
iPhone
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$KeyIterator.next(Unknown Source)
at FailFastExample.main(FailFastExample.java:20)Fail-Safe Example: Using ConccurentHashMap. For each looping in here will be fail-safe as well.
public class FailSafeExample{
public static void main(String[] args){
ConcurrentHashMap<String,String> premiumPhone =
new ConcurrentHashMap<String,String>();
premiumPhone.put("Apple", "iPhone");
premiumPhone.put("HTC", "HTC one");
premiumPhone.put("Samsung","S5");
Iterator iterator = premiumPhone.keySet().iterator();
while (iterator.hasNext()){
System.out.println(premiumPhone.get(iterator.next()));
premiumPhone.put("Sony", "Xperia Z");
}
}
}
// Output
S5
HTC one
iPhoneGood reference: http://tutorials.jenkov.com/java-exception-handling/index.html
The exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
For example, consider the following Java program that opens file at locatiobn “C:\test\a.txt” and prints first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException
import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}The exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

java.lang.Object
+--java.lang.Throwable (CHECKED)
+--Exception (CHECKED)
| +--ClassNotFoundException
| +--IOException
| | +--FileNotFoundException
| +--SQLException
| +--MalformedURLException
| +--RuntimeException (UNCHECKED)
| | +--NullPointerException
| | +--NumberFormatException
| | +--ClassCastException
| | +--IndexOutOfBoundsException
| | | +--ArrayIndexOutOfBoundsException
+--Error (UNCHECKED)
| +--VirtualMachineError
| | +--OutOfMemoryErrorRef: http://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
public class TryCatchFinally {
public int returnInCatch(){
System.out.println("---- Return in Catch block");
int i=1;
try{
throw new Exception("Bla");
}catch(Exception e){
return i;
}finally{
i=20;
System.out.println("Finally is called. i is reassign to: "+i);
}
}
public int returnNoCatch(){
System.out.println("----- Return no catch");
int i=1;
try{
System.out.println("In try");
}catch(Exception e){
return i;
}finally{
i=20;
System.out.println("Finally is called. i is reassign to: "+i);
}
return i;
}
public static void main(String[] args) {
TryCatchFinally obj=new TryCatchFinally();
System.out.println("Return is: "+obj.returnInCatch());
System.out.println("Return is:"+obj.returnNoCatch());
}
}
// Output will be
---- Return in Catch block
Finally is called. i is reassign to: 20
Return is: 1
----- Return no catch
In try
Finally is called. i is reassign to: 20
Return is:20Allow resources to be created and closed automatically.
Pre Java 7:
try{
//open file or resources
}catch(IOException){
//handle exception
}finally{
//close file or resources
}
Java 7:
try(open file or resource here){
//...
}catch(...){
//...
}
//after try block, file will close automatically.
Example Java 6: Classic way to read a file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example1 {
public static void main(String[] args) {
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Example Java 7: finally is no longer required. The file will be closed automatically after try block.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example2 {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example 2 Java 7: with 2 open resources
private static void printFileJava7() throws IOException {
try( FileInputStream input = new FileInputStream("file.txt");
BufferedInputStream bufferedInput = new BufferedInputStream(input)) {
int data = bufferedInput.read();
while(data != -1){
System.out.print((char) data);
data = bufferedInput.read();
}
}
}
This is also beneficial for implementing fail-safe exception handling easier. See Jenkov statement and links:
” If an exception is thrown both from inside the try-with-resources block, and when the FileInputStream is closed (when close() is called), the exception thrown inside the try block is thrown to the outside world. The exception thrown when the FileInputStream was closed is suppressed. This is opposite of what happens in the example first in this text, using the old style exception handling (closing the resources in the finally block). “
Multiple resources can also be called within the try.
http://tutorials.jenkov.com/java-exception-handling/try-with-resources.html
For primitives, == is used to compare the “values”.
For objects, by default both equlas() and ” == ” are the same, they checks to see if both objects reference the same place in memory. One has to overwrite equals() in order to compare actual values for objects.
public class EqualsAndEquals {
public static void main(String []arg) {
EqualsAndEquals obj1=new EqualsAndEquals();
EqualsAndEquals obj2=new EqualsAndEquals();
System.out.println("obj1==obj1: "+(obj1==obj1));
System.out.println("obj1==obj2: "+(obj1==obj2));
System.out.println("obj2.equals(obj2): "+obj2.equals(obj2));
System.out.println("obj1.equals(obj2): "+obj1.equals(obj2));
}
}
// Output are
obj1==obj1: true
obj1==obj2: false
obj2.equals(obj2): true
obj1.equals(obj2): false
String object is special, see String Literals vs. Object.

String strLiteral = “Java”;
String strObject = new String(“Java”);
Both expression gives you String object. When you create String object using new() operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. “Java”, it may return an existing object from String pool (a cache of String object in Perm gen space, which is now moved to heap space in Java 7), if it’s already exists. Otherwise it will create a new string object and put in string pool for future re-use.
Can use ‘==’ to compare String literals, but cannot compare String object with it since it will compare the address.
String a = "Java";
String b = "Java";
System.out.println(a == b); // True
String e = "JDK";
String f = new String("JDK");
System.out.println(e == f); // False since it will try to equate value in 'e' with address of 'f'
String e=new String("JDK");
String f=new String("JDK");
System.out.println(e==f); // False
System.out.println(e.equals(f)) // True
String Intern() method
Will be used in conjunction of New String(“hello”) for example. This will return string from String Pool if it is already there, if it is not then it will create “hello” and put is in String Pool.
public class InternExample{
public static void main(String args[]){
String s1=new String("hello");
String s2="hello";
String s3=s1.intern();//returns string from pool, now it will be same as s2
System.out.println(s1==s2);//false because reference is different
System.out.println(s2==s3);//true because reference is same
}}
Note: Strings that are in String Pool will not be garbage collected. (Need more investigation on this statement).
Autoboxing: automatic conversion from primitive to object wrapper e.g. int -> Integer
The compiler will use Integer.valueOf(int) to convert int to Integer at run time.
Unboxing: automatic conversion from object wrapper to primitive e.g. Integer -> int.
The compiler does not generate an error because it invokes the intValue() method to convert an Integer to an int at runtime.
Autoboxing and unboxing lets developers write cleaner code, making it easier to read.
| Primitive type | Wrapper class |
|---|---|
| boolean | Boolean |
| byte | Byte |
| char | Character |
| float | Float |
| int | Integer |
| long | Long |
| short | Short |
| double | Double |
Ref: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
Create table
CREATE TABLE products ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(30), price float, quantity int );
Explanation
CREATE TABLE reviews ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, rating TINYINT, review TEXT, product_id INT, FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE ON UPDATE CASCADE );
Explanation:
product_id INT: Foreign key from products.
Insert
INSERT INTO products (name, price) VALUES('Tape Gun', 14.50 )
/* OR can be written as */
INSERT INTO products VALUES(‘Tape Gun’, 14.50)
Select
SELECT products.name, reviews.review FROM products, reviews WHERE products.product_id=reviews.product_id AND products.name LIKE “Tape%”
Update
UPDATE products SET price=15.50, quantity=10 WHERE name=’Tape Gun’
Delete
DELETE FROM products, reviews WHERE products.product_id = reviews.product_id AND product_id=1
Case Sensitive Query
/* Using binary */ SELECT * FROM TestCustomerName WHERE BINARY name='Ferry' /* Use upper and lower case */ SELECT * FROM TestCustomerName WHERE upper(name)='FERRY'
Ref: http://www.tizag.com/mysqlTutorial/mysqlquery.php
For the most part only use JOIN, INNER JOIN, LEFT JOIN, RIGHT JOIN. JOIN = INNER JOIN = using where. OUTER might be added after the word LEFT/ RIGHT ex. LEFT OUTER JOIN, but not necessary, essentially this equals to LEFT JOIN. They are for ODBC compatibility and do not add extra capabilities.
JOIN: only includes all records that match.
SELECT name, phone, selling FROM demo_people JOIN demo_property ON demo_people.pid = demo_property.pid;
LEFT JOIN: includes all records that match plus unmatched records on the left.
SELECT name, phone, selling FROM demo_people LEFT JOIN demo_property ON demo_people.pid = demo_property.pid;
RIGHT JOIN: includes all records that match plus unmatched records on the right.
SELECT name, phone, selling FROM demo_people RIGHT JOIN demo_property on demo_people.pid = demo_property.pid;

Ref: http://www.wellho.net/mouth/158_MySQL-LEFT-JOIN-and-RIGHT-JOIN-INNER-JOIN-and-OUTER-JOIN.html
The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.
SELECT expression1, expression2, … expression_n,
aggregate_function (expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, … expression_n;
Parameters or Arguments
Example – Using GROUP BY with the SUM Function:
| employee_number | last_name | first_name | salary | dept_id |
|---|---|---|---|---|
| 1001 | Smith | John | 62000 | 500 |
| 1002 | Anderson | Jane | 57500 | 500 |
| 1003 | Everest | Brad | 71000 | 501 |
| 1004 | Horvath | Jack | 42000 | 501 |
SELECT dept_id, SUM(salary) AS total_salaries
FROM employees
GROUP BY dept_id;
| dept_id | total_salaries |
|---|---|
| 500 | 119500 |
| 501 | 113000 |
Example – Using GROUP BY with the MIN function:
SELECT dept_id, MIN(salary) AS lowest_salary
FROM employees
GROUP BY dept_id;
| dept_id | lowest_salary |
|---|---|
| 500 | 57500 |
| 501 | 42000 |
Example – Using GROUP BY with the MAX function:
SELECT dept_id, MAX(salary) AS highest_salary
FROM employees
GROUP BY dept_id;
| dept_id | highest_salary |
|---|---|
| 500 | 62000 |
| 501 | 71000 |
Example – Using GROUP BY with the COUNT function:
| product_id | product_name | category_id |
|---|---|---|
| 1 | Pear | 50 |
| 2 | Banana | 50 |
| 3 | Orange | 50 |
| 4 | Apple | 50 |
| 5 | Bread | 75 |
| 6 | Sliced Ham | 25 |
| 7 | Kleenex | NULL |
SELECT category_id, COUNT(*) AS total_products
FROM products
WHERE category_id IS NOT NULL
GROUP BY category_id
ORDER BY category_id;
| category_id | total_products |
|---|---|
| 25 | 1 |
| 50 | 4 |
| 75 | 1 |
Ref: http://www.techonthenet.com/sql/group_by.php
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.
SELECT DeptID, SUM(SaleAmount)
FROM Sales
WHERE SaleDate = ’01-Jan-2000′
GROUP BY DeptID
HAVING SUM(SaleAmount) > 1000
SELECT DepartmentName, COUNT(*)
FROM Employee, Department
WHERE Employee.DepartmentID = Department.DepartmentID
GROUP BY DepartmentName
HAVING COUNT(*)>1;
HAVING is convenient, but not necessary. Code equivalent to the example above, but without using HAVING, might look like:
SELECT * FROM (
SELECT DepartmentName AS deptNam, COUNT(*) AS empCnt
FROM Employee AS emp, Department AS dept
WHERE emp.DepartmentID = dept.DepartmentID
GROUP BY deptNam
) AS grp
WHERE grp.empCnt > 1;
Ref:
http://hungred.com/useful-information/ways-optimize-sql-queries/
http://beginner-sql-tutorial.com/sql-query-tuning.htm
Troubleshooting when hang
http://www.oracle.com/technetwork/issue-archive/2012/12-jul/o42dba-1566567.html
An index can be created in a table to find data more quickly and efficiently. A good analogy for this is an index in a book for example to search for Golden Retriever, you can go to the index and it will tell you the page number rather than flipping through all the pages.
As book index contains page number, a database index contains a pointer to the row containing the value that you are searching for in your SQL.


Ref: http://dba.fyicenter.com/faq/sql_server/table_index_diagram.jpg
The users cannot see the indexes, they are just used to speed up searches/queries. Index should only be created on a table if the data in the indexed column will be queried frequently.
Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
Syntax:
CREATE INDEX index_name ON table_name (column_name1, column_name2...)
Types of index:
CREATE INDEX index_name
ON table_name (column_name);
CREATE INDEX index_name
on table_name (column1, column2);
CREATE INDEX index_name
on table_name (column1, column2);
When to avoid index:
XML Interview Questions:
http://www.developersbook.com/xml/interview-questions/xml-interview-questions-faqs-1.php
DTD: Document Declaration Type, not as good as XSD.
Tutorial by example XSD (XML Schema Definition):
http://www.codeguru.com/java/article.php/c13529/XSD-Tutorial-XML-Schemas-For-Beginners.htm#page-1
Advantage of spring:
Below are classes for spring example
package com.pifl;
public class Car{
private String brand;
private String color;
public void setBrand(String brand){
this.brand=brand;
}
public String getBrand(){
return brand;
}
public void setColor(String color){
this.color=color;
}
Public String getColor(){
Return color;
}
}
public class User {
private String name;
private int age;
private String country;
private Car car;
User(String name, int age, String country) {
this.name=name;
this.age=age;
this.country=country;
}
User( int age, String country){
this.age=age;
this.country=country;
}
public String toString() {
return name + " is " + age
+ " years old, living in "
+ country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
// MAIN
package com.pifl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class main {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("beans.xml");
User user = (User)context.getBean("user");
System.out.println(user);
}
}
Singleton (by default) – Should be used for stateless bean.
Prototype – new bean instance is created every time a request for that specific bean is made. Should be used for statefull bean.
2 Types. Rule of thumb: use constructor arguments for mandatory dependencies and setters for optional dependencies. It is true that setters is most often used.
Ref:
http://www.tutorialspoint.com/spring/spring_dependency_injection.htm
http://java.dzone.com/articles/dependency-injection-an-introd?page=0,0
http://www.dzone.com/tutorials/java/spring/spring-bean-setter-injection-1.html
Set bean property via constructor injection.
If there are two constructors, to differentiate between the two, “type” and “index” (to specify order) attribute must be defined in the xml.
<beans>
<bean id="user" class="com.pifl.User" >
<constructor-arg index="0" type="java.lang.String" value="Eswar" />
<constructor-arg index="1" type="int" value="24"/>
<constructor-arg index="2" type="java.lang.String" value="India"/>
</bean>
<bean id="userWithTwoParams" class="com.pifl.User" >
<constructor-arg index="0" type="int" value="24"/>
<constructor-arg index="1" type="java.lang.String" value="India"/>
</bean>
</beans>
Set bean property via setter injection with dependency injection. Commonly used.
<beans >
<bean id=”userCar” class=”com.pifl.Car” />
<bean id="user" class="com.pifl.User" >
<property name="name" value="Eswar" />
<property name="age" value="24"/>
<property name="country" value="India"/>
<property name=”car” ref=”userCar”>
</bean>
</beans>

Instantiate object via spring where object cannot be instantiated directly using its constructor i.e. object has private constructor.
http://www.javabeat.net/create-spring-beans-using-factory-methods/
We can use the ‘factory-method’ attribute to tell spring to call a static factory method to instantiate our bean. Useful when existing legacy codes use static (factory) methods to create objects.
package com.pifl
public interface JapaneseCar{
}
public class Honda implements JapaneseCar{
public String color;
// Getter and setter below
…
}
public class Toyota implements JapaneseCar{
public String color;
// Getter and setter below
…
}
// Car factory with private constructor and static method to get instance.
public class CarFactory{
public Integer factoryMaxOutput;
private CarFactory(){};
// Static factory methods
public static JapaneseCar createJapaneseCarByBrand(String brand){
if(brand.equals(”Honda”))
return new Honda();
else
return new Toyota();
}
// Getter and setter below
…
}
<bean id="honda" class="com.pifl.CarFactory"
factory-method="createJapaneseCarByBrand">
<constructor-arg value="Honda"/>
<property name="color" value="Black"/>
</bean>
The constructor arguments will be passed as parameters to the static factory method and the property elements “color” will be set on the honda bean.
We can use the ‘factory-bean’ attribute along with the ‘factory-method’ attribute to call instance factory methods to create our beans. Let’s say the CarFactory class now looks like below:
// Car factory with private constructor and static method to get instance.
public class CarFactory{
public Integer factoryMaxOutput;
private CarFactory(){};
// Static factory methods
public static JapaneseCar getInstance(){
return new CarFactory()
}
public JapaneseCar getHonda(){
return new Honda();
}
// Getter and setter below
…
}
<bean id="japaneseCarFactory"
class="com.pifl.CarFactory">
factory-method=”getInstance”/>
</bean>
<bean id="honda" factory-bean="japaneseCarFactory"
factory-method="getHonda">
<constructor-arg value="1"/>
<property name="color" value="Silver"/>
</bean>
Ref: http://www.programmingforliving.com/2012/09/spring-bean-instantiation-through_27.html
Use spring’s own FactoryBean interface to create your factory class. This will make your code tightly coupled with Spring. One example is when you have a class you want to use but it has private constructor and only static method to give an object, see CarFactory class with static method createJapaneseCarByBrand. We can create a wrapper class which implements FactoryBean and have a public constructor.
// Wrapper class for CarFactory to create Japanese car
public class CarFactoryWrapper implements FactoryBean<JapaneseCar>{
private JapaneseCar car=null;
private String brand;
public CarFactoryWrapper(String brand){
car=CarFactory.createJapaneseCarByBrand(brand);
}
// Implements Factory Bean methods
public JapaneseCar getObject() throws Exception{
return car;
}
public Class<JapaneseCar> getObjectType(){
return JapaneseCar.class;
}
public Boolean isSingleton(){
return true;
}
}
// Class that use car created
Public class Person{
Private JapaneseCar myCar;
// set and getter below and othe logic
}
<!—Create Honda bean
<bean id=”honda” class=”com.pifl.CarFactoryWrapper”>
<constructor-arg value=”Honda”/>
</bean>
<!—Other class that use car-->
<bean id=”person” class=”com.pifl.Person”>
<property name=”myCar” ref=”Honda”>
</bean>
Ref: http://www.captaindebug.com/2011/06/implementing-springs-factorybean.html#.VBS3K_mwKIk
Ref: http://docs.spring.io/spring/docs/2.0.x/reference/beans.html#beans-factory-method-injection
When lifecycle on every Beans and their dependencies are the same, defining one bean as property of the other is adequate but problems when lifecycle is different. Consider singleton bean A needs to use prototype bean B and discard it when the method that use it is done. The container only create singleton bean A once this you can only set the properties with prototype bean B once.
Bean A is made aware of the container and can ask the container to give bean B on the fly. The downside of this is the program becomes tightly couple with spring.
If a bean in spring implements BeanFactoryAware then that bean has to implement a method that is setBeanFactory. And when that bean is loaded in spring container, setBeanFactory is called, nothing special need to be done.
public class CommandManager implements BeanFactoryAware{
private BeanFactory beanFactory;
public Object process(Map commandState){
// grab new command instance everytime
Command command=createCommand();
Command.setState(commandState);
return command.execute();
}
// Get command bean from container
protected Command createCommand(){
return (Command) this.beanFactory.getBean(“command”); // tightly coupled with spring
}
@override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException{
this.beanFactory=beanFactory;
}
}
// In spring. SPring will inject beanFactory automatically
<bean id="commandManager" class="com.pifl.CommandManager"/>
Refers to the ability of the container to override methods on container managed beans. This will decoupled the code from spring unlike the above but with caution below.
public abstract class CommandManager{
public Object process(Map commandState){
// grab new command instance everytime
Command command=createCommand();
Command.setState(commandState);
return command.execute();
}
// This method will be implemented in spring
protected abstract Command createCommand();
}
<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
<!-- inject dependencies here as required -->
</bean>
<!-- commandProcessor uses statefulCommandHelper -->
<bean id="commandManager" class="fiona.apple.CommandManager">
<lookup-method name="createCommand" bean="command"/>
</bean>
Caution:
TODO: There are better methods out there, need research.
Hibernate is object-Relational Mapping (ORM) tool that provides mapping of POJO entities to database tables and vice versa to retrieve and persists data to database.
Example below is DB contacts with details company information.

@Entity
@Table(name = "company")
public class Company implements Serializable {
@Id // This is id column
@Column(name = "id")
@GeneratedValue // Let database auto increment the id
private int id;
@Version // Control versioning or concurrency using @Version annotation.
@Column(name = "version")
private Date version;
@OneToOne(cascade = CascadeType.MERGE)
@PrimaryKeyJoinColumn // Associated entities sharing the same primary key
private CompanyDetail companyDetail;
@ManyToOne
@JoinColumn(name = "statusId")
private CompanyStatus status;
// Sort your data using @OrderBy annotation. In example below, it will sort all contacts in a company by their firstname in ascending order.
@OrderBy("firstName asc")
private Set contacts;
@Transient // Use transient if this property is not part of the table
private String flag;
// LOB saves data in CLOB (Character Large Object – larger than Varchar) or BLOB (Binary Large Object – double byte character large data) types
@LOB
private String largeText;
...
}
@Entity
@Table(name = "companyDetail")
public class CompanyDetail implements Serializable {
@Id
@Column(name = "id")
private int id;
...
}
@Entity
@Table(name = "contact")
public class Contact implements Serializable {
@ManyToOne
@JoinColumn(name = "companyId")
private Company company;
...
}
@Entity
@Table(name = "contactDetail")
public class ContactDetail implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@OneToOne
@MapsId // Don’t know why it is here, joincolumn should be enough?
@JoinColumn(name = "contactId")
private Contact contact;
...
}
Ref:
Simple example: persistency HQL, Criteria API
http://manikandanmv.wordpress.com/2011/04/13/hibernate-basics-simple-example/
Annotation best complete example
http://www.techferry.com/articles/hibernate-jpa-annotations.html
See also “thread safe singleton” in JAVA CONCURRENCY THREAD.
Characteristics:
// Lazy init singleton
public class Singleton {
private static Singleton uniqInstance;
private Singleton() {
// Reflection proof the singleton
if (uniqInstance != null) {
throw new IllegalStateException("instance already created.");
}
}
public static synchronized Singleton getInstance() {
if (uniqInstance == null) {
uniqInstance = new Singleton();
}
return uniqInstance;
}
// other useful methods here
}
// Eager init singleton
public class Singleton {
private static final Singleton uniqInstance=new Singleton();
private Singleton() {
// Reflection proof the singleton
if (uniqInstance != null) {
throw new IllegalStateException("instance already created.");
}
}
public static synchronized Singleton getInstance() {
return uniqInstance;
}
// other useful methods here
}
public enum EnumSingleton {
INSTANCE;
int value;
public int getValue(){
return value;
}
public void setValue(int value){
this.value=value;
}
public void doSomething(){
//do something
}
}
Characteristic:
Ref: https://dzone.com/articles/java-singletons-using-enum
Def: a creational design pattern. This is used to encapsulate object creation code. A factory class instantiates and returns a particular type of object based on data passed to the factory.
Both abstract and interface classes can be used in factory pattern.
Example: Simple dog factory that will return variety of dog types based on data passed.
//Dog interface
Interface Dog{
Public void speak();
}
//Dog classes that implement Dog
class Poodle implements Dog{
public void speak(){
System.out.println("The poodle says \"arf\"");
}
}
class Rottweiler implements Dog{
public void speak(){
System.out.println("The Rottweiler says (in a very deep voice) \"WOOF!\"");
}
}
class SiberianHusky implements Dog{
public void speak(){
System.out.println("The husky says \"Dude, what's up?\"");
}
}
//Java Factory Class
class DogFactory{
public static Dog getDog(String criteria){
if ( criteria.equals("small") )
return new Poodle();
else if ( criteria.equals("big") )
return new Rottweiler();
else if ( criteria.equals("working") )
return new SiberianHusky();
return null;
}
}
//Driver/ main program:
public class JavaFactoryPatternExample{
public static void main(String[] args){
// create a small dog
Dog dog = DogFactory.getDog("small");
dog.speak();
// create a big dog
dog = DogFactory.getDog("big");
dog.speak();
// create a working dog
dog = DogFactory.getDog("working");\
dog.speak();
}
}
Examples with Order Fulfillment Application
The order fulfillment application has to interact with different vendor’s web site which has common web flow.
Interfaces are declared for each part of the web flow e.g. ICategoryPage, ICartPage, ICheckoutPage, IConfirmationPage
Each web flow class for each vendors implements the above flows e.x. JxpCheckoutPage extends JxpPage implements ICheckoutPage.
Note: JxpPage is an abstract class.
In the application a factory class will generate the appropriate object for given vendor.
Ref: http://www.devdaily.com/java/java-factory-pattern-example
CME Pattern in Admin Process is similar to Observer Pattern and Chain of Responsibilities.
Each of the EventHandlers registers itself to admin EventManager. It is possible that an EventHandlers registered to multiple events. It is also possible that the event that is already registered by an event-handler be registered again by another event-handler (many to many relationship between events and event-handlers). These registrations are stored as mapping: Map<EventType, handlerObject> in the EventHandler.
Admin also used chain of reposibilities patterns to chain tasks. For example ???
Define a one-to-many dependency between objects so that when one object (Subject/ Observable) changes state, all its dependents (Observers) are notified and updated automatically.
An object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
It is mainly used to implement distributed event handling systems. The Observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern. For example:

Figure above illustrates the Model/View/Controller architecture in its most general form. There is one model. Multiple controllers manipulate the model; multiple views display the data in the model, and change as the state of the model changes.
Some points:

Example Code:
package com.pifl.exercise.design_pattern.observer;
import java.util.ArrayList;
import java.util.List;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util;
/**
* Observer design pattern demo.
* @author Ferry
*
*/
public class ObserverDemo {
public static void main(String [] args){
ObserverDemo ob=new ObserverDemo();
// Create subject
Subject subject=ob.new Subject();
// Register Observers to subject
ob.new BinaryObserver(subject);
ob.new OctalObserver(subject);
ob.new HexaObserver(subject);
// Subject state change or other changes is broadcasted to observers.
// Observers will print what it receives.
subject.setState(2);
subject.setState(3);
subject.setState(10);
}
class Subject{
List<Observer> observers=new ArrayList<Observer>();
Integer state;
public void notifyAllObserver(){
for(Observer ob: observers){
ob.update();
}
}
public void attach(Observer observer){
observers.add(observer);
}
public Integer getState(){
return state;
}
public void setState(Integer state){
this.state=state;
notifyAllObserver();
}
}
abstract class Observer{
protected Subject subject;
protected String observerName;
public abstract void update();
}
class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
this.observerName="BinaryObserver";
this.subject=subject;
this.subject.attach(this);
}
@Override
public void update() {
Util.println(observerName+": state change: "+subject.getState());
}
}
class OctalObserver extends Observer{
public OctalObserver(Subject subject){
this.observerName="OctalObserver";
this.subject=subject;
this.subject.attach(this);
}
@Override
public void update() {
Util.println(observerName+": state change: "+subject.getState());
}
}
class HexaObserver extends Observer{
public HexaObserver(Subject subject){
this.observerName="HexaObserver";
this.subject=subject;
this.subject.attach(this);
}
@Override
public void update() {
Util.println(observerName+": state change: "+subject.getState());
}
}
}
Sample output:
BinaryObserver: state change: 2 OctalObserver: state change: 2 HexaObserver: state change: 2 BinaryObserver: state change: 3 OctalObserver: state change: 3 HexaObserver: state change: 3 BinaryObserver: state change: 10 OctalObserver: state change: 10 HexaObserver: state change: 10
This observer pattern above is suitable for one subject having many Observers. If there are more than one subjects that should be monitored, the Observers registration should be done on each of the subjects. This can be solved with dispatcher where each of the subject (events) will have observers register to it, so in essence same observers can register to same event or vice verse (many to many).

This pattern introduces a third actor, the Dispatcher. It is responsible for:
Please notice that we define an enum for the event type (EventTypeEnum). Indeed there is one list of EventManagersfor each distinct EventTypeEnum.
The routing based on the EventTypeEnum is done in the dispatch(EventTypeEnum eventType, Subject object) method body.
public class Dispatcher{
...
public void dispatch(EventTypeEnum event, Subject object)
{
switch (event) {
case SAVE:
for(EventManager manager: this.saveEventManagers)
{
manager.executeEvent(event,object);
}
break;
case UPDATE:
for(EventManager manager: this.updateEventManagers)
{
manager.executeEvent(event,object);
}
break;
case DELETE:
for(EventManager manager: this.deleteEventManagers)
{
manager.executeEvent(event,object);
}
break;
default:
logger.error("Unknow EventType of type " + event.name());
}
}
...
} // End Dispatcher class
public class EventManager{
...
public void executeEvent(EventTypeEnum event, Subject object) {
...
// Processing here
...
}
...
}
In real projects, some processing can take time. With the Dispatcher pattern, the main thread is blocked until allEventManagers finish their task.
If would be interesting if we could delegate the processing to a separate thread. There comes the Asynchronous Dispatcher pattern.

Here we rely on a ThreadPoolTaskExecutor in each EventManager to delegate the work to a new thread. Please notice that the dispatching task is done in the main thread. The new thread delegation is done at the last step in eachEventManager.
One important point to take care when working in a multi-threaded context is concurrency issues. Indeed when we pass the Subject object to a new thread for processing, the main thread resumes its processing flow and the sameSubject object may be changed in this main thread.
Either you ensure that the processing flow in the main thread never change the Subject object, or you make a deep copy. It is quite expensive but there is no other way around to guard agains concurrent modifications.
Ref: https://doanduyhai.wordpress.com/2012/08/04/design-pattern-the-asynchronous-dispatcher/
Ref:
http://www.tutorialspoint.com/design_pattern/observer_pattern.htm
http://sourcemaking.com/design_patterns/Observer
http://en.wikipedia.org/wiki/Observer_pattern
Admin chaining
AdminSettlementEventHandler->AdminStoreEvenHandler (extends FaultTolerantTimedQueueSwitchService) –> AdminStoreSettlementEventHandler –> TradeDateRollPersistenceHandler
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
Strategy Pattern – that enables an algorithm’s behavior to be elected at runtime. The strategy pattern defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family.
Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime.
One of the best example of this pattern is Collections.sort() method that takes Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways.

Example codes:
package com.pifl.exercise.design_pattern.strategy;
import com.pifl.exercise.util.Util;
public class StrategyPatternDemo {
public static void main(String [] args){
Context context=new Context();
// Data is gathered
context.getData(2, 3);
// Different strategy/ algorithm can be chosen at run time.
Util.println("Result add: "+context.executeStrategy(new OperationAdd()));
Util.println("Result substract: "+context.executeStrategy(new OperationSubstract()));
Util.println("Result multiple: "+context.executeStrategy(new OperationMultiply()));
}
}
class Context{
Strategy strategy;
int num1=0;
int num2=0;
public void getData(int num1, int num2){
this.num1=num1;
this.num2=num2;
Util.println("Data input: num1: "+num1+", num2: "+num2);
}
public int executeStrategy(Strategy strategy){
return strategy.doOperation(num1, num2);
}
}
interface Strategy{
int doOperation(int num1, int num2);
}
class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1+num2;
}
}
class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1-num2;
}
}
class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1*num2;
}
}
Output:
Data input: num1: 2, num2: 3 Result add: 5 Result substract: -1 Result multiple: 6
Common example of strategy pattern in real life is custom sorting.
List<String> names = Arrays.asList("Anne", "Joe", "Harry");
Collections.sort(names, new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
Ref:
http://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
http://en.wikipedia.org/wiki/Strategy_pattern
http://java.dzone.com/articles/design-patterns-strategy
In State pattern a class behavior changes based on its state. This type of design pattern comes under behavior pattern.
In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

Step 1: Create an interface.
State.java
public interface State {
public void doAction(Context context);
}
Step 2: Concrete class that implement the interface.
StartState.java
public class StartState implements State {
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
public String toString(){
return "Start State";
}
}
StopState.java
public class StopState implements State {
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}
public String toString(){
return "Stop State";
}
}
Step 3: Context class.
Contex.java
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
}
Step 4: Use the context to see change in behavior when State change
StatePatternDemo.java
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
System.out.println(context.getState().toString());
StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}
Output:
Player is in start state Start State Player is in stop state Stop State
Token state implementation at Bank Of America
package com.pifl.exercise.design_pattern.state.boaState;
import com.pifl.exercise.util.Util;
/**
* Demo. Token state in Bank of America.
* Token can have different state and depend on the state only certain actions
* can be performed.
* Token state: Enable, Disable, Revoke (there are more states like: deactivate, provision
* but only those 3 implemnted below).
* @author Ferry
*/
public class TokenStateDemo {
public static void main(String[] args) {
// Set initial state in token context
TokenContext context=new TokenContext(DisableState.getInstance());
// Perform task based on action.
context.getState().enableAction(context);
context.getState().validateAction(context);
context.getState().revokeAction(context);
context.getState().validateAction(context); // Invalid action.
}
}
/**
* Token context which holds the current token state.
* @author Ferry
*
*/
class TokenContext {
private TokenState state;
public TokenContext(TokenState initialState) {
this.state = initialState;
}
public TokenState getState() {
return state;
}
public void setState(TokenState state) {
this.state = state;
}
}
/**
* Token state abstract. This can also be an interface.
* This contains all the default actions that can be performed
* on the state machine.
* @author Ferry
*
*/
abstract class TokenState {
protected String stateName;
protected TokenState(String stateName) {
this.stateName = stateName;
}
public Boolean validateAction(TokenContext context) {
Util.println("Error: invalid state");
return false;
}
public Boolean disableAction(TokenContext context) {
Util.println("Error: invalid state");
return false;
}
public Boolean enableAction(TokenContext context) {
Util.println("Error: invalid state");
return false;
}
public Boolean revokeAction(TokenContext context) {
Util.println("Error: invalid state");
return false;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
}
class DisableState extends TokenState {
static private DisableState state = null;
private DisableState() {
super("DisableState");
}
public static DisableState getInstance() {
if (state == null)
state = new DisableState();
return state;
}
@Override
public Boolean enableAction(TokenContext context) {
Util.println("Perform enable action");
context.setState(EnableState.getInstance());
return true;
}
@Override
public Boolean revokeAction(TokenContext context) {
Util.println("Perform revoke action");
context.setState(RevokeState.getInstance());
return true;
}
}
class EnableState extends TokenState {
static private EnableState state = null;
private EnableState() {
super("EnableState");
}
public static EnableState getInstance() {
if (state == null)
state = new EnableState();
return state;
}
@Override
public Boolean validateAction(TokenContext context) {
Util.println("Peform validate action");
return true;
}
@Override
public Boolean disableAction(TokenContext context) {
Util.println("Perform disable action");
context.setState(DisableState.getInstance());
return true;
}
@Override
public Boolean revokeAction(TokenContext context) {
Util.println("Perform revoke action");
context.setState(RevokeState.getInstance());
return true;
}
}
class RevokeState extends TokenState {
static private RevokeState state = null;
public static RevokeState getInstance() {
if (state == null)
state = new RevokeState();
return state;
}
RevokeState() {
super("RevokeState");
}
@Override
public Boolean revokeAction(TokenContext context) {
Util.println("Perform revoke action");
return true;
}
}
Multiple Defaults
With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods. The following code explains how this ambiguity can be resolved.
public interface vehicle { default void print() { System.out.println("I am a vehicle!"); } } public interface fourWheeler { default void print() { System.out.println("I am a four wheeler!"); } }
First solution is to create an own method that overrides the default implementation.
public class car implements vehicle, fourWheeler { public void print() { System.out.println("I am a four wheeler car vehicle!"); } }
Second solution is to call the default method of the specified interface using super.
public class car implements vehicle, fourWheeler { public void print() { vehicle.super.print(); } }
An interface can also have static helper methods from Java 8 onwards.
public interface vehicle { default void print() { System.out.println("I am a vehicle!"); } static void blowHorn() { System.out.println("Blowing horn!!!"); } }
Code ToDo:
— Next —