Applying regex patterns – In java and javascript

Regex patterns are easier to write than to read. Analysing the following regex patterns might give a good idea of how to come up with meaningful regex patterns:


All alphabets

^[a-zA-Z]*$

All digit

^[0-9]*$

All alphabets+digits

^[0-9a-zA-Z]*$

Email format

^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$

Integers or decimals rounded to last two digits

^[0-9]+[.]?[0-9]{0,2}$

should be alphabets+digits with enclosed space

^[0-9a-zA-Z]+[0-9a-zA-Z\\s]*$

Can consist of Characters,space,dash,dot,pound,slash,quote

^[0-9a-zA-Z\\s\\-.#\\/’]*$

Can consist space,dash,quote

^[0-9a-zA-Z\\s\\-‘]*$

Can have 5 or 9 digits or; 10 digits when dash is included

^(d{5}|d{9}|d{5}-d{4})$
for example ZIP

Format for phone (US)

^([(]{1}[0-9]{3}[)]{1}[.| |-]{0,1}|^[0-9]{3}[.|-| ]?)?[0-9]{3}(.|-| )?[0-9]{4}$

should have 9 Digits and can have one dash
for instance TAXID

^[0-9]{9}$ (method to validate this in java below)

Should have 9 Digits

^[0-9]{9}$
For example SSN

private static boolean checkTAXID(String val) {
        boolean flag = false;
        String[] t = val.split("-");
        if (t.length < 2) {
            if (checkRegExp(val, "^[0-9]{9}$")) {
                flag = true;
            }
        }
        if (t.length == 2) {
            if ((val.length() == 10) && checkRegExp(t[0], "^[0-9]*$")
                    && checkRegExp(t[1], "^[0-9]*$")) {
                flag = true;
            }
        }
        if (t.length > 2) {
            flag = false;
        }
        return flag;
    }
 Below is a java method to validate the regular expresssions above:
	private static boolean checkRegExp(String val, String regExp) {
		 boolean flag = false;
		 if (null != val && !val.trim().equals("")) {
		 flag = val.matches(regExp);
		 }
		 return flag;
		 }

Here is a utility method to validate dates in various formats using regular expressions to recognize patterns and the SimpleDateFormat class to validate further:

public static final String returnedDateFormatString = "MM/dd/yyyy";

public static String validateDate(String paramDate) {
    DateFormat returnedDateFormat = new SimpleDateFormat(
            returnedDateFormatString);
    String regExp1 = "^[0-1]\\d[0-3]\\d[1-2]\\d{3}$";
    // -- matches MMDDYYYY
    String regExp2 = "^[0-1]*\\d[/.][0-3]*\\d[/.][1-2][\\d]{3}$";// --
    // matches MM/DD/YYYY (with or without leading zeroes for MM and DD)
    String regExp3 = "^[0-1]*\\d[/.][0-3]*\\d[/.][\\d]{2}$";
    // (matches MM/DD/YY)(with or without leading zeroes for MM and DD)
    String regExp4 = "^[1-2][\\d]{3}[/.][0-1]*\\d[/.][0-3]*\\d$";
    // matches YYYY/MM/DD (with or without/ leading zeroes for MM and DD)
    String regExp5 = "^t$";// -- matches t
    String regExp6 = "^t[\\+\\-][\\d]+$";// -- matches t-# and t+#
    DateFormat dateFormat = null;
    Date date = null;
    if (checkRegExp(paramDate, regExp1)) {
        dateFormat = new SimpleDateFormat("MMddyyyy");
        try {
            date = dateFormat.parse(paramDate);
            if (dateFormat.format(date).equals(paramDate)) {
                return returnedDateFormat.format(date);
            }
        } catch (ParseException e) {
            date = null;
        }

    } else if (checkRegExp(paramDate, regExp2)) {
        String dateFormatArray[] = { "MM/dd/yyyy", "MM/d/yyyy",
                "M/dd/yyyy", "M/d/yyyy" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "MM.dd.yyyy", "MM.d.yyyy",
                "M.dd.yyyy", "M.d.yyyy" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    } else if (checkRegExp(paramDate, regExp3)) {
        String dateFormatArray[] = { "MM/dd/yy", "MM/d/yy", "M/dd/yy",
                "M/d/yy" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "MM.dd.yy", "MM.d.yy", "M.dd.yy",
                "M.d.yy" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    } else if (checkRegExp(paramDate, regExp4)) {
        String dateFormatArray[] = { "yyyy/MM/dd", "yyyy/MM/d",
                "yyyy/M/dd", "yyyy/M/d" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "yyyy.MM.dd", "yyyy.MM.d",
                "yyyy.M.dd", "yyyy.M.d" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    }
    return null;
}

Corresponding javascript method to validate regex:

function executePattern(val, regex) {
            var flg = false;
            var re = new RegExp(regex);
            if (val.length > 0 && !val.match(re)) {
                flg = true;
            }
            return flg;
        }

Here are some explanations for a few regex patterns:

^[0-1]d[0-3]d[1-2]d{3}$|^[0-1]*d[/.][0-3]*d[/.][1-2][d]{3}$|^[0-1]*d[/.][0-3]*d[/.][d]{2}$|^[1-2][d]{3}[/.][0-1]*d[/.][0-3]*d$|^t$|^t[+-][d]+$

break up to explaining the pieces
^[0-1]d[0-3]d[1-2]d{3}$ — matches MMDDYYYY
^[0-1]*d[/.][0-3]*d[/.][1-2][d]{3} — matches MM/DD/YYYY (with or without leading zeroes for MM and DD)
^[0-1]*d[/.][0-3]*d[/.][d]{2} — matches MM/DD/YY (with or without leading zeroes for MM and DD)
^[1-2][d]{3}[/.][0-1]*d[/.][0-3]*d — matches YYYY/MM/DD (with or without leading zeroes for MM and DD)
^t — matches t
^t[+-][d]+$ — matches t-# and t+#
http://regexpal.com/ is a good site to see how your regex patterns match input data.

Back to Basics – Subtler Nuances – Generics

public class Person {
	String person;

	public Person() {
	}

	public Person(String person) {
		this.person = person;
	}

	public String getName() {
		return this.person;
	}
}

public class Driver extends Person {
	String driver;

	public Driver(String driver) {
		this.driver = driver;
	}

	public String getDriver() {
		return this.driver;
	}

	public String getName() {
		return this.driver;
	}
}
import java.util.*;

public class Test {
	public void test() {
		List<String> list = new ArrayList<String>();
		list.add("Matty");
		for (String s : list) {
			System.out.println(s);
		}
	}

	public static void main(String[] args) {
		new Test().test();
	}
}
/*

The correct way to use a simple generic type

D:\work\projects\generics>java Test
Matty
*/

import java.util.*;

public class Test3 {
	public void test() {
		List<String> list = new ArrayList<String>();
		List<Object> object = list;
		object.add("jacob");
		list.add("Matty");
		for (String s : list) {
			System.out.println(s);
		}
	}

	public static void main(String[] args) {
		new Test3().test();
	}
}
/*

List<Object> is not a supertype of List<String> or List of any type for that matter!

Test3.java:7: incompatible types
found   : java.util.List<java.lang.String>
required: java.util.List<java.lang.Object>
List<Object> object = list;
*/
import java.util.*;

public class Test4 {
	public void test() {
		List<String> stringList = new ArrayList<String>();
		stringList.add("jacob");
		stringList.add("Matty");
		List<?> list = new ArrayList<String>();
		list = stringList;
		for (Object s : list) {
			System.out.println(s);
		}
	}

	public static void main(String[] args) {
		new Test4().test();
	}
}
/*

List<?> is a supertype of any List<genericType> It is used as a wildcard.
We can read elements from this list and assign them Object since whatever type of collection, it always contain objects
However it is not safe to add any element to this list including Object because
the added element would have to be a subtype of the actual type of this list
and since we dont know the actual type it is illegal to add any element to it! Except null.

D:\work\projects\generics>java Test4
jacob
Matty
*/
import java.util.*;

public class Test5 {
	public void test() {
		List<String> stringList = new ArrayList<String>();
		stringList.add("jacob");
		stringList.add("Matty");
		List<?> list = new ArrayList<String>();
		list.add((Object) ("Matty"));
		list = stringList;
		for (Object s : list) {
			System.out.println(s);
		}
	}

	public static void main(String[] args) {
		new Test5().test();
	}
}
/*

List<?> is a supertype of any List<genericType>
We can read elements from this list and assign them Object since whatever type of collection, it always contain objects
However it is not safe to add any element to this list including Object because
the added element would have to be a subtype of the actual type of this list
and since we dont know the actual type it is illegal to add any element to it! Except null

Test5.java:10: cannot find symbol
symbol  : method add(java.lang.Object)
location: interface java.util.List<capture#145 of ?>
list.add((Object)("Matty"));

*/

import java.util.*;

public class Test6 {
	public void test() {
		List<String> stringList = new ArrayList<String>();
		stringList.add("jacob");
		stringList.add("Matty");
		List<?> list = new ArrayList<String>();
		list.add(("Matty"));
		list = stringList;
		for (Object s : list) {
			System.out.println(s);
		}
	}

	public static void main(String[] args) {
		new Test6().test();
	}
}
/*

List<?> is a supertype of any List<genericType>
We can read elements from this list and assign them Object since whatever type of collection, it always contain objects
However it is not safe to add any element to this list including Object because
the added element would have to be a subtype of the actual type of this list
and since we dont know the actual type it is illegal to add any element to it! Except null

Test6.java:10: cannot find symbol
symbol  : method add(java.lang.String)
location: interface java.util.List<capture#145 of ?>
list.add(("Matty"));

*/
import java.util.*;

public class Test7 {
	public void test() {
		List<?> driverList = new ArrayList<Driver>();
		driverList.add(new Driver("jacob"));
		driverList.add(new Driver("Matty"));
		for (Driver s : driverList) {
			System.out.println(s);
		}
	}

	public static void main(String[] args) {
		new Test7().test();
	}
}
/*
List<?> is a supertype of any List<genericType>
We can read elements from this list and assign them Object since whatever type of collection, it always contain objects
However it is not safe to add any element to this list including Object because
the added element would have to be a subtype of the actual type of this list
and since we dont know the actual type it is illegal to add any element to it! Except null

D:\work\projects\generics>javac Test7.java
Test7.java:7: cannot find symbol
symbol  : method add(Driver)
location: interface java.util.List<capture#466 of ?>
driverList.add(new Driver("jacob"));
^
Test7.java:8: cannot find symbol
symbol  : method add(Driver)
location: interface java.util.List<capture#145 of ?>
driverList.add(new Driver("Matty"));
^
Test7.java:9: incompatible types
found   : java.lang.Object
required: Driver
for(Driver s:driverList)
^
3 errors
*/


import java.util.*;

public class Test8 {
	public void test() {
		List<Driver> driverList = new ArrayList<Driver>();
		driverList.add(new Driver("jacob"));
		driverList.add(new Driver("Matty"));
		List<?> genericList = driverList;
		for (Object s : genericList) {
			System.out.println(s);
		}
	}

	public static void main(String[] args) {
		new Test8().test();
	}
}
/*

List<?> is a supertype of any List<genericType>
We can read elements from this list and assign them Object since whatever type of collection, it always contain objects
However it is not safe to add any element to this list including Object because
the added element would have to be a subtype of the actual type of this list
and since we dont know the actual type it is illegal to add any element to it! Except null

D:\work\projects\generics>java Test8
Driver@addbf1
Driver@42e816
*/

import java.util.*;

public class Test9 {
	public void test() {
		List<Driver> driverList = new ArrayList<Driver>();
		driverList.add(new Driver("jacob"));
		driverList.add(new Driver("Matty"));
		List<?> genericList = driverList;
		for (Object s : genericList) {
			System.out.println(((Driver) s).getDriver());
		}
	}

	public static void main(String[] args) {
		new Test9().test();
	}
}
/*

List<?> is a supertype of any List<genericType>
We can read elements from this list and assign them Object since whatever type of collection, it always contain objects
However it is not safe to add any element to this list including Object because
the added element would have to be a subtype of the actual type of this list
and since we dont know the actual type it is illegal to add any element to it! Except null

D:\work\projects\generics>java Test9
jacob
Matty
*/
import java.util.*;

public class Test11 {
	public void test() {
		List<Driver> driverList = new ArrayList<Driver>();
		driverList.add(new Driver("jacob"));
		driverList.add(new Driver("Matty"));
		List<Driver> genericList = driverList;
		for (Driver s : genericList) {
			System.out.println(s.getDriver());
		}
	}

	public static void main(String[] args) {
		new Test11().test();
	}
}
/*
The correct way to assign a generic list to another when we dont use wildcards

D:\work\projects\generics>java Test11
jacob
Matty
*/

import java.util.*;

public class Test12 {
	public void test() {
		List<Driver> list1 = new ArrayList<Driver>();
		list1.add(new Driver("jacob"));
		list1.add(new Driver("Matty"));
		List<Person> list2 = new ArrayList<Person>();
		list2.add(new Person("Jimmy"));
		printName(list1);
		printName(list2);
	}

	public void printName(List<? extends Person> list) {
		for (Person s : list) {
			System.out.println(s.getName());
		}
	}

	public static void main(String[] args) {
		new Test12().test();
	}
}
/*

The list of generic type <? extends Person> can accept any object which is a subtype of Person
The disadvanatage is illegal to add objects to this generic list

D:\work\projects\generics>java Test12
jacob
Matty
Jimmy
*/
import java.util.*;

public class Test13 {
	public void test() {
		List<Driver> list1 = new ArrayList<Driver>();
		list1.add(new Driver("jacob"));
		list1.add(new Driver("Matty"));
		addName(list1);
	}

	public void addName(List<? extends Person> list) {
		list.add(new Driver("abc"));
		list.add(new Person("xyz"));
	}

	public static void main(String[] args) {
		new Test13().test();
	}
}
/*

The list of generic type <? extends Person>  can accept any object which is a subtype of Person
The disadvanatage is illegal to add objects to this generic list

D:\work\projects\generics>javac Test13.java
Test13.java:13: cannot find symbol
symbol  : method add(Driver)
location: interface java.util.List<capture#145 of ? extends Person>
list.add(new Driver("abc"));
^
Test13.java:14: cannot find symbol
symbol  : method add(Person)
location: interface java.util.List<capture#339 of ? extends Person>
list.add(new Person("xyz"));
*/
import java.util.*;

public class Test15 {
	public void test() {
		List<Driver> list = new ArrayList<Driver>();
		list.add(new Driver("jacob"));
		list.add(new Driver("Matty"));
		String[] arr = new String[1];
		arr[0] = "mj";
		addArrToList(arr, list);
	}

	public void addArrToList(String[] arr, List<? extends Person> list) {
		for (String name : arr) {
			list.add(name);
		}
	}

	public static void main(String[] args) {
		new Test15().test();
	}
}
/*
The list of generic type <? extends Person> can accept any object which is a subtype of Person
The disadvanatage is illegal to add objects to this generic list

D:\work\projects\generics>javac Test15.java
Test15.java:17: cannot find symbol
symbol  : method add(java.lang.String)
location: interface java.util.List<capture#145 of ? extends Person>
list.add(name);
^
1 error
*/

import java.util.*;

public class Test16 {
	public void test() {
		Collection<Person> list = new ArrayList<Person>();
		list.add(new Person("jacob"));
		list.add(new Person("Matty"));
		Driver[] arr = new Driver[1];
		arr[0] = new Driver("mj");
		addArrToList(arr, list);// T inferred to be Person
	}

	public <T> void addArrToList(T[] arr, Collection<T> list)// generic method
																// declaration
	{
		for (T t : arr) {
			list.add(t);
		}
		for (T x : list) {
			System.out.println(((Person) x).getName());
		}
	}

	public static void main(String[] args) {
		new Test16().test();
	}
}
/*

addArrToList is a generic method. Just like type declarations, method declarations can be generic.
The method overcomes the disadvantage that was encountered in the previous example.
i.e. it allows objects to be added to generic list.
The compiler infers the type argument for us, based on the types of the actual arguments. It
will generally infer the most specific type argument that will make the call type-correct.

Object[] oa = new Object[100];
Collection<Object> co = new ArrayList<Object>();
fromArrayToCollection(oa, co);// T inferred to be Object
String[] sa = new String[100];
Collection<String> cs = new ArrayList<String>();
fromArrayToCollection(sa, cs);// T inferred to be String
fromArrayToCollection(sa, co);// T inferred to be Object
Integer[] ia = new Integer[100];
Float[] fa = new Float[100];
Number[] na = new Number[100];
Collection<Number> cn = new ArrayList<Number>();
fromArrayToCollection(ia, cn);// T inferred to be Number
fromArrayToCollection(fa, cn);// T inferred to be Number
fromArrayToCollection(na, cn);// T inferred to be Number
fromArrayToCollection(na, co);// T inferred to be Object
fromArrayToCollection(na, cs);// compile-time error

D:\work\projects\generics>java Test16
jacob
Matty
mj
*/

Back to Basics – Subtler Nuances – Part Two

FinalReferenceInitializer.java

public class FinalReferenceInitializer {
	static String staticVar;

	public FinalReferenceInitializer() {
		initializeFinalVar();
		staticVar = "new Value for static var";
		System.out.println(staticVar);
	}

	public static void initializeFinalVar() {
		staticVar = new String("Static var Initializes");
		System.out.println(staticVar);
	}

	public static void main(String args[]) {
		FinalReferenceInitializer fri = new FinalReferenceInitializer();
		System.out.println(FinalReferenceInitializer.staticVar);
	}
}
/*
Only static variables and static methods can be called before a constructor completes.
D:\appletree>java FinalReferenceInitializer
Static var Initializes
new Value for static var
new Value for static var
*/

CallTest.java

class Factory {
	{
		System.out.println("A1");// 7 - instance init blocks run - right after
									// call to super()
	}
	static {// 1 static block executes - when Factory class is loaded - first
			// one to do so
		System.out.println("A9");// 1.a
	}

	public Factory() {// 6 default constructor called - which calls super()
		System.out.println("A2");// 8
	}
};

class CementFactory extends Factory {
	{
		System.out.println("A8");// 9 - instance init blocks run right after
									// call to super()
	}
	static {// 2 static block executes - when CementFactory class is loaded
			// -second to do so
		System.out.println("A3");// 2.a
	}

	public CementFactory() {// 5 default constructor called - which calls
							// super()
		System.out.println("A4");// 10
	}

	static {// 3 second static block executes in sequence- at class loading time
		System.out.println("A5");// 3.a
	}
};

class MyCementFactory extends CementFactory {
	public static void main(String args[]) {
		System.out.println("A6");// 4 first line in main executed after class is
									// loaded
		new MyCementFactory();// calls default constructor which in turn calls
								// super()
		System.out.println("A7");// 9
	}
};
/**
D:\appletree>java MyCementFactory
A9
A3
A5
A6
A1
A2
A8
A4
A7
**/

WidenTest.java

public class WidenTest {
	static void overload(int x) {
		System.out.println("Integer");
	}

	static void overload(float x) {
		System.out.println("float");
	}

	public static void main(String[] args) {
		byte b = 5;
		overload(b);
	}
}

/**
When an exact match is not found in an overloaded the smallest arg that is wider than the parameter is selected

D:\appletree>java WidenTest
Integer
*/

NarrowTest.java

public class NarrowTest {
	static void overload(byte x) {
		System.out.println("Integer");
	}

	static void overload(short x) {
		System.out.println("float");
	}

	public static void main(String[] args) {
		int b = 5;
		overload(b);
	}
}
/**

D:\appletree>javac NarrowTest.java
NarrowTest.java:12: cannot find symbol
symbol  : method overload(int)
location: class NarrowTest
overload(b);
^
1 error
*/

BoxTest.java

public class BoxTest {
	static void overload(Integer x) {
		System.out.println("Boxed");
	}

	static void overload(long x) {
		System.out.println("Widened");
	}

	public static void main(String[] args) {
		int b = 5;
		overload(b);
	}
}

/**
Widening beats auto boxing
reason -> widening existed prior to java 5 and hence backward compatibility is supported
D:\appletree>java BoxTest
Widened
*/

VarArgTest1.java

public class VarArgTest1 {
	static void overload(int x, int y) {
		System.out.println("Backward compatible");
	}

	static void overload(int... x) {
		System.out.println("Var arg");
	}

	public static void main(String[] args) {
		int b = 5;
		int c = 7;
		overload(b, c);
	}
}

/**
Method call is now backward compatible!
D:\appletree>java VarArgTest1
Backward compatible
*/

VarArgTest2.java

public class VarArgTest2 {
	static void overload(float x, float y) {
		System.out.println("Backward compatible");
	}

	static void overload(int... x) {
		System.out.println("Var arg");
	}

	public static void main(String[] args) {
		int b = 5;
		int c = 7;
		overload(b, c);
	}
}
/**
Method call is now backward compatible!
Widening beats var args
D:\appletree>java VarArgTest2
Backward compatible
*/

AutoBoxingVsVarArgs.java

public class AutoBoxingVsVarArgs {
	static void overload(Integer x, Integer y) {
		System.out.println("Boxed");
	}

	static void overload(int... x) {
		System.out.println("Var Arg");
	}

	public static void main(String[] args) {
		int b = 5;
		int c = 6;
		overload(b);
		overload(b, c);
	}
}

/**
var args are catch all arguments and have the lowest precedence

D:\appletree>java AutoBoxingVsVarArgs
Var Arg
Boxed
*/

WrapperWidening.java

class WrapperWidening {
	void widenWrapper(Integer y) {
		System.out.println("Accepted?");
	}

	public static void main(String[] args) {
		Short x = new Short(2 + "");
		widenWrapper(x);
	}
}
/**
D:\appletree>javac WrapperWidening.java
WrapperWidening.java:9: widenWrapper(java.lang.Integer) in WrapperWidening cannot be applied to (java.lang.Short)
widenWrapper(x);
^
1 error
*/

ArrayWidening.java

class ArrayWidening {
	void widenArray(int[] c) {
		System.out.println("Accepted?");
	}

	public static void main(String[] args) {
		byte[] b = new byte[2];
		widenArray(b);
	}
}
/**
D:\appletree>javac ArrayWidening.java
ArrayWidening.java:9: widenArray(int[]) in ArrayWidening cannot be applied to (byte[])
widenArray(b);
^
1 error
*/

BoxAndWiden.java

class BoxAndWiden {
	void boxAndWiden(Integer z) {
		System.out.println("Accepted?");
	}

	public static void main(String[] args) {
		short c = 4;
		boxAndWiden(c);
	}
}
/**
Fails because short would be boxed to Short but Short cannot be widened to Integer

D:\appletree>javac BoxAndWiden.java
BoxAndWiden.java:9: boxAndWiden(java.lang.Integer) in BoxAndWiden cannot be applied to (short)
boxAndWiden(c);
^
1 error
*/

WidenBox.java


class WidenBox {
	public static void main(String[] args) {
		int c = 1;
		boxInteger(c);
		widenBox(c);
		boxVarArg(c, c);
		widenVarArg(c, c);
	}

	static void boxInteger(Integer i) {// making this any other Wrapper type
										// won't work
		System.out.println(i.intValue());
	}

	static void widenBox(Object o) {
		Integer i = (Integer) o;
		System.out.println(i.intValue());
	}

	static void boxVarArg(Integer... i) {// making this any other Wrapper type
											// won't work
		System.out.println("int boxed to Integer and var-arged");
	}

	static void widenVarArg(long... i) {
		System.out.println("int widened to long and var-arged");
	}
}
/**
int c is boxed to Integer
int c is boxed to Integer, Integer widened to Object
int c is boxed and assigned to var arg
int c is widened and assigned to var arg

D:\appletree>java WidenBox
1
1
int boxed to Integer and var-arged
int widened to long and var-arged

*/

Back to Basics – Subtler Nuances – Part One

IllegalClass.java

//interfaces do not contain static methods – they are not overridden
public interface IllegalClass {
	public static void illegalMethod();
}

Parent.java

public class Parent {
	public static void toDo() {
		System.out.println("The Parent speaks!!");
	}
}

class Child extends Parent {
	public static void toDo() {
		System.out.println("The Child speaks!!");

	}

	public static void main(String args[]) {
		Parent parent = new Parent();
		parent.toDo();
		Parent child = new Child();
		child.toDo();
		Child childOfParent = new Child();
		childOfParent.toDo();
	}
}
/**
Note static toDo is not overridden. The execution sequence is not looked up at runtime!
And hence static methods cannot be contained in an interface.
C:\appletree>java Parent

The Parent speaks!!
The Parent speaks!!
The Child speaks!!
*/

ITooPromiseImplVarTest.java

class IPromiseImpl {
	String name = "Mattiz";
}

public class ITooPromiseImplVarTest extends IPromiseImpl {
	String name = "Porsche";

	public static void main(String[] args) {
		ITooPromiseImplVarTest iPromiseImpl = new ITooPromiseImplVarTest();
		System.out.println(iPromiseImpl.name);
		IPromiseImpl iPromise = new ITooPromiseImplVarTest();
		System.out.println(iPromise.name);
	}
};
/**
D:\appletree>java ITooPromiseImplVarTest
Porsche
Mattiz
*/

Original.java

public interface Original {
	public void doPicasso();
}

interface Duplicate {
	public void doMattisse(final int var);
}

interface Extender extends Original, Duplicate {
	public void cheapSkatePainting();
}

class AllRounder implements Extender {
	public void doPicasso() {
		System.out.println("Picasso Art Piece");
	}

	public void doMattisse(final int count) {
		System.out.println("Mattisse Art Piece number " + count);
	}

	public void cheapSkatePainting() {
		final int count = 10;
		System.out.println("My sad first attempt at painting " + count);
	}

	public static void main(String args[]) {
		AllRounder ronaldo = new AllRounder();
		ronaldo.doPicasso();
		int count = 11;
		ronaldo.doMattisse(count);
		ronaldo.cheapSkatePainting();
	}
}
/*
An interface can extend multiple interfaces!!

C:\appletree>java Original
Picasso Art Piece
Mattisse Art Piece number 11
My sad first attempt at painting 10
*/

MyPromise.java

public interface MyPromise{
int length = 10;
}
class MyPromiseImpl implements MyPromise
{
int length = MyPromise.length;//compiles fine
MyPromise.length = 25;//does not compile. length is by default - public static final in the interface
};

IPromise.java

public interface IPromise {
	void toDo();
}

class IPromiseImpl implements IPromise {
	private void toDo() {
		System.out.println("Promised");
	}
}
/*

toDo() is by default public in IPromise interface. It is overridden by a class in which toDo has lower visibility - compile time error

D:\appletree>javac IPromise.java
IPromise.java:7: toDo() in IPromiseImpl cannot implement toDo() in IPromise; attempting to assign weaker access privileges; was public
private void toDo(){
^
1 error
*/

IPromiseAnExceptionImpl.java

interface IPromiseAnException {
	public void toDo() throws Exception;
}

public class IPromiseAnExceptionImpl implements IPromiseAnException {
	public static void main(String[] args) {
		IPromiseAnExceptionImpl iPromiseImpl = new IPromiseAnExceptionImpl();// compiles
																				// fine
		iPromiseImpl.toDo();// compiles fine
		IPromiseAnException iPromise = new IPromiseAnExceptionImpl();// compiles
																		// fine
		iPromise.toDo();// compile time error
	}

	public void toDo() {
		System.out.println("Implemented");
	}
}
/*

Compiler sees an exception thrown by parent class, overriding occurs at runtime

D:\appletree>javac IPromiseAnExceptionImpl.java
IPromiseAnExceptionImpl.java:9: unreported exception java.lang.Exception; must be caught or declared to be thrown
iPromise.toDo();
^
1 error
*/

ITooPromiseAnExceptionImpl.java

import java.sql.SQLException;

class IPromiseAnExceptionImpl implements IPromiseAnException {
	public void toDo() throws Exception {
		System.out.println("Implemented");
	}
}

public class ITooPromiseAnExceptionImpl extends IPromiseAnExceptionImpl {
	public void toDo() throws SQLException {
		System.out.println("Done");
	}

	public static void main(String[] args) {
		try {
			ITooPromiseAnExceptionImpl iPromiseImpl = new ITooPromiseAnExceptionImpl();// compiles
																						// fine
			iPromiseImpl.toDo();
			IPromiseAnExceptionImpl iPromise = new ITooPromiseAnExceptionImpl();// compiles
																				// fine
			iPromise.toDo();// runtime selection of execution call in either
							// case.
		} catch (Exception e) {
			// do something
		}
	}
};
/*
SQL Exception subset of Exception - hence no compile time error
D:\appletree>javac ITooPromiseAnExceptionImpl.java

D:\appletree>java ITooPromiseAnExceptionImpl
Done
Done
*/

CastTester.java

//result of int sized or smaller expresssions is always an int
public class CastTester {
	public void toDo() {
		byte b = 2;// valid -> (byte)27
		char c = 8;// valid -> (char)89
		short m = 90;// valid -> (short)90
		byte a = (b + c);
		// expression equates to int, no casting done.. compile time error
	}

	public static void main(String args[]) {
		CastTester castTester = new CastTester();
		castTester.toDo();
	}
}
/*
C:\appletree>javac CastTester.java
CastTester.java:7: possible loss of precision
found   : int
required: byte
byte a = (b+c);
^
1 error
*/

CastTester2.java

//result of int sized or smaller expresssions is always an int
public class CastTester2 {
	public void toDo() {
		byte b = 2;// valid -> (byte)27
		char c = 8;// valid -> (char)89
		short m = 90;// valid -> (short)90
		short a = (b + c);// expression evaluates to int at runtime.. no
							// explicit cast to short
	}

	public static void main(String args[]) {
		CastTester2 castTester2 = new CastTester2();
		castTester2.toDo();
	}
}
/*
C:\appletree>javac CastTester2.java
CastTester2.java:7: possible loss of precision
found   : int
required: short
short a = (b+c);
^
1 error
*/

CastTester3.java

//result of int sized or smaller expresssions is always an int
public class CastTester3 {
	public void toDo() {
		byte b = 2;// valid -> (byte)27
		char c = 8;// valid -> (char)89
		short m = 90;// valid -> (short)90
		float f = 34.4;// not valid double assigned to float..no implicit cast
						// to float
	}

	public static void main(String args[]) {
		CastTester3 castTester3 = new CastTester3();
		castTester3.toDo();
	}
}
/*
C:\appletree>javac CastTester3.java
CastTester3.java:7: possible loss of precision
found   : double
required: float
float f = 34.4;//
^
1 error]
*/

MyOuter.java

public class MyOuter {
	static class MyNested {
		public MyNested() {
			System.out.println("Body of Nested Inner Class");
		}
	}

	public static void main(String args[]) {
		MyOuter.MyNested myNested = new MyOuter.MyNested();
	}
}
/*
C:\appletree>java MyOuter
Body of Nested Inner Class
*/

Java 6 Refresher

JDK 4 introduced the assert keyword

JDK 5 introduced generics, autoboxing, enumerations, var-args, enhanced for loop.

New keywords in Java

assert (since 1.4)
enum (since 1.5)

keywords to watch out for

const
strictfp
goto

JavaBean standard for getter and setter for boolean:

getXXX
setXXX / isXXX

JavaBean standard for getter and setter for listners:

addXXXListener(XXXListener xxxlistener)
removeXXXListener(XXXListener xxxlistener)

The strictfp non access modifier

Applicable to class and method
Marking a class strictfp means that any method code in the class/method will conform to a floating point standard without relying on the underlying operating system.

Points to note:

All variables declared in an interface are implicitly “public static final”
All methods in an interface are implicitly “public abstract”
An interface implicitly is always abstract
An interface method cannot be static since interface methods are meant to be overrridden and static methods cannot be overridden.
Interface methods cannot be native/strictfp
Abstract classes have to be explictly declared “abstract”
An interface may have public/default access modifiers just like classes
An interface can exend more than one interfaces
Abstract classes can extend other abstract classes
Abstract classes can implement one or more interfaces.
Abstract classes can never contain private methods since all its methods are meant to be overridden.
A native method must end with a semicolon with the implementation omitted.
Native methods are implemented in platform dependent code.

Flavors of the final modifier

final methods cannot be overrridden
final variables cannot change the value assigned to them
final classes cannot be extended
final references cannot be used to reference another object
*final reference variables must be initialized before the constructor completes

the abstract modifer cannot be combined with the static modifier for methods since abstract implies overriding while static methods cannot be overrridden.

“synchronized” modifier applies to code blocks and methods
*”sychronized” can be combined with static/ final

class TestFinalVar {
	public void testFinalVar(final int a, final int b) {// a and b cannot be
														// reassigned //within
														// this method
		System.out.println(a + b);
	}

	public static void main(String args[]) {
		TestFinalVar tfv = new TestFinalVar();
		tfv.testFinalVar(2, 3);
	}
}

Var-args:
Things to remember:
Only one var-arg is allowed in a list of arguemnts
A var-arg always has to be the last in a list of arguments.
var-args can be part of arguments to a constructor
more on var-args…

Note:
Negative numbers in Java are represented by 2’s complement notation:
1. subtract 1
2. take 1’s complement of the result(replace 1 with 0 and vice versa)

byte(8 bits=1 byte)
short(16 bits=2 bytes)
int(32 bits-4 bytes) float(4 bytes-signed)
long(64 bits=8 bytes) double(8 bytes-signed)
boolean is OS dependent

Variables are always created on the stack while objects on the heap

Transient variables:
By declaring a variable transient you are asking the JVM to skip it during serialization

Volatile variables:
These are used to transmit single variables between threads. Synchronized blocks are preferred to volatile variables. Volatile vars will never use local copies. They will use shared memory for reading and writing. If you want to transfer two or more variables there is a risk that reading will be done while the writing has not yet finished. “volatile” indicates that the var may be used by other threads.

Nested classes:

An inner class can be static/ non-static/ abstract/ final/ public/ private/ protected
A method local class can be instantiated only inside a method where it is defined, a local block, a static initializer or an instance intializer (need more info)
It cannot access the local vars of the enclosing method unless they are declared final. The only modifier for a method local class is abstract/ final

class Outer {
	static class StaticNested {
		public void print() {
			System.out.println("Hallo World");
		}
	}

	public static void main(String[] args) {
		Outer.StaticNested ou = new Outer.StaticNested();
                // instance of StaticNested is not required.
		ou.print();
	}
}

As a separate class:

enum TShirtSize {// enum as a separate class
	SMALL, MEDIUM, LARGE,
}

public class TShirtTest {
	public void print() {
		TShirtSize tss = TShirtSize.SMALL;
		System.out.println("I always wanted " + tss);
	}

	public static void main(String args[]) {
		TShirtTest tt = new TShirtTest();
		tt.print();
	}
}

D:\java6\work>java TShirtTest
I always wanted SMALL

As a separate class:

enum ShirtSize {// enum as a separate class
	SMALL, MEDIUM, LARGE,
}

class Shirt {
	ShirtSize ss;
};

public class ShirtTest {
	public void print() {
		Shirt shirt = new Shirt();
		shirt.ss = ShirtSize.LARGE;
		System.out.println("I always wanted " + shirt.ss);
	}

	public static void main(String args[]) {
		ShirtTest tt = new ShirtTest();
		tt.print();
	}
}
D:\java6\work>java ShirtTest
I always wanted LARGE

As a class member:

class BallTest {
	enum Ball {// enum as a a class member
		SMALL, MEDIUM, LARGE,
	}

	public void print() {
		System.out.println("I always wanted " + Ball.MEDIUM);
	}

	public static void main(String args[]) {
		BallTest bt = new BallTest();
		bt.print();
	}
}
D:\java6\work>java BallTest
I always wanted MEDIUM

*Enum declarations outside a class must not be marked static/ final/ abstract/ private/ protected

enum with a constructor and method

enum Weight {// enum with a constructor and method
	LIGHT(20), MEDIUM(40), HEAVY(80);// note semicolon
	Weight(int pounds) {
		this.pounds = pounds;
	}

	public int getPounds() {// method
		return pounds;
	}

	private int pounds;;// instance var after enum value declaration
}

public class WeightTest {
	public static void main(String args[]) {
		Weight bert = Weight.LIGHT;
		Weight amy = Weight.MEDIUM;
		Weight brown = Weight.HEAVY;
		System.out.println(bert.getPounds() + "  " + amy.getPounds() + "  "
				+ brown.getPounds());
	}
};
D:\java6\work>java WeightTest
20  40  80

The compiler looks only at the reference type, not the instance type. At runtime the actual instance is looked up. Only overridden instance methods are dynamically invoked based on the real object’s type. Not static methods, not variables. But which overloaded version of the method to be called is decided at based on the reference type of the argument passed at compile time.

class Parent {
	public void study() throws Exception {
	}
};
class Child extends Parent {
	public void study() {
	}
}
public class CompilerVsRuntimeTest {
	public static void main(String[] args) {
		Parent p = new Parent();
		Child c = new Child();
		Parent pc = new Child();
		c.study();// ok
		pc.study();// compiler sees exception thrown
	}
}
D:\java6\work>javac CompilerVsRuntimeTest.java
CompilerVsRuntimeTest.java:17: unreported exception java.lang.Exception; must be
caught or declared to be thrown
pc.study();//compiler sees exception thrown
^
1 error
class Parent {
	public void groan() {
		System.out.println("Grooooooan");
	}
};
class Child extends Parent {
	public void groan() {
		System.out.println("Yeaaaaaaaaaaah!!");
	}

	public void play() {
		System.out.println("Will I be called?");
	}
};
public class InheritanceTest {
	public static void main(String[] args) {
		Parent p = new Parent();
		Parent c = new Child();// Child is the father of man?
		p.groan();
		c.groan();
		c.play();
	}
}
D:\java6\work>javac InheritanceTest.java
InheritanceTest.java:22: cannot find symbol
symbol  : method play()
location: class Parent
c.play();
^
class Parent {
	public void groan() {
		System.out.println("Grooooooan");
	}
};

class Child extends Parent {
	public void groan() {
		System.out.println("Yeaaaaaaaaaaah!!");
	}

	public void play() {
		System.out.println("Will I be called?");
	}
};

public class InheritanceTest {
	public static void main(String[] args) {
		Parent p = new Parent();
		Parent c = new Child();// Child is the father of man?
		p.groan();
		c.groan();
		// c.play();
	}
}
D:\java6\work>java InheritanceTest
Grooooooan
Yeaaaaaaaaaaah!!
class Parent {
};

class Child extends Parent {
};

public class OverloadTest {
	public void doStuff(Parent p) {
		System.out.println("Parent version");
	}

	public void doStuff(Child c) {
		System.out.println("Child version");
	}

	public static void main(String[] args) {
		Parent p = new Parent();
		Parent c = new Child();// Child is the father of man?
		OverloadTest ot = new OverloadTest();
		ot.doStuff(p);
		ot.doStuff(c);
	}
}
D:\java6\work>java OverloadTest
Parent version
Parent version

As of Java5 you are allowed to change the return type of the overriding method as long as the new return type is a subtype of the declared return type of the superclass method.

A class that implements an interface must follow all the rules for legal overrides for the methods it implements.

Only static variables and methods can be accessed as part of the call to super() or this().

This is because instance methods cannot be run before the super() call returns.

Loose coupling and tight cohesion

Playing with constructors

Child.java

public class Child extends Parent {
	static String staticNameVar = "NoNameYet";
	int ageInstanceVar = 5;

	Child(String name, int age) {
		this(name);
		System.out.println("My name is " + name + " and I am " + age
				+ " years old");
		doingThis("playing");
	}

	Child(String name) {
		super(doingThis("Studying"));// only static methods can be called before
										// constructor completes
		System.out.println("My name is " + name);
	}

	public static String doingThis(String activity) {
		System.out.println("I am " + activity);
		return ("Had enough of " + activity);
	}

	public static void main(String[] args) {
		Child child = new Child("Amy", 19);
	}

}
class Parent {
	Parent(String msg) {
		System.out.println("I am your parent; my message is " + msg
				+ ". Is it?");
	}

	Parent() {
		System.out.println("I am your parent I have no message for you");
	}
};
/**
Output ->

I am Studying
I am your parent; my message is Had enough of Studying. Is it?
My name is Amy
My name is Amy and I am 19 years old
I am playing

*/

Questions, Questions, Questions

Q. Give a tabular definition of common Collection classes.

Q. How would you classify exceptions?

Q Can we call ordinary methods from a synchronized method?

It is good programming advice not to call methods from inside a synchronized method because you may lose track of methods being called and end up in a deadlock because of bad programming. Don’t call any methods within a synchronized block except the class Object methods (wait, notify,).

Q What are the types of validation in Struts?

Validations in Struts are server side.
1. Server side using validation.xml without using javascript and
2. Validation using ValidatorForm with validate() method
In both cases the Form Bean needs to extend ValidatorForm. What you write in validation.xml is invoked by super.validate().
Struts framework reads validation.xml and puts some request attributes as error messages which gets passed on to the tag class behind

<action:errors../>

, which then creates html and sends it to the client.
If you are overriding the validate() method and plan to use both validation.xml as well as handcode the validate() method then you need to use super.validate().
validation.xml will still work if you don’t override the validate() method in your Form Bean extending ValidatorForm because it will inherit super’s validate() method.

Q How would you compare statement, prepared statement and callable statement in SQL?

Callable statement is a different animal, comparing it to queries is like apples and oranges.
Prepared statement is the faster of the two- statement and prepared statement. You write a query “select * from blah where foo=’a’” and next time it is “select * from blah where foo=’b’”, there is a slight change in passed parameter, but the database doesn’t know the difference. It will parse the second query without any memory of the first.
If you use the prepared statement with “?” as placeholder, then the database knows that the query does NOT need to be reparsed. It is cached internally, only the parameter value is changed.

Q Compare SAX and DOM parsers.

A DOM parser processes XML data and creates a tree representation of the document that you can navigate at run-time. The tree representation occupies memory and can be a major resource overhead.
The SAX parser on the other hand raises events that you can handle as you see fit.
Because of this design, the SAX implementation is generally faster and requires fewer resources. On the other hand, SAX code is frequently complex. A SAX parser is suitable for sequential and infrequent access while a DOM parser is more useful for frequent and random access.

Q Name some xsl:fo tags.

A snippet demonstrating use of some xsl:fo tags follows:

<xsl:stylesheet version="1.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
	<xsl:template>
		<fo:block>
			<fo:table>
				<fo:table-body>
					<fo:table-row>
						<fo:table-cell>
							<xsl:apply-templates select="category" />
						</fo:table-cell>
					</fo:table-row>
				</fo:table-body>
			</fo:table>
		</fo:block>
	</xsl:template>

	<xsl:template match="category">
		<fo:block>
			<xsl:value-of select="." />
		</fo:block>
	</xsl:template>
</xsl:stylesheet>

XML:

<category>
An asset to our company
</category>

Q Name some xsl tags.

A snippet demonstrating use of xsl tags follows:

Xsl:

<xsl:for-each select="ENTRY">
	<xsl:for-each select="ENGLISH">
		<td width="25%">
			<xsl:if test="string(.)!='null'">
				<i>
					<xsl:value-of select="." />
				</i>
			</xsl:if>
		</td>
	</xsl:for-each>
</xsl:for-each>

Xml:

<entry>
	<english>20</english>
	<german>A+</german>
</entry>
<entry>
	<english>10</english>
	<german>C++</german>
</entry>
<entry>
	<english>10</english>
	<german>A</german>
</entry>

Q Name some JSF tags:

A snippet demonstrating JSF tags follows:

<f:view>
	<h:form>
		<h:panelGrid id="grid1" columns="2" border="0" width="100%">
			<h:outputText id="text1" style="color: #000099;" value="Enter ISBN Code :" />
			<h:inputText value="#{authorBean.isbnCode}" />
		</h:panelGrid>
	</h:form>
</f:view>

A similar snippet using ADF faces would look like this:

<ui:define name="body">
	<div id="MyForm" class="HeaderBlock">
		<h:panelGrid columns="2">
			<af:outputLabel for="userName" value="Enter UserName " />
			<af:inputText id=" userName " columns="30"
				value="#{MyBean.userName}" maximumLength="40" />
		</h:panelGrid>
	</div>
</ui:define>

Q What are the implicit variables in JSP, and what are their servlet equivalents?

Implicit vars in JSP       Scope           Servlet-Equivalent

pageContext
application      application       ServletContext
request          request           HttpServletRequest
session          session           HttpSession
response                         HttpServletResponse
out                              PrintWriter
config                           ServletConfig
exception                        Throwable
page                             Object

Q Name some Ant tags.

<target name="war" depends="compile">
	<war warfile="${war}" webxml="${conf.dir}/web.xml">
		<classes dir="${build.classes.dir}">
			<include name="**/**" />
		</classes><!--All files included in this fileset will end up in the WEB-INF/classes
			directory of the war file -->
		<fileset dir="${css.dir}">
			<include name="**/**" />
		</fileset><!--places files from css dir(build) into root of the war -->
		<webinf dir="${conf.dir}">
			<include name="**/**" />
		</webinf><!--places files from conf dir(build) into WEB-INF of war -->
		<zipfileset dir="${images.dir}" prefix="images" />
		<!--places folder of images dir(build and places it in folder called "images"
			in root of war) > <lib dir="${jsf.lib.dir}"/><!--places files from lib(build
			into WEB-INF/lib folder of war) -->
	</war>
</target>

Q what are inner and outer joins in SQL?

Inner joins will return all rows from multiple tables where the join condition(in the “where” clause) is met.
An outer join returns all rows from one table and only those rows from a secondary table where the joined fields are equal (join condition is met).

Q. Name some Struts tags:

Some Struts tags:

Struts html tags: <html:text../> <html:form../> <html:errors/> <html:submit../> <html:reset../>
Struts bean tags: <bean:write.../> <bean:message.../>
Struts logic tags: <logic:iterate../> <logic:empty.../>
Struts nested tags: <nested:write... /> <nested:iterate.../>
Struts tiles tags: <tiles:insert../> <tiles:put../>

What is connection pooling?

A connection pool is a cache of open connections that can be used and reused, thus cutting down on the overhead of creating and destroying database connections.

Q. Briefly describe Servlet and JSP life cycles.

Servlet Life Cycle

When the Servlet Container starts up, it looks for web.xml, which includes an entry for each of the servlet the application uses. The servlet creates an instance of the compiled class and loads it. Next the servlet is initialized with initialization parameters in the ServletConfig object. The servlet is initialized after init() method returns. (Lazy loading – The servlet container does not initialize the servlet as soon as it starts up but rather when it receives a specific request for that servlet for the first time).
After the servlet instance is initialized, it is ready to service client requests. When the servlet container no longer needs the servlet instance(such as when the container is shutting down, or it is running low on resources, or no request has arrived for that servlet for a long itme), the servlet instance again goes to the unloaded state and cannot service any requests. Once destroyed, the servlet instance is garbage collected.

JSP life cycle

For each client request, the jsp container checks if the JSP page is new or has already been converted to a class file. If so, page translation occurs where the jsp code is converted to a regular java file, after checking for translation time errors. This java file is then compiled into a class file after compile time errors are checked. Once an instance of the class file is loaded it follows the same life cycle pattern as a regular servlet except that the following methods are involved
jspInit() instead of init()
jspDestroy() instead of destroy()
The container calls _jspService(), which was created during translation time by the jsp container, for each request.

Abstract Classes and Interfaces – Similarities and Differences

An abstract class may or may not contain concrete functions and may or may not contain abstract functions.
An interface can contain only abstract methods.
You cannot create instances of interfaces or abstract classes.
All variables declared in an interface are presumed to be as public static final even if not explicitly declared as such. That is the value contained in variables in an interface cannot be altered.

What is the purpose of using abstract classes when you have interfaces?

A class can implement multiple interfaces while a class can extend only one concrete or abstract class. Thus interfaces allow a variation of multiple inheritance, though not exactly in the proper sense.

In an abstract class you put all the common functionality that you intend your subclasses to inherit (Inheritance of functionality).
An interface guarantees that all the classes that implement it, provide concrete implementations of its abstract methods, if not, that class itself is to be declared as abstract (Inheritance of type).

Note: An interface can extend another interface. An abstract class can extend another abstract class. An abstract class can implement interface(s). A concrete class can extend another class or implement interface(s).

Getting the Streams Right

classLoader.getResourceAsStream
You should use classloader only for reading INSIDE a file like reading text from inside a text file or properties from inside a properties file. It is useful only for reading from text files etc. The file should be on the classpath . Loading a class means making the class available in your code. Getting a resource as stream means giving access to some “resource” from the classpath. Resource here is any other file other than java-classes.

classLoader = this.getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream(“com/mattiz/test/resources/sql.properties”);

The above code is used to load a class such as a properties file or an xml file.
The input stream may be passed onto suitable constructors wherever permissible.
The getResourceAsStream is basic java. It reads resources from the classpath. There’s nothing servlet-ish about it. It would work the same with a standalone java application.

classloader.getResource()
If you do want the file literally as a file (not to read it), then use classloader.getResource(). This returns a URL, which would look like this

file:///c:/temp/file.txt

if it is on the classpath.
Pattern:

file:///{absolutepath}

Remove the leading file:/// and you have the path to the file.
This uses the same technique as getResourceAsStream but returns a URL instead of inputstream

For example here you use getResourceAsStream() to read from a file to load properties:

// the answer lies in not specifying the absolute/relative path of
//sql.properties.
// instead load the resource from the classpath using
//classloader.getResourceAsStream()
// this is how to go about it
// create a package inside the EJB project called
//com/mattiz/test/resources/sql.properties or some name like that
// and put the sql.properties file into it.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = this.getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream(“com/mattiz/test/resources/sql.properties”);
Properties sqlCache = new Properties();
sqlCache.load(is);

For simple read access you would do the following where stream is an input stream


BufferedReader br = new BufferedReader(new InputStreamReader(stream));
//printing out contents if text file
while((line = br.readLine()) != null)
{
//iterate through the contents
System.out.print(line);
}

The constructor of the transformer class which is used in xsl transformations takes an inputStream as a parameter directly. This input stream may be obtained from an xsl file using the getResourceAsStream() method.