Jul 30, 2008

inheritance in java

Inheritance in Java means extension and code reuse as in term of object orientation with some difference in implementation.

The class which provides the general functionality is known as superclass, base class or parent of its children and the class which inherits this class is known as subclass, derived class or child of base class.

An example of inheritance can be a vehicle and the car classes. While a car is a vehicle but a vehicle may or may not be car and may be a truck/bus. The Car class will inherit the vehicle class which can provide the basic properties of a vehicle which is sure to be present in the car like applyBrake, accelerate etc.
The Car class will add more properties specific to a car.

As a vehicle will always be concrete hence the Vehicle class should be abstract which means that a new instance of Vehicle class can’t be created using the new operator.

Coming back to inheritance, creation of Vehicle class makes it easy to code as there is no need to implement each method which a Vehicle is supposed to implement.

Note: Implementing an interface is never inheritance.

DOM parsing

Function to get document by DOM parser

public static synchronized Document load(String filename, String filePath)
throws Exception {
Document doc;

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();


String fullFilePath = filePath + filename;
File file = new File(fullFilePath);
FileInputStream fis = new FileInputStream(file);
InputSource is = new InputSource(fis);
doc = builder.parse(is);
fis.close();
is = null;
fis = null;
file = null;

return doc;
}


The document returned by this function can be used to extract more data by using the methods like getElementsByTagName.

NodeList nodeList = doc.getElementsByTagName("Item");

Even new nodes can be added to the document and attributes can be added/modified.

SAX Parsing

SAX parser can be created using either the xerces or J2SE API. Both have a class named SAXParser.

On calling the parse method of SAXParser, the document is parsed and some events are raised

parser.parse(new InputSource(reader));

The events are catched by a DefaultHandler or its subclass. The event methods are startElement, endElement, startDocument, endDocument

Jul 18, 2008

Why are thread related methods present in Object class?

The threading methods are defined in Object class because these methods are related to object locks and any object can act as a lock and hence these methods are defined in the Object class. These methods are wait(), notify() and notifyAll(). These methods are final and return nothing. All of them must be called from a synchronized block or method and the thread calling them should pocess the lock on the object.

While calling wait() method, the thread to release the lock on Object on which wait() method is called and on calling the notify()/notifyAll() makes the other capture the lock.

Jul 17, 2008

History of J2EE

Java has been versioned since its inception. It has upgraded to Java 5 which means Java 1.5 version compiler but it was the version 1.2 which changed the world in dramatic changes. The impact so huge that J2EE (viz JEE 1.2) was envisioned.

Jul 16, 2008

Abstract classes in Java

An abstract class is like a normal class with the difference that it contains at least one abstract method or it extends another abstract class.
Thus the two conditions under which a class is and must be declared as abstract are:
1) It extends another abstract class
2) It declares an abstract method.


The above implies that at some point the hierarchy of abstract classes, one class must have declares an abstract method. So let’s discuss an abstract method. An abstract method looks like:

abstract void foo();

The difference between this and a normal method is that the abstract methods don’t have method body. This means to compiler that the current class is not meaningful in the real world scenario and some other class which will be extending this class will provide complete definition of the abstract method. In a way, this enforces that all subclasses of an abstract classes have to define the method body for abstract method.

An abstract class definition looks like:

abstract class Myfoo {
abstract void foo();
}


or it can be

abstract class Myfoo {}

or

abstract class Myfoo {
abstract void foo();
void anotherfoo() {
System.out.println(“I am not a abstract method”);
}


The above example shows that an abstract class can have some implemented methods in addition to abstract methods.

Now what about the below code:

abstract class MyAnotherfoo extends Myfoo {
void wrongFoo {
System.out.println(“This is wrong”);
}
}

The compiler will be more than happy in the above case because of the marker abstract before the class. Had the class not been declared as abstract, the compiler would have flashed an error unless an implementation of the abstract method foo(); has not be given in the subclass.

As far as design is concerned, the abstract classes are provided so that some common guidelines can be provided to the subclasses. For e.g. a class named as Figure will have an abstract method as:

abstract void setColor();

which will make sure that Square, Rectangle and Triangle which extend the Figure class will have to provide a method body for the above method.

One more implication of abstract classes is that since abstract classes are meant to be extended, so they can’t be instantiated. However a reference can be declared and is declared quite often in well designed application. For e.g in the Figure class above, a reference to Figure class can hold objects of type Square, Rectangle and Triangle and hence provides more usability.

Please note that final and abstract are mutually exclusive.

The point to be taken home from the above discussion is that declare classes as abstract where generality is implicit and more concrete implementations for this generality follow.

Difference between String and StringBuffer

The String class is final and String objects are immutable which means that the value of String objects can’t be modified.
But there are situations where one needs to modify the underlying String text. To solve this problem, java has StringBuffer class whose objects are mutable and can be modified using the methods. This means that instead of returning a new object as in case of String class, the methods of StringBuffer class return the modified object.

Other thing to note about StringBuffer class is that the methods are synchronized. StringBuilder is another class whose objects are mutable but its methods are not synchronized.

For the SCJP exam, it is crucial to know that StrigBuffer class has constructor which can accept an object of type String but the reverse is not true.
Moreover, the String and StringBuffer objects are never equal to each other even if the underlying text is same for both.

Jul 15, 2008

Strings in Java

The String type is so widely used that Java treats its values as literals within double quotes. But internally, the Strings are stored as Objects. Since they are so widely used, there is a danger that a String written by somebody may be overwritten by others erroneously. To avoid such kind of situation, the String class has been made final which means that no class can extend String class so as to modify the operations which are meant to be standard for all users/programmers. Moreover, the String objects are immutable which means that the String class’s methods don’t modify the String object on which the method is invoked. Instead, they return a new String object after modification operation. Thus one invokes the trim() method on a String literal as

String a = “ String ”;
a.trim();
System.out.println(“,” + a “,”);

A new String object is return by the trim() method which is shown by the value printed by the 3rd line.

Thus we have learnt that
1) String class is final
2) String objects are immutable.


Another important concept associated with Strings is String literals and the literal pool. The JVM places all the String literals in a separate pool and uses String literals from this pool when referenced multiple times. This saves on creating the same object again. For e.g.

String a = “String”;
String b = “String”;

a == ?


The answer to above question is true because the both a and b point to the same String object present in the String literal pool and this is also known as flyweight design pattern.

Jul 14, 2008

Overloading rules in Java

Let's quickly define overloading in a basic way:
Overloading is using the same method name but different number/type/order parameters .



Case1:
A method named fix() is defined in a class as:
void fix() {
System.out.println("fix--no parameters");
}

This method can be overloaded, if a method with name fix() is defined in the same class but with different parameters as:
void fix(int t) {
System.out.println("fix--one parameters");
}

The compiler will not flash any error in the above case.
A method call as fix(2) will print [b]fix--one parameters[/b] on console
But a method call as fix() will print [b]fix--no parameters[/b] on console


Case2:
Consider the overloaded methods defined as:
void fix(int t) {
System.out.println("fix--one int parameters");
}

void fix(long t) {
System.out.println("fix--one long parameters");
}

Guess what will the call fix(2) do. Yes the int parameterized function will be called.

Case3:
Consider the methods in case2 redefined as:
int fix(long t) {
System.out.println("fix--one int parameters");
return 2;
}

void fix(long t) {
System.out.println("fix--one long parameters");
}

The above methods are not overloaded because return types don't matter. The compiler will flash an error in this case.


Case4:
Consider the methods in case2 redefined as:
void fix(long t) throws IOException{
System.out.println("fix--one int parameters");
return 2;
}


void fix(long t) throws SQLException{
System.out.println("fix--one long parameters");
}

The above methods are again not overloaded as exception declarations also don't matter while overloading.


Case5:
Consider the fix methods defined as in Case2 above
void fix(int t) {
System.out.println("fix--one int parameters");
return 2;
}

void fix(long t) {
System.out.println("fix--one long parameters");
}


and method call as
char ch=2;
s.fix(ch);

Here ch will be implicitly typecasted to match method. The casting will be done to a minimum wider types of those available in the method call. Thus in this case void fix(int t) will be called.

Case6:
void fix(int t,long u) {
System.out.println("fix--one int parameters");
return 2;
}


void fix(int t,float u) {
System.out.println("fix--one long parameters");
}

A method call fix(2,2) in this case will work but a method call fix(2,2.0) won't work because the second argument type double can't be typecasted to float or long. Thus it is the method calls that determine the ambiguity of the overloaded methods.


Now an interesting case. Suppose there is a class BinarySearch which has its constructor declared as
BinarySearch() { //some code } Notice that constructors don't have any return type.
Now declare a method as:

int BinarySearch() {//some code }


A method call for the instance bs of class BinarySearch as bs.BinarySearch() will not call the constructor.Its a call to the second method which is a normal method. Thus the constructor names with different return types are also allowed. But that is an exception for constructor names only and not for other normal methods as seen in Case3.

difference between comparable and comparator interface

The key difference between comparable and comparator interface is:

The comparable interface should be used when the current object is to be compared to objects of its type only.
The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn't know how to compare the objects and expects you to give it. In this case you can't give your class as the comparator. It has to be some other class which implements comparator interface and does the comparison.

The above is what we will learn from the following discussion about the two interfaces.


Lets start with the comparable interface:
The comparable interface is present in java.lang package. This means that you need not import this interface when you are implementing this interface.
This interface has only one method which has the signature as:

public int compareTo(Object o);


As the name suggests you want this object to be compared to someone else. In Java syntax, the code is:

CompareClass cmp1 = new CompareClass();
CompareClass cmp2 = new CompareClass();
cmp1.compareTo(cmp2);

The best definition of this interface will be the one given in Java API which is reproduced here:

This interface imposes a total ordering on the objects of each class that implements it

Its all upto the implementor to decide how and which kind of objects will he be comparing with the Object for which compareTo method has been invoked. Some facts related to comparable interface are as follows:

1) The compareTo() method should return -ve,zero or +ve integer depending upon whether this object is less than,equal to or greater than the specified object
2) The value returned by compareTo() should be consistent with the value returned by equals() method of the same class. if not so, the class should explicitly state that.
3) Any comparison with null should throw NullPointerException
4)If the object of the classes which implement this interface can be used as keys in the SortedMap or SortedSet.
5)Lists and Arrays that implemet this interface can be sorted using the Collections.sort(List/Array) method without specifying any external comparator.

Example: Lets take the example of String class. Here is a sample code which will clear the compareTo method for you:
public class Test
{
public static void main(String[] args)

{

String str1 = "bar";

String str2 = "barfoo";

int compareResult = str1.compareTo(str2);

if (compareResult < 0){ System.out.println(str1 + "is less than" + str2); }else if (result == 0){ System.out.println(str1 +"is equal to" + str2); }else{ System.out.println(str1 +"is greater than" + str2); } } }





In this example, we are comparing String objects with other String objects and the comparTo method resides within the String class itself.


Now lets see the comparator interface.
The Comparator interface is a part of util package and needs to explicitly imported.

The general contract that is true for comparable is also true for comparator interface which is restated here because of its importance.

The value returned by the compare method of the class implementing the comparator interface should also return the same value with equals() method. This is important because the SortedSet and SortedMap will behave strangely.

There are two methods specified in the comparator interface which have the signature as follows:

int compare(T o1, T o2);
boolean equals(Object obj);

The compare() method should return -ve,zero or +ve integer depending upon whether this object is less than,equal to or greater than the specified object

Example:
import java.util.*;

class Test{

private int prop1;

public void setProp1(int prop1){

this.prop1=prop1;

}

public int getProp1(){

return this.prop1;

}

}


class TestComparator implements Comparator{

public int compare(Object obj1, Object obj2){

int test1 = ( (Test) obj1).getProp1();

int test2 = ( (Test) obj2).getProp1();

if( test1 > test2 )

return 1;

else if( test1 < test2 ) return -1; else return 0; } }

So whats the distinguishing part between the comparable and comparator?
Well its the difference in terms of the method signature at code level.
But in terms of design level, there is a big difference and should not be overlooked.

The comparable interface should be used when the current object is to be compared to objects of its type only.
The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn't know how to compare the objects and expects you to give it. In this case you can't give your class as the comparator. It has to be some other class which implements comparator interface and does the comparison. A typical example of this is the Collections.sort(List l, Comparator c) method.

Below is the link to some more material on this topic

Comparable Interface API

Comparable Interface API



SCJP Sun Certified Programmer for Java 6 Exam 310-065

Jul 11, 2008

After SCJP what?

Well you are now SCJP after passing the so called SCJP exam and are now wondering what to do now?
The answer is analyze. Analyze what role you will be doing while you will be coding. Will you be working on client side and working with Servlets, JSP etc. or you will be working on the server side and working with EJB’s etc.

Well in both cases, there is something that can make your resume more appealing and that is the SCWCD exam. While SCJP shows that the person has knowledge of Java, SCWCD shows that the person has knowledge of Servlets, JSP. SCWCD stands for Sun Certified Web Component Developer and current version offered by Sun is SCWCD 1.5. There is pre-requisite before one can appear for the SCWCD exam and that is the person should be SCJP which means SCJP 1.1, SCJP 1.2, SCJP 1.4 or SCJP 1.6. Whatever version of SCJP have you passed, you can always appear for the SCWCD exam.

I asked you to analyze, what will you be doing after SCJP because there is life unaware of a client-server paradigm (may be Swing or the likes)

So all those guys who fall in first category go for SCWCD and decorate your resume with that logo of SCWCD.

checked and unchecked exceptions

The exceptions can be of two types viz checked and unchecked. Checked exceptions mean to compiler those exceptions from which the program can occur but that are not caused by programming bugs like File not available on hard disk, or Database is shutdown as program is trying to make some connection. The compiler knows these are areas where problem can occur which is not due to a problem with the code. Thus the compiler keeps a check on the statements which try to induldge in such activities.

e.g Try some code like:

public static void main(String[] args) {

FileWriter f = new FileWriter("E:\\new.txt");
}

The compiler complains that “unhandled exception of type IOException”

Now write something as:

public static void main(String[] args) {

FileWriter f = new FileWriter("E:\\new.txt");
f.write("a");
}

Again the compiler complains about, “unhandled exception of type IOException” on both lines.


Now try this one:

public static void main(String[] args) {

try {
FileWriter f = new FileWriter("E:\\new.txt");
f.write("a");
}
catch(IOException e) {

}
}

Now the compiler doesn’t stops complaining because it knows that if some problem occurs during writing a file, a proper action is being taken by the program as specified in the catch block.

Some other checked exceptions are:

SQLException, FileNotFoundException

In fact all subclasses of the class Exception which are not in the hierarchy of RunTimeException are checked exceptions.


Other thing to know about checked exceptions is that they need to be declared or catched.
This means that either catch the checked exception or declare that this function can throw a checked exception in which case the caller has the responsibility of catching it or declaring it. The catching logic has been shown above. Below is the way to declare a checked exception

public static void main(String[] args) throws IOException

FileWriter f = new FileWriter("E:\\new.txt");
f.write("a");

}

The above is our way of saying to compiler that I may throw a checked exception and I know that and I am declaring that so the caller should have the responsibility to handle the exception.

Unchecked exceptions are those exceptions which occur at runtime and which occur because of flaw in programming logic. Examples are, ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException

The compiler doesn’t complain about these exceptions and it is the sole responsibility of programmer to take care of them.
For example consider the following code:


public static void main(String[] args) throws IOException

System.out.println(args[1]);

}

and the invocation as
java ClassTest

No command line arguments have been supplied and thus when we try to access the second element in the args string array, an ArrayIndexOutOfBoundsException is thrown

This is unchecked exception because compiler doesn’t place a check that an exception is likely to occur.

That’s all, one has to know at the level of “what is difference between checked and unchecked exceptions”

Introduction to exceptions in java

There are some runtime operations which are invalid for the JVM. These runtime operations may have been fired by the program or they may occur by default. The former are known as exceptions and the latter as errors. Though there is nothing that can be done by the programmer in the event of an error but something can be done in case of exceptions.

A typical example of an exception is “Divide by zero”, “Accessing a null object” etc. and that of an error can be “Running out of memory so that no more objects can be allocated by memory”.

The bottom line is that error is something from which the program can not recover and is terminated but exceptions are something from which program can recover and both are some erroneous situations.

Unable to load default ProjectHelper due to java.lang.NoClassDefFoundError: org/xml/sax/SAXException

Unable to load default ProjectHelper due to java.lang.NoClassDefFoundError: org/xml/sax/SAXException

I have been getting this problem in Eclipse when I try to build my project using ANT. The problem occurs because of misconfiguration. To fix this issue, do this:

Go to Window>>Preferences>>Ant>>Runtime>>Classpath>>Ant Home Entries and add these 2 External JARs (Click to get them):

xercesImpl.jar
xmlParserAPIs.jar


Note: The name of above jar's may be different on your side.

Jul 10, 2008

SCJP mock exam links.

Mock exams for SCJP 6

JavaPrepare for
SCJP 6


Mock exams for SCJP5

Exmulator for SCJP 5(Get daily a question on Java, book mark this website)


Devaka's ExamLab for SCJP 5

Java Beat mock exams (SCJP 5)

Mock exams for all SCJP versions (consists of topics from SCJP 1.4 but doesn’t cover the topics like Generics, Autoboxing etc.)

Exams Guide SCJP mock exam (for all versions of SCJP)

Sahir Shah mock tests applet (for all versions of SCJP)

Valoxo (for all versions of SCJP)

Danchisholm (for all versions of SCJP)

JCHQ mock exam 1

JCHQ mock exam 2

JCHQ mock exam 3

Angelfire (for all versions of SCJP)

lanw (for all versions of SCJP)

JavaCertificate (for all versions of SCJP)

skmajji mock exams (for all versions of SCJP)

Javaranch online mock exams (for all versions of SCJP)

Coffee with java (for all versions of SCJP)

Testsworld (general java test)

Links for SCJP 1.4 study notes

http://www.jchq.net/tutorial/04_01Tut.htm
http://www.javadeveloper.co.in/scjp/scjp-notes.html
http://www.michael-thomas.com/tech/java/index.html
http://www.freejavaguide.com
http://java.boot.by/scjp-tiger/
http://www.javacertificationexams.com/scjp-study-guides.php
http://www.javacertificationexams.com/scjp-community.php

Jul 7, 2008

SCJP 1.5 I/O

The exam says you need to know the writer classes, Serialization and design pattern being used in implementing I/O package.

The writer class heirarchy starts from Writer class which is an abstract class. The next usable class is FileWriter which extends from Writer class and can be used to write to files. It has constructor which accepts the File name as String or can accept File Object. The FileWriter class has limited use as it doesn't have any buffer.

Similar heirarchy exists in Reader classes with Reader class being the abstract class and FileReader corresponds to FileWriter of Writer heirarchy.

Besides this, one also needs to know the design pattern

Jul 4, 2008

SCJP 1.4 Study Notes- Part-2

0)
Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides

If static is specified in either superclass or subclass for a method the both the other class should also make it static.
1) No variable can be native, abstract or synchronized. Member variables can be transient, final, static, volatile. Local variables can be final only.
2) For same class names, use the fully qualified name. If not done so, the first path in the classpath will be used.
3) const and goto are keywords but are not in use.
4) Memorize all keywords, null, true and false are not keywords.
5) Local objects and primitive variables must be initialized before first use, not necessarily on the first line.
6) Initialized individual elements of an array may be used with some other elements remaining uninitialized.
7) “John” + b is not a String literal.
8) There can be a maximum of 21 digits in a octal number not including the leading 0 and a maximum of 16 digits in a hexadecimal number not including the leading 0x.
9) An array of superclass can accommodate objects of subclass by auto typecasting. But the reverse is not true. Even if explicit cast is done, java.lang.ClassCastException will be thrown at runtime.
10) Interfaces can’t have variables with modifier other than public static and final.
11) An interface can’t implement another interface
12) An interface can’t extend any class
13) An interface can only extend other interfaces. (super interfaces)
14) An abstract class can implement an interface.
15) An abstract class can extend other classes.
16) An abstract class can have final methods.
17) static final variable can be a member variable and needs special treatment than that without static keyword. Since it is static, the initialization in constructor may not work. It will work if the variable has been initialized before the class was loaded. This initialization can be in a static block or when declaring the variable. Once done that it becomes definitely assigned and hence can’t be reassigned. Moreover a final global variable must be assigned while a final local variable may not be.
18) If not initialized while declaring a non-static final variable is expected to be initialized in all the constructors.
19) But if there is an infinite loop in a constructor, then the initialization of definitely unassigned non-static final variable can be avoided.
20) For an infinite loop, the definitely unassigned non-static final variable will be unassigned for first iteration and will be assigned for every iteration afterwards. Hence compiler flashes error in both cases.
21) But since an if(true) is iterated only once, the initialization can’t be avoided as far as constructor is concerned. Predict the case for if(false). Yes, the compiler flashes error.
22) If definitely unassigned non-static final variable is assigned in both if(cond) and corresponding else then compiler comes to know that the variable will be initialized in any case and hence no error.
23) For final primitives, the value may not be altered once it is initialized. For objects, the data within the object may be modified but the reference variable may not be changed.
24) Hashtable and Hashmap are different in the sense that Hashmap is unsynchronized and permits nulls as keys as well as values.
a. In case the iteration performance is important, keep the capacity/size small because the time for iteration is proportional to capacity + size. However get() and put() have constant time performance.
b. The load factor and initial capacity effect the performance of hashmap. When the number of entries in the hashmap exceed the product of load factor and current capacity, the hashmap is rehashed so as to have twice the number of buckets. A value of 0.75 is for load factor is good tradeoff between time and space cost.
c. The expected number of entries should be taken into account when setting the initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the number of entries divided by the load factor, no rehash will ever occur.
d. The parameterized constructors allow for setting the initial capacity and/or load factor.
e. The hashmap is unsynchronized for structural changes. Collections.synchronizedMap should be used for synchronized access.
f. The iterator returned by hashmap is fail-fast which means that if the map is modified by any means other than the iterator’s modification methods, the iterator throws ConcurrentModificationException. However, the fail fast behaviour is not guaranteed.
g. The put() method returns null if there is no mapping for the key or null was stored as the value for that key otherwise it returns the previous value of the key. Similar is the case with get(). The containsKey() method may be used to distinguish between the cases when there is no key with specified name and when null is stored as value for the key.
h. The implementation class which wants to leave out some operation, simply throws UnsupportedOperationException in that method.

25) switch expects an argument of type int. But due to auto casting short, byte, char also work.
26) strictfp used in front of method or class indicates that floating-point numbers will follow FP-strict rules in all expressions.
27) Even the order of arguments matters when overriding a method.
28) Object reference and local variables are stored on stack. IS a relationship is inheritance and HAS a relationship is composition (One class has an object of other as its member)

SCJP 1.4 Study Notes- Part-1

1) Return type and method name always go together
2) Native method declarations have no body
3) A top-level class can be public, abstract/final, strictfp.
4) A top-level interface can be public, abstract, strictfp. abstract is implied by default.
5) Inner classes can be only public, protected, private, static, abstract/final.
6) Inner interfaces can be only public, protected, private, static, abstract.
7) Only one class/interface can be public in a source file and if it is so, the name of the source file should be the name of the public class/interface.
8) The default access is also available for the class members.
9) For searching a pattern use, the pattern and matcher. E.g
String str=”bcbcbcbabcbbcbcbababbaba”;
String regex=”bc”;
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(str);
while(matcher.find()) {
System.out.println(matcher.start);
}
10) Program to count the number of times a character appears in a string:
Map hmap2 = new HashMap();
for(int counter1 =0 ; counter1 if (hmap2.containsKey(String.valueOf(str.charAt(counter1)))) {
count = (Integer)hmap2.get(String.valueOf(str.charAt(counter1)));
count++;
} else {
count = 1;
}
hmap2.put(String.valueOf(str.charAt(counter1)),new Integer(count));
}

Iterator it = hmap2.keySet().iterator();
while(it.hasNext()) {
key = (String)it.next();
System.out.println(key+ " " + hmap2.get(key));

}
11) Code to create database connection, execute statement and process results is:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Database","a","b");
Statement stmt = con.createStatement();
ResultSet set = stmt.executeQuery("Select * from abc");
while(set.next()) {

}
12) The String class is a final class.
13) Final classes improve performance as the methods are expanded inline.
14) All the methods of final class are also final as the class can’t be subclassed and hence the methods can’t be overridden.
15) volatile and transient can only be applied to member variables.
16) volatile and final can’t go together.
17) transient makes member variables non-persist able while serializing the object.
18) volatile variables maintain a master copy in addition to the local copy of each thread and each thread has to keep its local copy in sync with the global copy. These variables are useful to avoid concurrency problem when synchronization is not an option. They are slower.
19) To avoid having different people using the same package name, Sun recommends using the reverse of the internet domain as package name. e.g com.sun.java
20) abstract and final are mutually exclusive
21) All java classes must extend a superclass.
22) Though classes can be built without inheritance and interfaces, but that design will be poor.
23) All variables in an interface are public static final by default and all methods are public abstract by default. public because compiler knows that interface by itself is abstract and somebody needs to implement it, so even if public is omitted the methods and variables are public by default.
24) Method access modifiers: public, private, protected or none (default)
Method special modifiers: abstract, final, static, synchronized, native
When abstract is used for a method then final, synchronized, strictfp, static and native can’t be used.
25) Constructor facts:
a. The return type is implicitly this, but this value can’t be collected using assignment operator
b. Constructor can’t be inherited as other superclass methods
c. The constructor can’t be final, abstract, synchronized, native, static (special modifiers)
26) If only one constructor is supplied and is made private, no class can instance that class.
27) As main method is declared static, it can’t use non-static variables declared in the same class.
28) Only a constructor can invoke another constructor and that call must be the first statement of the calling constructor. (this() or super())
29) super() is usually used to call parameterized superclass’ constructor. If there is no call to superclass constructor and there is no no-argument constructor then compiler flashes error because compiler automatically inserts a call to no-argument constructor.
30) Constructor chaining is the calling of superclass constructor all through the hierarchy.

How to code in XSL

Here's a document to upgrade your XSLT skills. Its a kind of study notes for XSL.
http://javacentre.f-sw.com/tutorials/xslt/xslt.doc

How to design MVC architeture

The purpose of MVC is to free the view of any details about who and how handles the business process. The view simply needs to indicate what was the action performed by the user and then business process should be performed based on that indication. For the smooth flow between view and business process, there has to be some intermediary which is known as controller. All pages will submit to the same controller and the controller based on what is return from the view, calls the corresponding dispatcher. The dispatcher on completing its process forwards to appropriate view. The view mappings may be stored somewhere or may be hardcoded withing the dispatcher.

One way the view can send the event fired by user to the controller is by the use of JSP which will add a parameter into the request object. But this will unnecessarily complicate the things. Another approach is to use some hidden field which will automaticall included in the request and whose value can be set using javascript depending upon the event fired by the user.

Here is some code to demonstrate this.



Now the FrontController will do something like this


Jul 3, 2008

XSLT Process

Here is the process to generate the output (txt,pdf,scg,csv etc.) using xml, xsl and xslt processor.

1) Get the XML containing the data.
2) Decide on the layout of output.
3) Write the XSL file
4) Run the XSLT processor to generate the output document.

SCJP 1.5 or 1.4

I was in the dilema that should I go for SCJP 1.4 or scjp 1.5 certification. But now I have decided that I will go for scjp 1.5 because that much improved and will give much better appeal to CV than 1.4 version.

Moreover, as it stands out that SUN Microsystems may withdraw 1.4 version certification by the time I appear for the exam.
1.5 is going to stay and thats for sure.

A random thought that SCWCD exam is 1.5 now and not 1.4. So SCJP 1.5 and SCWCD 1.5 make better combination than SCJP 1.4 and SCWCD 1.5