Вы находитесь на странице: 1из 104

EXPLORING INTERVIEW ORIENTATION 1 JVM concepts........................................................................................................................1 2 OOPS concepts......................................................................................................................5 3 Exceptions.............................................................................................................................7 4 Object..................................................................................................................................12 5 String manipulation.............................................................................................................13 6 UTIL package:.....................................................................................................................22 7 Wrapper Classes:.................................................................................................................

30 8 I/O package..........................................................................................................................31 9 Serialization:........................................................................................................................38 10 Threads..............................................................................................................................47 11 Reflection..........................................................................................................................60 12 JDK 1.5 Features:..............................................................................................................60 13 JDBC :...............................................................................................................................65 14 Java Script.........................................................................................................................75 15 Servlets :............................................................................................................................75 16 Web.xml............................................................................................................................85 17 JSP.....................................................................................................................................85 18 Struts..................................................................................................................................87 19 EJB....................................................................................................................................88 20 JMS....................................................................................................................................92 21 XML..................................................................................................................................93 22 WebServices......................................................................................................................95 23 Design Patterns..................................................................................................................95 24 ANT.................................................................................................................................100 25 UML................................................................................................................................100 26 Log4J...............................................................................................................................101 27 Eclipse/NetBeans............................................................................................................101 28 Weblogic/Websphere/Jboss/Tomcat...............................................................................101 29 VSS/CVS.........................................................................................................................101 30 Spring..............................................................................................................................101 31 Hibernate.........................................................................................................................101 32 Java Performance tuning.................................................................................................101 33 SQL.................................................................................................................................103

1 JVM concepts
What are the Different types of Class Loading? Static class loading: Classes are statically loaded with Javas new operator. class MyClass { public static void main(String args[]) { Car c = new Car(); } }

A NoClassDefFoundException is thrown if a class is referenced with Javas new operator (i.e. static loading) but the runtime system cannot find the referenced class. Dynamic class loading: Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically. Class.forName (String className); //static method which returns a Class The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime instance of the loaded class. Its just like creating a class object with no arguments. class.newInstance (); //A non-static method, which creates an instance of a class (i.e. creates an object). Jeep myJeep = null ; //myClassName should be read from a properties file or Constants interface. //stay away from hard coding values in your program. CO String myClassName = "au.com.Jeep" ; Class vehicleClass = Class.forName(myClassName) ; myJeep = (Jeep) vehicleClass.newInstance(); myJeep.setFuelCapacity(50); A ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found: The forName(..) method in class - Class. The findSystemClass(..) method in class - ClassLoader. The loadClass(..) method in class - ClassLoader. What are static initializers or static blocks with no function names? When a class is loaded, all blocks that are declared static and dont have function name (i.e. static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initialize static fields. CO public class StaticInitilaizer { public static final int A = 5; public static final int B; //Static initializer block, which is executed only once when the class is loaded. static { if(A == 5) B = 10; else B = 5; }

public StaticInitilaizer(){} // constructor is called only after static initializer block } The following code gives an Output of A=5, B=10. public class Test { System.out.println("A =" + StaticInitilaizer.A + ", B =" + StaticInitilaizer.B); } What is the difference between an instance variable and a static variable? Give an example where you might use a static variable? Static variable: Class variables are called static variables. There is only one occurrence of a class variable per JVM per class loader. When a class is loaded the class variables (aka static variables) are initialised. Instance variable: Instance variables are non-static and there is one occurrence of an instance variable in each class instance (i.e. each object). Give an example where you might use a static method? Static methods prove useful for creating utility classes, singleton classes and factory methods. Utility classes are not meant to be instantiated. Improper coding of utility classes can lead to procedural coding. java.lang.Math, java.util.Collections etc are examples of utility classes in Java. What is a final modifier? Explain other Java modifiers?

Modifier static

abstract

synchronized

Class A static inner class is just an inner class associated with the class, rather than with an instance. Cannot be instantiated, must be a superclass, used whenever one or more methods are abstract. N/A

Method cannot be instantiated, are called by classname.method, can only access static variables

Property Only one instance of the variable exists.

Method is defined but contains no implementation code (implementation code is included in the subclass). If a method is abstract then the entire class must be abstract. Acquires alock on the class for static methods. Acquires a lock on the instance for non-static methods.

N/A

N/A

transient

N/A

N/A

final

Class cannot be inherited N/A

Method cannot be overridden

native

Platform dependent. No body, only signature.

Field should not be serialized. Makes the variable a constant. N/A

What is the difference between final, finally and finalize() in Java? final - constant declaration. Refer Q27 in Java section. finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc. (Refer Q45 in Enterprise section) finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these nonmemory resources through the finalize() method. How does Java allocate stack and heap memory? Explain re-entrant, recursive and idempotent methods/functions? Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed. In a multithreaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code. A method in stack is re-entrant allowing multiple concurrent invocations that do not interfere with each other. A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods,

which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server. What do you know about the Java garbage collector? When does the garbage collection occur? Explain different types of references in Java? Each time an object is created in Java, it goes into the area of memory known as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garbage collector runs in low memory situations. When it runs, it releases the memory allocated by an unreachable object. The garbage collector runs on a low priority daemon (background) thread. You can nicely ask the garbage collector to collect garbage by calling System.gc() but you cant force it. Explain types of references in Java? java.lang.ref package can be used to declare soft, weak and phantom references. Garbage Collector wont remove a strong reference. A soft reference will only get removed if memory is low. So it is useful for implementing caches while avoiding memory leaks. A weak reference will get removed on the next garbage collection cycle. Can be used for implementing canonical maps. The java.util.WeakHashMap implements a HashMap with keys held by weak references. A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want to be notified that an object is about to be collected.

2 OOPS concepts
a) Abstraction: it is the selective examination of certain aspects of a problem.
The goal of abstraction is to isolate those aspects that are important for some purpose and suppress those aspects that are unimportant. Abstraction is generally defined as 'the process of formulating generalized concepts by extracting common qualities from specific examples. What is the diffrence between an Abstract class and Interface ? when to use what ?

b) Encapsulation: It is a simple, yet reasonable effective, system-building tool. It


allows suppliers to present cleanly specified interfaces around the services they provide. A consumer has full visibility to the procedures offered by an object, and no visibility to its data. From a consumer's point of view, and object is a seamless capsule that offers a number of services, with no

visibility as to how these services are implemented ... The technical term for this is encapsulation. Encapsulation (also information hiding) consists of separating the external aspects of an object which are accessible to other objects, from the internal implementation details of the object, which are hidden from other objects c) Polymorphism: definition comes here What is overloading and overriding? Diff btwn overloading and overriding? Java api examples for overloading? Wait () method in Object class Real time examples for overriding? - Tostring(),equals (),hashcode() In method overriding, return type should be same or Could be different? Should be same Tell me the real time scenario for runtime polymorphism? Example: A a = new B(); a.method(); Can u override a static method? Then what is the output for above example? ClassA a = new ClassA (); ClassB b = new ClassB (); ClassC c = new ClassC (); ClassA ab = new ClassB (); ClassA ac = new ClassC(); ab = ac; ab.method(); What is the output of following code? Will it compile? a =(ClassA)b; a.method (); ClassBs method will be invoked. What is the output of following code? Will it compile? b =(ClassB) a; b.method(); ClassCastException best real time example for RunTimeException. Public method () throws Exception Access modifiers ---- cannot be more private in the subclass Throws clause ----- should be same or subclass of exception thrown in the super class for the overriding method. d) Inheritance def comes here. Why java does not support multiple inheritances directly? http://www.javaworld.com /javaqa/2002-07/02-qa-0719-multinheritance.html

In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritances from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache. java support pass by value or pass by reference?

http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

3 Exceptions
What is the diff betwn Error and Exception? Error in the terms the errors that can't be handled by the jvm, which leads to the termination of the program. Thats why you are not able catch the error in your program. Exception in the terms the errors that it can be handled by the jvm by using try catch block. What is checked exception and unchecked exception? A checked exception is a subclass of Throwable but not of RunTimeException. Such exceptions generally indicate an extra-logical failure (one not related to programming errors; e.g. EndOfFileException).). They are required either to be caught, or appear in a method that specifies in its prototype that it throws that kind of exception. Contrast to Unchecked Exception. Throwble

Exception

Error

Runtime Exception All subclasses of Runtime Exception and Error are called unchecked Exception. Checked Exceptions are checked at compile time, where as unchecked exceptions are at runtime. Please explain the difference between checked exceptions and runtime exceptions? When would I throw them, and when would I catch them?

http://www.javaworld.com/javaworld/javaqa/2002-02/01-qa-0208-exceptional.html
Java provides two main exception types: runtime exceptions and checked exceptions. All checked exceptions extend from java.lang.Exception, while runtime exceptions extend from either java.lang.RuntimeException or java.lang.Error.

Two aspects differentiate checked exceptions from runtime exceptions: mechanical and logical. The mechanics From a mechanical viewpoint, runtime exceptions and checked exceptions differ in how you declare the method that throws the exception, and how you handle the exception when it's thrown. Consider the following checked exception definition:

Public class Checked Exception extends Exception { public Checked Exception () {} public Checked Exception (String message) {super (message); } } The following class has a number of methods that throw exceptions:

Public class ExceptionalClass { public void method1 () throws Checked Exception { // ... some code throw new Checked Exception( "something bad happened" ); } public void method2( String arg ) { if( arg == null ) { throw new NullPointerException( "arg passed to method2 is null" ); } } public void method3() throws Checked Exception { method1(); } } Right away you'll notice that both method1 () and method2 () throw exceptions, but only method1 () has an exception declaration. You'll also notice that method3 () doesn't throw an exception itself, but its signature indicates that it may throw a Checked Exception. Before I tell you why, consider the following main method:

Public static void main (String [] args) { ExceptionalClass example = new ExceptionalClass (); try { example.method1 (); example.method3 (); } catch (CheckedException ex) {

} example.method2( null ); } When a call is made to method1 (), you must make the call from within a try/catch block. In this case, it's a checked exception because you must catch it. Checked exceptions are always declared as thrown in the method signature. The signature lets the method's caller know that an exception may occur as a consequence of the call. If the exception does get thrown, the caller must be prepared to do something about it. Contrast method1 () with method2 (). When you make a call to method2 (), you don't have to do so within a try/catch block. Since you do not have to catch the exception, the exception is said to be unchecked; it is a runtime exception. A method that throws a runtime exception need not declare the exception in its signature. Now, look back at method3 (). It makes a call to method1 () without making the call in a try/catch block. Method3 () avoids not catching the exception by declaring that it may also throw the exception thrown by method1 (). Instead of catching the exception, method3 () simply passes the exception along. Analogously, you could have dispensed with the try/catch block in the main method by declaring that it throws CheckedException. (I only mention this to give you a second reference point; you should never declare a main as throwing an exception.) Here's a summary of the mechanical aspects of exceptions: Runtime exceptions: o A method signature does not need to declare runtime exceptions o A caller to a method that throws a runtime exception is not forced to catch the runtime exception o Runtime exceptions extend from Runtime Exception or Error Checked exceptions: o A method must declare each checked exception it throws o A caller to a method that throws a checked exception must either catch the exception or throw the exception itself o Checked exceptions extend from Exception

The logic From a logical viewpoint, checked exceptions and runtime exceptions serve two separate purposes. Checked exceptions indicate an exceptional condition from which a caller can conceivably recover. Conversely, runtime exceptions indicate a programmatic error from which a caller cannot normally recover. Checked exceptions force you to catch the exception and to do something about it. Take a look at the constructors for java.net.URL. Each constructor may throw a MalformedURLException, an example of a checked exception. Imagine that you've written a simple program that prompts the user for a URL. Using that URL, the program retrieves a page. If something is wrong with the URL the user enters, the constructor will throw an exception. Since the URL constructor throws a

checked exception, the program must catch the exception and try to recover. In the case of the bad URL, the program could ask the user to retype it. Now, consider the following method: Public void method () { int [] numbers = {1, 2, 3 }; int sum = numbers[0] + numbers[3]; } Executing method () will always yield an ArrayIndexOutOfBoundsException since we are trying to read past the end of the array. Remember, an array index i must be: 0 <= i <= (array. length - 1) The method caller has no recourse because the caller cannot do anything meaningful in response to the error. This method, as well as method2 (), represents a runtime exception example. As I mentioned above, runtime exceptions indicate programmatic errors. Programmatic errors are normally unrecoverable bugs, so the proper recovery is to fix the error in the code. As a rule of thumb, you should always catch a checked exception once you reach a point where your code can make a meaningful attempt at recovery. However, it is best not to catch runtime exceptions. Instead, you should allow runtime exceptions to bubble up to where you can see them. If you do catch runtime exceptions, you risk inadvertently hiding an exception you would have otherwise detected and fixed. As a result, catching runtime exceptions complicates unit and regression testing. While testing, seeing a stack trace or allowing the test to catch and report runtime exceptions lets you quickly identify problems. Some programmers advocate catching and logging runtime exceptions, but I disagree because that makes you read through logs while you unit test your code. A unit test should indicate whether the test passed or failed without manual verification from a log. Let the unit test catch the exception, not the code being tested. Catching runtime exceptions also leads to a worse problem: what exceptions do you catch, and when do you catch them? Runtime exceptions are undeclared, so how do you know what you should catch? How do you know there's an exception to catch? Certainly you wouldn't place try/catch blocks around every method call and array access you perform? Try {

} Catch(first catch block) { } Catch (second catch block)) { } Finally {

} We can have multiple catch blocks. The order of the catch blocks from the top to bottom is subclass to superclass.i.e more specific exception should come in the first catch block. The code in the finally block would be always executed, if exception comes or not. Tell me the Real time examples of Runtime Exceptions? 1.NullpointerException In the Hashtable, if u put null will get NullpointerException. If u call any method on the any object which is null For Example call toString method on null object. 2.ClassCastException. Iterate through array list and get one value object from it and cast it to another value object, u will get ClassCastException 3.NumberFormatException: if u are trying to parse a string which is not a valid number,u will get this NumberFormatException int intVar = Integer.parseInt("ad");//example code what is the diff between throws and throw clause? Throws clause would be used in the method signature where as throw can be used in the method body. Throw MyOwnException(); Good article on Exception Handling.

http://www.congreve.com/articles/exception-handling/
How to write your ownException? It should extend Exception. Is there a way to get the original exception object from inside a nested or wrapped Exception (for example an EJBException or RemoteException)? Absolutely yes, but the way to do that depends on the Exception, since there are no standards for that. Some examples: When you have an javax.ejb.EJBException, you can use the getCausedByException() that returns a java.lang.Exception. A java.rmi.RemoteException there is a public field called detail of type java.lang.Throwable With a java.sql.SQLException you need to use the method getNextException() to get the chained java.sql.SQLException.

When you have an java.lang.reflect.InvocationtargetException, you can get the thrown target java.lang.Throwable using the getTargetException() method.

As usual, the best way to check how to get that piece of information is to read the documentation of the specific Exception. How to print the trace in a string: Exception ex = new Exception("something went wrong"); StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); String stack trace = sw.toString (); System.out.println ("stack trace = " + stack trace); An OutOfMemoryError can be thrown due to one of the following 4 reasons ? JVM may have a memory leak due to a bug in its internal heap management implementation. But this is highly unlikely because JVMs are well tested for this. The application may not have enough heap memory allocated for its running. You can allocate more JVM heap size (with Xmx parameter to the JVM) or decrease the amount of memory your application takes to overcome this. To increase the heap space: Java -Xms1024M -Xmx1024M Care should be taken not to make the Xmx value too large because it can slow down your application. The secret is to make the maximum heap size value the right size. Another not so prevalent cause is the running out of a memory area called the perm which sits next to the heap. All the binary code of currently running classes is archived in the perm area. The perm area is important if your application or any of the third party jar files you use dynamically generate classes. For example: perm space is consumed when XSLT templates are dynamically compiled into classes, J2EE application servers, JasperReports, JAXB etc use Java reflection to dynamically generate classes and/or large amount of classes in your application. To increase perm space: Java -XX:PermSize=256M -XX:MaxPermSize=256M The fourth and the most common reason is that you may have a memory leak in your application as discussed in Q64 in Java section.

4 Object
What is the main difference between shallow cloning and deep cloning of objects?

The default behaviour of an objects clone() method automatically yields a shallow copy. So to achieve a deep copy the classes must be edited or adjusted. Shallow copy: If a shallow copy is performed on obj-1 as shown in fig-2 then it is copied but its contained objects are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable interface. Deep copy: If a deep copy is performed on obj-1 as shown in fig-3 then not only obj1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead. For example, invoking clone() method on a HashMap returns a shallow copy of HashMap instance, which means the keys and values themselves are not cloned. If you want a deep copy then a simple method is to serialize the HashMap to a ByteArrayOutputSream and then deserialize it. This creates a deep copy but does require that all keys and values in the HashMap are Serializable. Its primary advantage is that it will deep copy any arbitrary object graph List some of the methods supported by Java object class? clone(), toString(), equals(Object obj), hashCode() wait(), notify(),notifyall() and finalize() etc.

5 String manipulation
Describe the significance of the immutability of String objects. Once you instantiate a String Object with a set of characters, you can't change its size or replace its characters, in effect the String becomes a constant. Strings are immutable.

What are mutable and immutable objects in Java? As per the dictionary, mutable objects are objects which can change their values and immutable objects are objects which cannot have their values changed. The basic way to create an immutable object is to make all of its data fields private and don't create any methods which can change any of the data fields once the object has been constructed. If you need to make an object immutable for which you don't control of the source code for its class, you can create a wrapper/adapter class which uses an instance of the existing, mutable class to do all of the work (via e.g., delegation) but doesn't provide any methods which can effect any change to the mutable object.

How do I create my own pair of mutable and immutable classes similar to String and StringBuffer? http://www.javaworld.com/javaworld/javaqa/2002-12/01-qa-1206-immutable.html? What is immutable class in java? The contents of the immutable class cannot be changed. What is the diff betwn String and StringBuffer? String is immutable and StringBuffer is mutable. If u uses String.concat () method, to hold the modified string u need to assign it some intermediate string. Where as in StringBuffer append is enough to hold the modified String. If u want to add something to the existing string go for Stringbuffer append method.if u go for String concat method, performance may be reduced, as u have to create many intermediary strings which would stay around in the memory for some time. If you compare two StringBuffers, which has same value with equals (), it will return false What is the output of the following code? StringBuffer s1 = new StringBuffer ("abcde"); StringBuffer s2 = new StringBuffer("abcde"); if(s1.equals(s2)) System.out.println("equals"); else System.out.println("not equal"); prints not equal . What are the advantages (and disadvantages) of using String.intern()? First off, let's make sure that we all understand what java.lang.String.intern() actually does... Basically, it internalizes strings such that for any two strings, s1.intern() == s2.intern() if and only if s1.equals(s2). In other words, it makes sure that the returned string reference points to the single, canonical version of that string of characters. It does this by managing a pool of unique string values. Now, as noted in What are the differences between the == operator and the equals () method?, we know that, typically, we can't use the == operator to compare string values because the == operator is just comparing the values of references to those strings rather than the strings' values. But, for internalized strings, since we know that the value of the reference will always be to the unique, canonical version of the string, we can use the == operator. Therefore, the primary benefit in this case is that using the == operator for internalized strings is a lot faster than use the equals() method. So, use the intern() method if you're going to be comparing strings more than a time or three. The primary disadvantage is that you have to remember to make sure that you actually do intern() all of the strings that you're going to compare. [Note that you don't have to intern() string literals or string-valued constants.] It's easy to forget to intern () all strings and then you can get confusingly incorrect results. Also, for

everyone's sake, please be sure to very clearly document that you're relying on the strings being internalized. The second disadvantage if you decide to internalize strings is that the intern() method is relatively expensive. It has to manage the pool of unique strings so it does a fair bit of work (even if the string has already been internalized). So, be careful in your code design so that you e.g., intern () all appropriate strings on input so you don't have to worry about it anymore. How do I convert a String to an Input Stream? Since strings are character based, you should convert the String to a Reader-type stream, not an Input Stream: Reader reader = new String Reader (the String); Note that the StringBufferInputStream doesn't work properly to make a String an Input Stream, as it doesn't properly handle converting characters into bytes. You can also try to work with a ByteArrayInputStream, as in new ByteArrayInputStream (theString.getBytes()), but it only works with platform's default character encoding. How to eliminate duplicate chars in a string? String str = "aabbccc"; String strtest = ""; for (int i=0;i<str.length(); i++) { Char first = str.charAt(i); if(strtest.indexOf(first) == -1) { strtest = strtest + first; } } System.out.println("remove duplicate"+strtest); how to count the number of occurrences of a char in a string? public static int countChars(String s, char c) { if (s.length() == 0) return 0; else if (s.charAt(0) == c) return 1 + countChars(s.substring(1), c); else return countChars(s.substring(1), c); }

How a simple string can be converted to java date?

String str = "01/02/2003"; SimpleDateFormat sdft = new SimpleDateFormat("mm/dd/yyyy"); try { Date utilDate = sdft.parse(str); System.out.println("utilDate"+utilDate); } catch (ParseException e) { e.printStackTrace(); } what is the diff betwn == and .equals method? == checks only the references where as .equals method checks the content of the objets what is the output of the following code? Why? String str1 = "hello"; String str2 = "hello"; if(str1 == str2) { System.out.println("str1 and str2 are equal"); } else { System.out.println ("str1 and str2 are not equal"); } output is both are equal. For performance optimization, String literals are maintained as pool. it checks the contents of the string ,if they are same they would be assigned single address(reference). Java Virtual Machine maintains an internal list of references for interned Strings ( pool of unique Strings) to avoid duplicate String objects in heap memory. Whenever the JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it does not create a new String and it uses reference to the existing String Object. JVM does this type of checking internally for String literal but not for String object, which it creates through 'new' keyword

Optimization by Interning Strings


In situations where String objects are duplicated unnecessarily, String.intern() method avoids duplicating String objects. The following figure shows how the String.intern() method works. The String.intern() method checks the object existence and if the object exists already, it changes point of reference to the original object rather than create a new object. The following figure shows the creation of String literal and String Object using intern

Here is the sample code to know the importance of String.intern() method..

StringTest2.java
package com.performance.string; // This class shows the use of intern() method to improve performance public class StringTest2 { public static void main(String[] args){

// create String references like s1,s2,s3...so on.. String variables[] = new String[50000]; for( int i=0;i<variables.length;i++){ variables[i] = "s"+i; }

// create String literals long startTime0 = System.currentTimeMillis();

for(int i=0;i<variables.length;i++){ variables[i] = "hello"; }

long endTime0 = System.currentTimeMillis(); System.out.println("Time taken for creation of String literals : " + (endTime0 - startTime0) + " milli seconds" );

// create String objects using 'new' keyword long startTime1 = System.currentTimeMillis();

for(int i=0;i<variables.length;i++){ variables[i] = new String("hello"); }

long endTime1 = System.currentTimeMillis(); System.out.println("Time taken for creation of String objects with 'new' key word : " + (endTime1 - startTime1)+" milli seconds");

// intern String objects with intern() method long startTime2 = System.currentTimeMillis(); for(int i=0;i<variables.length;i++){ variables[i] = new String("hello"); variables[i] = variables[i].intern();

long endTime2 = System.currentTimeMillis(); System.out.println("Time taken for creation of String objects with intern(): " + (endTime2 - startTime2)+" milli seconds"); } }

Here is the output of the above code


Time taken for creation of String literals : 0 milli seconds Time taken for creation of String objects with 'new' key word : 160 milli seconds Time taken for creation of String objects with intern(): 60 milli seconds

The default behavior of StringBuffer:


String Buffer maintains a character array internally. When you create String Buffer with default constructor StringBuffer() without setting initial length, then the StringBuffer is initialized with 16 characters. The default capacity is 16 characters. When the StringBuffer reaches its maximum capacity, it will increase its size by twice the size plus 2 ( 2*old size +2). If you use default size, initially and go on adding characters, then it increases its size by 34(2*16 +2) after it adds 16th character and it increases its size by 70(2*34+2) after it adds 34th character. Whenever it reaches its maximum capacity it has to create a new character array and recopy old and new characters. It is obviously expensive. So it is always good to initialize with proper size that gives very good performance. I tested the above StringTest4.java again with two StringBuffers, one without initial size and other with initial size. I added 50000 'hello' objects this time and did not use the + operator. I initialized the second StringBuffer with StringBuffer(250000). The output is Time taken for String concatenation using StringBuffer with out setting size: 280 milli seconds Time taken for String concatenation using StringBuffer with setting size: 0 milli seconds It shows how effective the initialization of StringBuffer is. So it is always best to initialize the StringBuffer with proper size. Example:

long startTime1 = System.currentTimeMillis();

StringBuffer result1 = new StringBuffer("hello");

for(int i=0;i<50000;i++){

Result1.append("hello");

} long endTime1 = System.currentTimeMillis();

System.out.println("Time taken for string concatenation using StringBuffer without setting size: "

+ (endTime1 - startTime1)+ " milli seconds");

long startTime2 = System.currentTimeMillis();

StringBuffer result2 = new StringBuffer(25000);

for(int i=0;i<50000;i++){

result2.append("hello");

} long endTime2 = System.currentTimeMillis();

System.out.println("Time taken for string concatenation using StringBuffer with size: "

seconds"); For string literals see the follwing link.

+ (endTime2 - startTime2)+ " milli

http://www.janeg.ca/scjp/lang/strLiteral.html

what is the output of the code ? why? if( "String".replace('g', 'g') == "String".replace( 'g','g'))

System.out.println("Equal");

else

System.out.println("Not Equal");

Equal would be printed

if( "String".replace('g', 't') == "String".replace( 'g','t'))

System.out.println("Equal");

else

System.out.println("Not Equal"); Not Equal would be printed Reason implementation of replace method

6 UTIL package:
What are the top level interfaces in the util ? Collection,List,Map,Set Diff betwn Vector and ArrayList? Vector is synchronized.Arraylist is not. Vector has constructors : Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. Vector(Collection c) Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection's iterator. Vector(int initialCapacity) Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. Vector(int initialCapacity, int capacityIncrement) Constructs an empty vector with the specified initial capacity and capacity increment. Arraylist has constructors: ArrayList()

Constructs an empty list with an initial capacity of ten. ArrayList(Collection c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. ArrayList(int initialCapacity) Constructs an empty list with the specified initial capacity. What is the diff between Hashtable and HashMap? Hashtable is synchronized and HashMap is not. Hashtable does not allow nulls as a value or key where as Hashmap allows it. Example:

Hashtable ht = new Hashtable(); ht.put("key1","value1"); ht.put("key2",null); ht.put(null,"value2"); u will get Nullpointerexception---best example for runtime exception HashMap hm = new HashMap(); hm.put("key1","value1"); hm.put("key2",null); hm.put(null,null); System.out.println("null as key "+hm.get(null)); Will not get any exception. What is the output of the following code ? will it compile

HashMap hm = new HashMap(); hm.put("key1","value1");

hm.put("key1","value2"); System.out.println("key-vlaue "+hm.get("key1")); Prints value2. What is the difference between Arraylist and LinkedList ? For random access Arraylist would be used For sequential access(read) LinkedList would be preferable. General concept from performance point of view is that ArrayList gives better performance when accessing and iterating objects whereas LinkedList gives better performance when adding and removing objects Although true in most cases, sometimes there is an exception.

Type of operation

ArrayList with ArrayList with out initialization initialization

fast (but slower Adding objects than fast at end initialization)

slow ( slower Adding objects than when at middle adding objects at last) slow ( slower than when Adding objects adding objects at first at last and middle)

slow ( slower than when adding objects at last) slow ( slower than when adding objects at last and middle)

Vector with out Vector with LinkedList initialization initialization fast (but sligtly slower than fast(but sligtly fast ( but slightly initialization and slower than slower than slower than ArrayList ArrayList and ArrayList because of Vector) because of synchronization) synchronization) slow ( slower slow ( slower worse( worse than when than when than every adding objects adding objects operation) at last) at last) slow ( slower slow ( slower slow ( slower than when than when than when adding objects adding objects adding objects at at last and at last and last and middle) middle) middle)

The conclusion for removing objects is 1. All classes take approximately same time when removing objects from end 2. ArrayList and Vector give similar performance with slight difference because of JDK1.3 Hotspot JVM. 3. LinkedList gives worst performance when removing objects from middle (similar to adding objects at middle). 4. LinkedList gives better performance when removing objects from the beginning. 5. Only LinkedList gives better performance when removing objects from the beginning.

The conclusion for accessing objects 1. ArrayList and Vector give best performance because they access objects using index. Vector takes slightly more time but it is negligible. 2. LinkedList gives worst performance when accessing objects at end and middle because it has to scan nodes to access objects. What is the diff betwn List and Set ? Set does not allow duplicate values,where as List allows. What is the diff betwn Hashset and Treeset? HashSet gives better performance than TreeSet because , TreeSet is an ordered collection of objects and the objects are sorted while they are inserted in the TreeSet where as in case of HashSet objects are added in an adhoc manner. It is expensive to do all basic operations in TreeSet because it has to compare and sort every object. We can get better performance by using a HashSet and converting it to a TreeSet later on. Use TreeSet if you want sorted collection otherwise use HashSet The constructors for the HashSet to initialize with proper size are: HashSet(int initialcapacity) HashSet(int initialcapacity, float loadfactor)

Lists: 1. Use ArrayList with proper initialization if you don't want thread safe for the collection whenever you add/remove/access objects at end and middle of collection. 2. Use Vector with proper initialization if you want thread safe for the collection whenever you add/remove/access objects at end and middle of collection. 3. Use LinkedList if you don't want thread safe for the collection whenever you add/remove/access objects at beginning of collection. 4. Use synchronized LinkedList if you want thread safe for the collection whenever you add/remove/access objects at beginning of collection. 5. Use ListIterator than Iterator and Enumeration for List types Sets: 1. Use HashSet for maintaining unique objects if you don't want thread safe for the collection for all basic(add/remove/access) operations otherwise use synchronized HashSet for thread safe. 2. Use TreeSet for ordered and sorted set of unique objects for non-thread safe collection otherwise use synchronized TreeSet for thread safe

Maps: 1. Use HashMap for non-thread safe map collection otherwise use Hashtable for thread safe collection. 2. Use TreeMap for non-thread safe ordered map collection otherwise use synchronized TreeMap for thread safe. How do I load property settings with the Properties class? java.util.Properties objects can load values from a file using the method load(InputStream). Here is the code you need: Properties props = new Properties(); props.load(new FileInputStream("propertyfile.properties")); String value = props.getProperty("propertyname"); Just a trick: in a web archive (war) you can get the InputStream inside the war archive using ClassLoader cl = this.getClass().getClassLoader(); InputStream is = cl.getResourceAsStream("it/package/application.properties"); This is best than using a FileInputStream, because you are loading the file within the archive as it was a resource. You should this.getClass().getClassLoader() to use the same ClassLoader as the one used by the servlet container to load your JSP/Servlet. This code is snipped from a JSP page inside Tomcat. How do I save properties settings with the Properties class? Try this: Properties prop = new Properties(); FileOutputStream output = new FileOutputStream("Test.properties"); prop.store(output,"my testproperties"); output.flush(); output.close(); You'll need to catch an IOException. How can I add an array of objects to a collection? First you need to convert the array to a Collection. This can be done with Arrays.asList(objectArray). Once you have the array as a List, you can add it to another Collection with theCollection.addAll(theList). Example: String[] strArray = {"abc","def","ghi"}; List list = Arrays.asList(strArray);

Collection collection = new ArrayList(); collection.addAll(list); Iterator iterator = collection.iterator(); while(iterator.hasNext()){

String str = (String)iterator.next(); System.out.println("collection " + str); } What's new to the Collections Framework in Java 1.4? There are three new implementations: LinkedHashSet LinkedHashMap IdentityHashMap

One marker interface: RandomAccess

And six new utility methods for the Collections class: rotate(List list, int distance) replaceAll(List list, Object oldVal, Object newVal) indexOfSubList(List source, List target) lastIndexOfSubList(List source, List target) swap(List list, int i, int j) list(Enumeration e)

Can u use the iterator multiple times? U can not.

How do I traverse a sorted set backwards? List list = new LinkedList(set); Collections.reverse(list); for (Iterator it = list.iterator(); it.hasNext();) { System.out.println(it.next()); }

What's the most optimum way of swapping two elements in a List?

The 1.4 version of Collections has a swap() method to do this for you. However, for earlier version of Java, you can swap two elements w/o an intermediate variable with: list.set(index1, list.set(index2, list.get(index1))); This works because the set() method returns the original element. Example: List collection = new ArrayList(); collection.add("abc"); collection.add("def"); collection.add("ghi"); Collections.swap(collection,0,1); Iterator iterator = collection.iterator(); while(iterator.hasNext()){

String str = (String)iterator.next(); System.out.println("collection " + str); } How do you sort an ArrayList (or any list) of user-defined objects? Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator). How can I retrieve the items in my HashSet / HashMap in the order they were added? Prior to Java 1.4, you had to manage a separate insertion order list yourself. Starting with Java 1.4, you can use the new LinkedHashMap / LinkedHashSet classes. The iterators you get back from them return the items in insertion order. Example: String Englishmonths[] = new DateFormatSymbols().getMonths();

String frenchMonths[] = new DateFormatSymbols(Locale.ITALIAN).getMonths(); Map orderedMap = new LinkedHashMap(); for (int i = 0, n = Englishmonths.length; i < n; i++)

{ orderedMap.put(Englishmonths[i], frenchMonths[i]); }

Collection values = orderedMap.values(); for (Iterator i = values.iterator(); i.hasNext(); ) { System.out.println(i.next()); } int a[] = {1, 2, 3}; int b[] = {1, 2, 3}; if u want to check the equality of two arrays ,which method should be used? int a[] = {1, 2, 3}; int b[] = {1, 2, 3}; Arrays.equals()

How do I create a read-only collection? The Collections class has six methods to help out here: unmodifiableCollection(Collection c) unmodifiableList(List list) unmodifiableMap(Map m) unmodifiableSet(Set s) unmodifiableSortedMap(SortedMap m)

unmodifiableSortedSet(SortedSet s)

If you then get an Iterator from one of these unmodifiable collections, when you call remove() it will throw an UnsupportedOperationException.

How do I synchronize a collection? Collection c = Collections.synchronizedCollection(myCollection);

Diff betwn Iterator and enumerator?

Iterator is returned by List and other Collection interfaces. Iterator is fail fast if a modification to the collection is performed while iterating. Enumeration is used by Vector and Hashtable. Enumeration may or may not throw an error if the collection is changed. (Make reproducing errors harder) Remove method is there in iterator where as it is not there in Enumerator.

7 Wrapper Classes:
What is the significance of wrapper classes ? Java wrappers are classes that wrap up primitive values in classes that offer utility methods to manipulate the values. If for example you want to store a set of int values in the elements of a Vector, the values in a Vector must be objects and not primitives. When you want to retrieve the values wrapped up in the Integers that are in the Vector elements you will need to cast the elements back to Integers and then call the toxxValue in order to get back the original number

Different ways of converting a string to number ? 1. String strNumber = 100; Integer number = new Integer(strNumber); 2. int intNum = Integer.parseInt(strNumber); What will happen when you attempt to compile and run the following code?

public class WrapMat{ public static void main(String argv[]){ Integer iw = new Integer(2); Integer iw2 = new Integer(2); System.out.println(iw * iw2); System.out.println(iw.floatValue()); } } * can not be operated on wrapper classes. It is only used for primitives.

8 I/O package
The stream classes are divided into two class hierarchies, based on the data type (either characters or bytes) on which they operate.

Character Streams :

Byte Streams :

As with Reader and Writer, subclasses of InputStream and OutputStream provide specialized I/O that falls into two categories, as shown in the following class hierarchy figure: data sink streams (shaded) and processing streams (unshaded).

What's the difference between a StringBuffer and StringBuilder? The StringBuilder class was introduced with JDK 5.0. Essentially, a StringBuffer is a thread-safe version of StringBuilder. If you are only adding/removing characters from a single-thread, the StringBuilder implementation will be faster. If you are using multiple threads to add and remove characters, use StringBuffer.

How do I load property settings with the Properties class?

Properties props = new Properties(); props.load(new FileInputStream("propertyfile.properties")); String value = props.getProperty("propertyname"); //Just a trick: in a web archive (war) you can get the InputStream inside the war archive using ClassLoader cl = this.getClass().getClassLoader(); InputStream is = cl.getResourceAsStream("it/package/application.properties"); This is better than using a FileInputStream, because you are loading the file within the archive as it was a resource. You should use this.getClass().getClassLoader() to use the same ClassLoader as the one used the servlet container to load your JSP/Servlet. This code is snipped from a JSP page inside Tomcat. How do I get a listing of all the files in a directory and its sub-directories? To recursively get all files under a specific directory, just keep calling listFiles() on the File that is returned, if it is a directory (isDirectory() returns true). Here is what it looks like... From vineet bhatia /** * list all files in a directory and its sub-directories * @param directory to be scanned * @return vector of the files in all the sub-directories */ private Vector listAllFiles(File directory) { String[] fileList = null; Vector vectList = new Vector(); if(directory.isDirectory()) fileList = directory.list(); String path = directory.getAbsolutePath(); for(int i=0; i<fileList.length;i++) { File f = new File(path + File.separator + fileList[i]); if(!f.isDirectory()) vectList.addElement(fileList[i]); else { Vector subList = listAllFiles(f); Enumeration enum = subList.elements(); while(enum.hasMoreElements()) vectList.addElement(enum.nextElement()); } } return vectList;

Is there an easy way of counting line numbers? Or do you have to go through the entire file? You have to go through the entire file. LineNumberReader lnr; try { lnr = new LineNumberReader(new FileReader("fixwrapper.props")); String s; while ((s = lnr.readLine()) != null); System.out.println("Lines: " + lnr.getLineNumber()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

When do you use the Reader/Writer classes, instead of the InputStream/OutputStream classes? The InputStream/OutputStream classes are for reading and writing bytes, while the Reader/Writer classes are for reading characters / text. If you need to process text, you use Reader/Writer. If you need to process content at the byte level, either as the raw bytes, or as higher level data like primitives (through DataInput/Output), objects (through ObjectInput/Output), or possibly compressed data (GZIPInput/Output), then you would work with an InputStrem/OutputStream. How do I get the creation date and time of a file? There is no support for getting the creation date and time of a file from Java. All you can get is when the file was last modified, with the the lastModified() method of File. How can I use Runtime.exec() to run MS-DOS commands without having MSDOS shells popup each time? String[] command = { "C:\\winnt\\system32\\cmd.exe", "/y", "/c", "dir"}; try { Process p = Runtime.getRuntime().exec(command);

InputStream is = p.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { } e.printStackTrace();

How can I open the same file for reading as well as writing? The RandomAccessFile class supports simultanous reading and writing from the same file. Just open it in "rw" mode: RandomAccessFile raf = new RandomAccessFile("filename.txt", "rw"); Use skipBytes() to move to where you wish to read/write. How do I read text from standard input?

try { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(isr); String line = null; while ((line = reader.readLine()) != null) { System.out.println("Read Line" + line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } How do I get a listing of the files in a directory? Create a java.io.File for the directory, then ask for the list of files with one of the following: public java.lang.String[] list(); public java.lang.String[] list(java.io.FilenameFilter); public java.io.File[] listFiles();

public java.io.File[] listFiles(java.io.FilenameFilter); public java.io.File[] listFiles(java.io.FileFilter); The first two return the filenames as strings (for that directory), the latter three return actual File objects. Also, see Re: how do i search a file from a folder that is in the server side using servlet for another method that lists files in a directory. How do I check for end-of-file when reading from a stream? Exactly how depends upon which stream you are reading from. If you are reading with the read() method of InputStream/Reader, this will return -1 on EOF. If however you are using BufferedReader.readLine(), then this will return null on end of file. And, the readXXX operations of the DataInput interface throw an EOFException. If you are unclear how to terminate your reading, check the javadoc for the stream you are using. How do I append to end of a file in Java?

You can use java.io.RandomAccessFile and something like the following:

try { RandomAccessFile raf = new RandomAccessFile("filename.txt", "rw"); raf.skipBytes( (int)raf.length() ); // You are now at the end of the file, // and can start writing new data out, e.g. raf.writeBytes( "Log restarted at 13:00pm 3-2-2000\n"); raf.close(); } catch (IOException ex ) { ex.printStackTrace(); } or you can use FileWriter / FileOutputStream and open it for append: FileWriter writer = new FileWriter("filename.txt", true); Can I use a BufferedOutputStream with an ObjectOutputStream to serialize an object? Yes. In fact, it is recommended that you buffer all your input and output unless you have a good reason not to. Here's an example of how to do this: ... String myobject = new String("myobject"); try {

FileOutputStream file = new FileOutputStream("myobject.ser"); BufferedOutputStream bout = new BufferedOutputStream(file); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(myobject); out.flush(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ... Java allows you to chain I/O streams together. Using a BufferedOutputStream makes output much more efficient because the I/O overhead is then expended on large chunks of data, rather than on individual bytes. Likewise, many times it makes sense to compress your output, say if you are writing many large objects to a file or a socket. You can do this using a ZipOutputStream or a GZIPOutputStream in place of (or in addition to!) the BufferedOutputStream in the above example.

How can you improve Java I/O performance? Java applications that utilise Input/Output are excellent candidates for performance tuning. Profiling of Java applications that handle significant volumes of data will show significant time spent in I/O operations. This means substantial gains can be had from I/O performance tuning. Therefore, I/O efficiency should be a high priority for developers looking to optimally increase performance. The basic rules for speeding up I/O performance are Minimise accessing the hard disk. Minimise accessing the underlying operating system. Minimise processing bytes and characters individually. Use the NIO package, if you are using JDK 1.4 or later, which uses performanceenhancing features like buffers to hold data, memory mapping of files, non-blocking I/O operations etc. I/O performance can be improved by minimising the calls to the underlying operating systems. The Java

runtime itself cannot know the length of a file, querying the file system for isDirectory(), isFile(), exists() etc must query the underlying operating system. Where applicable caching can be used to improve performance by reading in all the lines of a file into a Java collection class like an ArrayList or a HashMap and subsequently access the data from an in-memory collection instead of the disk.

9 Serialization:
What is a marker interface in java ? Serializable,Runnable are examples Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket. Deserialization is the process of reading back that serialized java object stream from input stream. A java object is serializeable and deserializeable if that class follows the following rules A) The java class must implement java.io.Serializable interface or java.io.Externalizable interface or inherit that implementation from any one of it's super class implementation. B) All instance variables of that class must implement Serializable interface or Externalizable interface or inherit from one of it's super class. All primitive data types and some of standard java API classes are serializable. You need not explicitly implement Serializable or Externalizable interfaces for those classes. Serialization process ignores class (static) variables. Externalizable interface allow to do your own custom implementation of serialization. In this section, focus is only on Serializable interface. We will talk initially about Serializable interface. This is a marker interface and does not have any methods. All major java technologies like RMI, EJB are based on serialization process to pass the objects through network. These technologies implicitly do all the serialization work for you. You need to simply implement the java.io.Serialzable interface, but If you want to do your own serialization, that is reading from or writing to streams, ObjectInputStream and ObjectOutputStream can be used.

These methods help to write into stream and read from stream ObjectInputStream.readObject(); // to read object

ObjectInputStream.writeObject(Object obj); // to write object Initially, We need to understand the default mechanism of serialization process in order to improve performance Serialization and deserialization of object Example: public class JavaQTest {

public static void main(String[] args) {

SerializeTest serTest = new SerializeTest(); serTest.setBaseName("BaseName"); serTest.setBaseSalary("BaseSalary"); serTest.setFirstName("Srinu"); serTest.setLastName("Vanka"); serTest.setSalary(4444);

try { FileOutputStream file = new FileOutputStream("SerializeTest.abc"); BufferedOutputStream bout = new BufferedOutputStream(file); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(serTest); out.flush(); FileInputStream fin = new FileInputStream("SerializeTest.abc");

BufferedInputStream bin = new BufferedInputStream(fin); ObjectInputStream oin = new ObjectInputStream(bin); SerializeTest serRead = (SerializeTest)oin.readObject(); System.out.println("read from ser file BaseName " +serRead.getBaseName()); System.out.println("read from ser file BaseSalary" +serRead.getBaseSalary()); System.out.println("read from ser file FirstName " +serRead.getFirstName()); System.out.println("read from ser file LastName " +serRead.getLastName()); System.out.println("read from ser file Salary" +serRead.getSalary()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }

} public class SerializeTest implements Serializable{

private String firstName;

private String lastName ;

private final static String serailize = "serailize";

private int salary = 0;

/** * @return Returns the firstName. */ public String getFirstName() { return firstName; } /** * @param firstName The firstName to set. */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return Returns the lastName.

*/ public String getLastName() { return lastName; } /** * @param lastName The lastName to set. */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return Returns the salary. */ public int getSalary() { return salary; } /** * @param salary The salary to set. */ public void setSalary(int salary) { this.salary = salary; } }

public class SerializeBase implements Serializable{

private String baseName; private String baseSalary;

/** * @return Returns the baseName. */ public String getBaseName() { return baseName; } /** * @param baseName The baseName to set. */ public void setBaseName(String baseName) { this.baseName = baseName; } /** * @return Returns the baseSalary. */ public String getBaseSalary() { return baseSalary; } /** * @param baseSalary The baseSalary to set. */

public void setBaseSalary(String baseSalary) { this.baseSalary = baseSalary; } } .ser file extension is not necessary, u can give any extension. what is the use of key word transient ? if u make any variable transient,it will not get serialized

Are methods also serialized along with the data members? No. Method bodies do not hold any information on the state of an object, so they are not needed in order to save or restore the state. Serialization is for saving the state of an object instance, whereas the object's methods and static fields are class-level properties. So, there is no need to serialize methods and static members.

Can a Vector or a Hashtable be serialized and deserialized?

Both these classes implement Serializable, and have been designed for serialization. So yes, they can be serialized. One thing you have to watch out for, though, is that in order to serialize a collection like Vector or Hashtable, you must also be able to serialize all of the objects contained in these collections. Otherwise, the collection would not be able to be completely restored. Your program will throw a NotSerializableException unless all objects stored in the Vector or Hashtable are also serializable. Can I serialize an object that has native methods? Method implementations, whether native or pure Java, are not part of the serialized state of an object. There is nothing that prevents objects with native methods from being serialized. It might however be problematic in practice to reconstitute these objects if the native code can't be loaded, e.g. when sending serialized objects over a socket where the other end doesn't have the native library installed. It is of course also a problem if the other end can't load the .class files, but native libraries can't be dynamically downloaded like .class files.

Why would I want to implement Externalizable instead of Serializable?

By implementing Externalizable yourself you can win performance at the cost of flexibility and extra code to maintain. If you implement Externalizable yourself you stream the data directly without the need for reflection which is used in the case of Serializable.

Externalization is also useful for working around serialization bugs in classes you don't control. For instance, a third-party (or JFC!) class may be specified as Serializable, but it throws an exception when serialized or deserialized. You can subclass this class into one that's Externalizable and define a no-argument constructor for it. The implement your constructor to call whichever superclass constructor pleases you. Implement writeExternal() by saving off the fields you're interested in. Implement readExternal() to read these fields back in and reconfigure the superclass. In this way, you effectively take over all serialization work; it's as if the superclass doesn't even implement Serializable.

http://java.sun.com/developer/TechTips/2000/tt0425.html

How can I do a deep clone of an object? Or How can I make a deep copy of an object using serialization?

The default/conventional behavior of clone() is to do a shallow copy. You can either override clone() to do a deep copy or provide a separate method to do a deep clone. The simplest approach to deep cloning is to use Java serialization, where you serialize and deserialize the object and return the deserialized version. This will be a deep copy/clone, assuming everything in the tree is serializable. If everything is not serializable, you'll have to implement the deep cloning behavior yourself. Assuming everything is serializable, the following should create a complete deep copy of the current class instance: ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); Object deepCopy = ois.readObject();

My subclass implements Serializable but my superclass doesn't. Both subclass and superclass contain instance variables that need to be saved as part of the state of the subclass. Will serialization save the superclass fields for me?

When you serialize an object, the serialization mechanism works by chaining up the inheritence hierarchy, saving the sate of each Serializable superclass in turn. When serialization reaches the first non-serializable superclass, the serialization stops. When deserializing, the state of this first non-serializable superclass is restored not from the stream, but by invoking that class' no-argument constructor. If the noargument constructor is not adequate for your purposes, you must customize the serialization of your subclass with writeObject() and readObject() in order to write out and restore any information from the non-serializable superclass that you find necessary.

What things are required for a class that implements Serializable? A class that implements Serializable must also: Have access to a no-argument constructor in its first non-serializable superclass Identify non-serializable data members using the transient keyword or explicitly mark data members as serializable using the serialPersistentFields member.

What are the advantages and disadvantags of serialization? The advantages of serialization are: It is easy to use and can be customized. The serialized stream can be encrypted, authenticated and compressed, supporting the needs of secure Java computing. Serialized classes can support coherent versioning and are flexible enough to allow gradual evolution of your application's object schema. Serialization can also be used as a mechanism for exchanging objects between Java and C++ libraries, using third party vendor libraries (like RogueWave's Tools.h++ ) within C++. There are simply too many critical technologies that rely upon serialization, including RMI, JavaBeans and EJB.

However, serialization has some disadvantages too: It should ideally not be used with large-sized objects, as it offers significant overhead. Large objects also significantly increase the memory requirements of your application since the object input/output streams cache live references to all objects written to or read from the stream until the stream is

closed or reset. Consequently, the garbage collection of these objects can be inordinately delayed. The Serializable interface does not offer fine-grained control over object access - although you can somewhat circumvent this issue by implementing the complex Externalizable interface, instead. Since serialization does not offer any transaction control mechanisms per se, it is not suitable for use within applications needing concurrent access without making use of additional APIs.

Why doesn't serialization save the value of static variables? Variables declared as static members are not considered part of the state of an object because they are shared by all instances of that class. Classes which need to preserve the value of static members during serialization should save and restore these values explicitly using private void readObject(ObjectInputStream) and private void writeObject(ObjectOutputStream).

What are the security ramifications of using the Externalizable interface? The methods within the Externalizable interface, readExternal() and writeExternal() have public scope. This implies some client object could potentially bypass the Java sandbox mechanisms and overwrite or gain access to the state of an externalizable object. As a general rule of thumb, a class should implement the Externalizable interface only if the object contains nonsensistive information.

10 Threads
Briefly explain high-level thread states? Runnable waiting for its turn to be picked for execution by the thread schedular based on thread priorities. Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should not be used very frequently. Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish. Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);

Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes. Blocked on synchronization: Will move to Runnable when a lock is acquired. Dead: The thread is finished working.

What is the difference between yield and sleeping? When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state. Significance of synchronized key word ? It can be used for blocks and can also be used for methods. Two threads concurrently can not access the synchronized method of same object. Best Example for synchronized

public class FirstThread implements Runnable{

public SynchronizedClass test = null;

public FirstThread(SynchronizedClass pTest) {

this.test = pTest; }

public void run() { System.out.println("thread 1 start");

// test.syncMethod1("First Thread");

test.staticSyncMethod1("First Thread"); //test.nonSyncMethod("First Thread"); System.out.println("thread 1 end"); }

public static void main(String args[]) throws InterruptedException{ SynchronizedClass test = new SynchronizedClass();

Thread t1 = new Thread(new FirstThread(test)); t1.start();

Thread t2 = new Thread(new SecondThread(test)); t2.start();

/* for(int i=0; i<10; i++){ try{ Thread.sleep(1000);//this.wait(1000); System.out.println("Calling from current thread :"+i); }catch(Exception e){

e.printStackTrace(); } }*/

public class SecondThread implements Runnable{

public SynchronizedClass test = null;

public SecondThread(SynchronizedClass pTest){ this.test = pTest; }

public void run(){ System.out.println("thread 2 start"); //test.staticSyncMethod("Second Thread"); test.staticSyncMethod2("Second Thread"); System.out.println("thread 2 end"); }

public class SynchronizedClass{

public static synchronized void staticSyncMethod1(String source){

System.out.println("staticSyncMethod 1-> static synchnorized1");

for(int i=0; i<10; i++){ try{ Thread.sleep(1000);//this.wait(1000); System.out.println("Calling from "+source+" static synchnorized:"+i); }catch(Exception e){ e.printStackTrace(); } }

public static synchronized void staticSyncMethod2(String source){

System.out.println("staticSyncMethod2 -> static synchnorized2");

for(int i=0; i<10; i++){ try{ Thread.sleep(1000);//this.wait(1000); System.out.println("Calling from "+source+" static synchnorized:"+i);

}catch(Exception e){ e.printStackTrace(); } }

public synchronized void syncMethod1(String source){

System.out.println("Calling from "+source+" syncMethod1 -> synchnorized");

for(int i=0; i<10; i++){ try{ Thread.sleep(1000);//this.wait(1000); System.out.println("Calling from "+source+" syncMethod1 synchnorized:"+i); }catch(Exception e){ e.printStackTrace(); } }

public synchronized void syncMethod2(String source){

System.out.println("Calling from "+source+" syncMethod2 -> synchnorized");

for(int i=0; i<10; i++){ try{ Thread.sleep(1000); System.out.println("Calling from "+source+" syncMethod2 synchnorized:"+i); }catch(Exception e){ e.printStackTrace(); } }

public void nonSyncMethod(String source){

System.out.println("Calling from "+source+" nonSyncMethod -> Non synchnorized");

for(int i=0; i<10; i++){ try {

System.out.println("Calling from "+source+" nonSyncMethod synchnorized:"+i); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }

What is the difference between Process and Threads ? How to communicate 2 threads each other ? What does it mean to lock an object? Every object instance in Java has a little piece of data hanging off of it called a "monitor lock." This is similar to a semaphore. When you use the synchronized keyword, the current thread attempts to obtain the monitor lock for the object in question (either "this" or the object named explicitly). If the lock is unavailable, because another thread has acquired it, then the current thread pauses indefinitely. When it wakes up again, it will have acquired the lock, and will retain it until the end of the code block where synchronized was used. One confusing part is that the only thing that this lock locks is access to the lock itself. It does not control access to instance variables or method access in and of itself. Other threads can reach in and modify variables and call methods. If you want the lock to control access to variables, then you must explicitly use the synchronized keyword every single place in your code that accesses them.

A straightforward way to guarantee that no variable access happens without a lock is by making all your variables private and using synchronized on all your accessor/mutator methods (getFoo/setFoo). What is the difference between sleep and yield? yield() tells the JVM Thread Scheduler that it's OK to give other threads time slices. Usually the JVM uses this call to activate another thread of the same thread priority. In a good preemptive multithreading environment, yield() is a no-op. However, it is important in a cooperative multithreading environment, since without yield(), one thread can eat up all of the CPU. sleep(x) tells the JVM Thread Scheduler to actively put this thread to sleep and not run it again until at least x milliseconds have elapsed. Neither sleep() nor yield() change anything about the status of synchronization locks. If your thread has a lock, and you call sleep(1000), then at least a second will elapse before your thread wakes up. When it wakes up it may decide to release the lock -- or it may hold on to it longer. If an exception is thrown inside a synchronized block will the lock on the object that was synchronized be automatically released? It depends on whether the exception escapes (passes through) the synchronized block or not. Consider the following example. try { synchronized (o) { try { doSomething(); } catch (A) { a(); } } } catch (B) { b(); } If doSomething() throws an exception of type A, it will be caught by the inner try block, and the lock on o will still be active during method a(). However, if doSomething() throws an exception of type B, it will be caught by the inner try block -- on its way out of the series of nested stack frames -- and the lock will be released before method b() is invoked What is deadlock? How can I eliminate it? A simple deadlock situation is one in which a two threads are waiting. Each thread waiting for a resource which is held by the other waiting thread. [In Java, this resource is usually the object lock obtained by the synchronized keyword.]

This deadlock situation can range from the above two thread situation to any number of threads waiting in a circular fashion. Many solutions to this well known problem have been defined over the years including the large range of solutions to "The Dining Philosophers" problem. Hope this can point you in the right direction.

For an example, let's take a simple bank application. Consider the following: class Account { private int id; private int balance; public Account(int id) { this.id = id; } public synchronized void deposit(int amount) { this.balance += amount; } public synchronized void withdraw(int amount) { this.balance -= amount; } public static void transfer(Account from, Account to, int amount) { synchronized (from) { synchronized (to) { from.withdraw(amount); to.deposit(amount); } } } Imagine that there are two concurrent accesses to transfer, one doing transfer(a1, a2), and one doing transfer(a2, a1). If the first thread swaps out after locking a1 but before locking a2, then the second thread locks a2, we have deadlock. The second thread will block on a1 (since the first thread has it already), and the first thread will block on a2 (since the second thread has it already). Unfortunately, there is no universal solution. Some solutions include... Ordered lock acquisition. Change transfer() to public static void transfer(Account from, Account to, int amount) { Account first; Account second; if (a1.id < a2.id) { first = a1; second = a2; } else { first = a2; second = a1;

} synchronized (first) { synchronized (second) { from.withdraw(amount); to.deposit(amount); } } } This type of solution will work for any number of locks, assuming that there's some way to consistently order them. In this case, we know that each object has an immutable id variable; since it's an int, it's got built-in ordering.

Encapsulation (forcing directionality) Design your program so the only access to a thread-unsafe object is through a thread-safe object. Spawn new threads to handle each part of the transaction. If each thread only locks one object at a time there can be no deadlock. Check and back off If you can test to see if another thread has a lock you want, you can "back off" instead of locking it, allowing it to complete its transaction before trying again. This can't be done with normal Java locks, but you can try to write your own lock object to satisfy them. Timeout If you write your own lock object, it can automatically return from the "lock" method if a certain amount of time elapses. Minimize or remove synchronization If there's no locks, there's no deadlock!

These solutions must be applied to your particular needs; sometimes it will be impossible to use one or more of them. See Doug Lea's Concurrent Programming in Java for more details. How do you write a Thread-Safe Singleton? public class JGKSingleton { /* Here is the instance of the Singleton */ private static JGKSingleton instance_; /* Need the following object to synchronize */ /* a block */ private static Object syncObject_; /* Prevent direct access to the constructor private JGKSingleton() { super(); } public static JGKSingleton getInstance() {

/* in a non-thread-safe version of a Singleton */ /* the following line could be executed, and the */ /* thread could be immediately swapped out */ if (instance_ == null) { synchronized(syncObject_) { if (instance_ == null) { instance_ = new JGKSingleton(); } } } return instance_; } } How can I control which waiting thread is notified when I call notify()? There is no way to control which thread is notified when you call notify(). Neither thread priorities nor order of entering wait() determine what is notified first. [Any pattern you may notice is platform-specific and should not be relied upon. -Alex] What is the keyword volatile used for? What sort of situations should I use volatile when developing a multi-threaded application? "If a double or long variable is not declared volatile, then ... they are treated as if they were two variables of 32 bits each... Consequently, if two threads concurrently assign distinct values to the same shared non-volatile double or long variable, a subsequent use of that variable may obtain a value that is not equal to either of the assigned values, but some implementation-dependent mixture of the two values." "Meanwhile, programmers are cautioned always to explicitly synchronize access to shared double and long variables." So shared double and long fields should be either declared as volatile or the access to the whole object should be synchronized. How can I actually, really deallocate a Thread to release the memory? Setting thread = null does not work!

Using thread = null will not release a running thread. In order to release the memory associated with a thread, you need to make sure that all of the following are done: Make sure that the thread's start() method has been called. Make sure that the thread has stopped executing. Clear any references to that Thread object (thread = null;).

This is the best you can do to ensure the release of memory for a Thread. You have to call start() on the thread because several JVMs have a bug where they will not release all the thread's memory if the thread is not started What is the meaning of calling a method or object "thread-safe?" Basically, calling a method "thread-safe" means that even if multiple threads try to access it simultaneously, nothing bad happens. Here "bad" usually means that due to race conditions, or deadlock, or other pitfalls, the object's state gets corrupted, or its methods produce unreliable results. A method usually acheives thread-safety by protecting access to shared resources. This usually translates to using the Java synchronized keyword to protect blocks of code that access instance variables, or other shared variables. For an object to be thread-safe, it must be possible for multiple threads to simultaneously access the same method, or multiple methods, in that object. Usually this is acheived by assuring that each method is thread-safe, but this doesn't always suffice, since methods can call each other in strange ways, leading to deadlock and other weirdness. It is very difficult to prove that an object is thread-safe. The main rule of thumb for making thread-safe objects is, "Make all the instance variables private, and all the public accessor methods synchronized." However, this is sometimes difficult to achieve in practice, due to exigencies of performance, architecture, or implementation. Accurate multithreaded programming is a true art, and very difficult to master. Read "Java Threads" by Oaks and Wong, and "Concurrent Programming in Java" by Lea, for inspiration in your quest to become a thread-safe programmer. What is the difference between sleep(), wait() and suspend()? Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread. t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone. object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock

object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object. Why are the methods wait() and notify() defined in the Object class when they are used with Threads? The wait() and notify() methods are object-specific. The wait() method suspends the current thread of execution, and tells the object to keep track of the suspended thread. The notify() method tells the object to wake up the suspended threads that it is currently keeping track of. Since wait() and notify() are object specific, they must be used within code that is synchronized on the object in question. It is also important to use state variables when using wait() and notify(), as threads can be woken up by conditions other than notify(). suspend() is similar to wait() but does not add the thread to an object's wait list. What are the differences between extending the Thread class and implementing the Runnable interface? Extending the Thread class will make your class unable to extend other classes, because of the single inheritence feature in JAVA. However, this will give you a simpler code structure. If you implement runnable, you can gain better objectoriented design and consistency and also avoid the single inheritance problems. How do I have one thread wait for another thread to finish before continuing? You can wait for a thread to finish by calling its join() method. For instance, in the following code, the current thread will wait until thread2 finishes before printing Done. thread2.start(); // do more stuff here thread2.join(); System.out.println("Done");

11 Reflection 12 JDK 1.5 Features:


In this article, we'll discuss several of the new language features of JDK 1.5, including:

GenericsProvides compile-time type safety for collections and eliminates


the need for casting every time you get an object out of Collections.

Can you give me an example of how it is useful in your current project?

Enhanced For loopEliminates error-proneness of iterators. Autoboxing/unboxingEliminates need of manual conversion between
primitive types (such as double) and wrapper types (such as Double). Typesafe enumsProvides all benefits of the Typesafe enum pattern. Advantages of enum : 1. can be used in enhanced for loop 2. Switch statement (in JDK 1.4 only with int values) How to define enum? Public enum/Enum Day{ }

Is enum is Serializable ?

Static importEliminates the need for using class names prior to using the static member variables of other classes. This will make the code a bit neater. Metadata (Annotation)Allows programmers to avoid writing boiler plate code and gives the opportunity for declarative programming.

Annotations can be applied to ?


TYPE Applied only to Type. A Type can be a Java class or interface or an Enum or even an Annotation. FIELD Applied only to Java Fields (Objects, Instance or Static, declared at class level). METHOD Applied only to methods. PARAMETER Applied only to method parameters in a method definition. CONSTRUCTOR Can be applicable only to a constructor of a class. LOCAL_VARIABLE Can be applicable only to Local variables. (Variables that are declared within a method or a block of code). ANNOTATION_TYPE Applied only to Annotation Types. PACKAGE Applicable only to a Package.

@Retention(RetentionPolicy.CLASS)?

Retain the Annotation in the Source Code only Retain the Annotation in the Class file also. Retain the Annotation Definition during the Run-time so that JVM can make use of it.

Annotattion Usages?

Annotations will also be used for compile-time checking such as to produce warnings and errors for different failure scenarios. An example of an annotation that is used at compile time is the new @Deprecated annotation, which acts the same as the old @deprecated JavaDoc tag. Of course, a compiler has to know how to interpret annotation data that is meant to produce compile-time warnings, so again, annotations that do things at compile time will likely be used frequently, but rarely written by average developers. Annotations can be useful at runtime as well. Using annotations you could mark code to behave in a particular way whenever it is called. For example, you could mark some methods with a @prelog annotation. Then at runtime, you could analyze the methods that you're calling and print a particular log message before you begin executing code for that method. One way to achieve this would be through the use of the updated Java 1.5 reflection API. The reflection API now provides access to runtime-accessible annotation data. < Another way to use annotations at runtime is to use Aspect-Oriented Programming (AOP). AOP uses pointcutssets of points configured to executed aspects. You could define a pointcut that will execute an aspect for an annotated method. My guess is that developers would be more likely to write their own runtime annotation types than they would annotation types used for code generation and compile-time checking. Still, writing and understanding the code that accesses the annotations (the annotation consumer) at runtime is fairly advanced.

Let's discuss each feature in detail and take a look at some examples. Generics Generics is one of the coolest features of JDK 1.5. By introducing generics, we will have compile-time type safety and possibly fewer ClassCastExceptions during run time. In JDK 1.5, you can declare the type of objects one collection will accept/return. In JDK 1.4, creating a List of employee names requires a collection object like the following statement: List listOfEmployeeName = new ArrayList(); In JDK 1.5, you would use this statement: List<String> listOfEmployeeName = new ArrayList<String>(); The cool part is that if you try to insert something that's not a string, you will find out at compile time and then you can fix the problem. Without generics, you discover such a bug when your customer calls and tells you that the program you shipped crashed with a ClassCastException.

The other cool thing is that you don't have to cast when you get an element out of the collection. So instead of this type of statement: String employeeName = ((String) listOfEmployee.get(i)); It's simply: String employeeName = listOfEmployee.get(i); Casting objects without knowing the type of object is not good, and more importantly, it can fail at run time. Suppose the user accidentally passes in a collection that contains string buffers rather than strings. In Listing A, the client is required to pass in a collection of strings that the compiler can't enforce.Listing B shows how the same method looks with generics. Now it's clear from the method signature that the input collection must contain only strings. If the client tries to pass in a collection of string buffers, the program won't compile. And notice that the method doesn't contain any casts. It's one line shorter and, once you get used to reading generics, it's clearer too. Enhanced For Loop Here's the syntax for the For loop in the current version of the JDK: void printAll(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) { Employee emp = (Employee)i.next(); System.out.println(emp.getName()); } } Now here's the same method with an enhanced For statement: void printAll(Collection c) { for (Object o : c) System.out.println((TimerTask)o).getName()); } In this For loop, you should read the ":" as "in," so the example reads "for Object o in c". You can see this For loop has more readability. Autoboxing and unboxing In Java, we have primitive data types and wrapper classes around these primitive types. Most often programmers need to convert one type to another. Take a look at the code snippet in Listing C. Notice how messy the inner-loop code that calculates ageAfterTenYear looks. Now take a look at the same program rewritten with autoboxing, as shown in Listing D. One thing worth noting: Previously, if you unboxed Null, it became zero. In this code, the

compiler would automatically convert Integer to int and add 10 to it, then convert that back to Integer. Typesafe enums Typesafe enums provide the following features:

They provide compile-time type safety. They are objects, so you can put them in collections. They are implemented as a class, so you can add some methods. They provide a proper name space for the enumerated type. Their printed values are informativeif you print an int enum, you just see a number, which may not be that informative.

Example 1: enum Season { winter, spring, summer, fall } Example 2: public enum Coin { penny(1), nickel(5), dime(10), quarter(25); Coin(int value) { this.value = value; } private final int value; public int value() { return value; } } Static imports Static imports make code more readable. Currently, you use constants defined in other classes, like this: import org.yyy.pkg.Increment; class Employee { public Double calculateSalary(Double salary{ return salary + Increment.INCREMENT * salary; } } But with static import, we can use those constants without providing the name of the class prior to constant name, like this: import static org.yyy.pkg.Increment; class Employee { public Double calculateSalary(Double salary{ return salary + INCREMENT * salary;

} } Note that we are able to call the INCREMENT constant without using the class name Increment. Metadata The metadata feature is focused on making a developer's life simpler with the support of tools provided by vendors. Take a look at the code in Listing E. With metadata support, you can write the code in Listing E like this: import org.yyy.hr; public class Employee { @Remote public String getName() { ... } @Remote public public String getLocation() { ... } }

13 JDBC :
JDBC defines how a Java program can communicate with a database. This section focuses mainly on JDBC 2.0 API. JDBC API provides two packages they are java.sql and javax.sql . By using JDBC API, you can connect virtually any database, send SQL queries to the database and process the results. JDBC architecture defines different layers to work with any database and java, they are JDBC API interfaces and classes which are at top most layer( to work with java ), a driver which is at middle layer (implements the JDBC API interfaces that maps java to database specific language) and a database which is at the bottom (to store physical data). The following figure illustrates the JDBC architecture.

JDBC API provides interfaces and classes to work with databases. Connection interface encapsulates database connection functionality, Statement interface encapsulates SQL query representation and execution functionality and ResultSet interface encapsulates retrieving data which comes from execution of SQL query using Statement. The following are the basic steps to write a JDBC program 1. Import java.sql and javax.sql packages 2. Load JDBC driver 3. Establish connection to the database using Connection interface 4. Create a Statement by passing SQL query 5. Execute the Statement 6. Retrieve results by using ResultSet interface 7. Close Statement and Connection We will look at these areas one by one, what type of driver you need to load, how to use Connection interface in the best manner, how to use different Statement interfaces, how to process results using ResultSet and finally how to optimize SQL queries to improve JDBC performance.

Note1: Your JDBC driver should be fully compatible with JDBC 2.0 features in order to use some of the suggestions mentioned in this section. Note2: This Section assumes that reader has some basic knowledge of JDBC. Sequence of steps to get the DataBase connection and finally Resultset? 1.DriverManager.getConnection 2.Datasource.getConnection which are the concrete classes in JDBC api ? DriverManager,Date,Time,TimeStamp,SQLException,SQLWarning.

Detecting Duplicate Keys I have a program that inserts rows in a table. My table has a column 'Name' that has a unique constraint. If the user attempts to insert a duplicate name into the table, I want to display an error message by processing the error code from the database. How can I capture this error code in a Java program? A solution that is perfectly portable to all databases, is to execute a query for checking if that unique value is present before inserting the row. The big advantage is that you can handle your error message in a very simple way, and the obvious downside is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad. Joe Sam Shirah adds: You can also get this information in a portable way, and potentially avoid another database access, by capturing SQLState messages. Some databases get more specific than others, but the general code portion is 23 "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000. For more information, see Where can I find a list of the possible SQLStates returned by SQLException.getSQLState()? and my JDBC 2.0 Fundamentals Short Course at the Java Developer Connection. What are the standard isolation levels defined by JDBC? The values are defined in the class java.sql.Connection and are: TRANSACTION_NONE TRANSACTION_READ_COMMITTED TRANSACTION_READ_UNCOMMITTED TRANSACTION_REPEATABLE_READ TRANSACTION_SERIALIZABLE

Any given database may not support all of these levels. How do you set transaction Isolation levels?

Connection.setTransactionIsolation(int level).

How can I determine the isolation levels supported by my DBMS? Use DatabaseMetaData.supportsTransactionIsolationLevel(int level). How do I insert/update records with some of the columns having NULL value? Use either of the following PreparedStatement methods: public void setNull(int parameterIndex, int sqlType) throws SQLException public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException What are the components of the JDBC URL for Oracle's "thin" driver and how do I use them? Briefly: jdbc:oracle:thin:@hostname:port:oracle-sid

1. in green the Oracle sub-protocol (can be oracle:oci7:@, oracle:oci8:@, 2. 3. 4.

racle:thin:@, etc...) is related on the driver you are unsign and the protocol to communicate with server. in red the network machine name, or its ip address, to locate the server where oracle is running. in blue the port (it is complementary to the address to select the specific oracle service) in magenta the sid, select on which database you want to connect.

example:

jdbc:oracle:thin:@MyOracleHost:1521:MyDB
I've found sometime user/password encoded in the URL. I never used this form, but here's an example:

jdbc:oracle:thin:scott/tiger@MyOracleHost:1521:MyDB
where user=scott and pass=tiger.

How do I create a java.sql.Date object? java.sql.Date descends from java.util.Date, but uses only the year, month and day values. There are two methods to create a Date object. The first uses a Calendar object, setting the year, month and day portions to the desired values. The hour,

minute, second and millisecond values must be set to zero. At that point, Calendar.getTime().getTime() is invoked to get the java.util.Date milliseconds. That value is then passed to a java.sql.Date constructor: Calendar cal = Calendar.getInstance(); // set Date portion to January 1, 1970 cal.set( cal.YEAR, 1970 ); cal.set( cal.MONTH, cal.JANUARY ); cal.set( cal.DATE, 1 ); cal.set( cal.set( cal.set( cal.set( cal.HOUR_OF_DAY, 0 ); cal.MINUTE, 0 ); cal.SECOND, 0 ); cal.MILLISECOND, 0 );

java.sql.Date jsqlD = new java.sql.Date( cal.getTime().getTime() ); Explain differences among java.util.Date, java.sql.Date, java.sql.Time, and java.sql.Timestamp? java.util.Date - class supports both the Date (ie year/month/date etc) and the Time (hour, minute, second, and millisecond) components. java.sql.Date - class supports only the Date (ie year/month/date etc) component. The hours, minutes, seconds and milliseconds of the Time component will be set to zero in the particular time zone with which the instance is associated. java.sql.Time - class supports only Time (ie hour, minute, second, and millisecond) component. The date components should be set to the "zero epoch" value of January 1, 1970 and should not be accessed. java.sql.TimeStamp class supports both Date (ie

How to get current system Date? 1. Calendar cal = Calendar.getInstance(); cal.set( cal.YEAR, cal.get (Calendar.YEAR) ); cal.set( cal.MONTH, cal.get(Calendar.MONTH)); cal.set( cal.DATE, cal.get(Calendar.DATE)); Date currentDate = new Date(cal.getTime().getTime()); System.out.println(currentDate.toString()); 2. java.sql.Date date = new java.sql.Date(new java.util.Date().getTime()); 3. java.sql.Date date = new java.sql.Date(System.currentMilis()); How do I create an updatable ResultSet?

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE ); What's new in JDBC 3.0? Probably the new features of most interest are: Savepoint support Reuse of prepared statements by connection pools Retrieval of auto-generated keys Ability to have multiple open ResultSet objects Ability to make internal updates to the data in Blob and Clob objects Ability to Update columns containing BLOB, CLOB, ARRAY and REF types Both java.sql and javax.sql ( JDBC 2.0 Optional Package ) are expected to be included with J2SE 1.4.

For additional features and complete information, the specification can be downloaded from JDBC API Specifications. How do I convert a java.sql.Timestamp to a java.util.Date? How can I insert multiple rows into a database in a single transaction? //turn off the implicit commit Connection.setAutoCommit(false); //..your insert/update/delete goes here Connection.Commit(); a new transaction is implicitly started. Why does my "if(rs==null)" condition always evaluate to false after executing a query? The driver's executeXXX() methods will always return a ResultSet object unless there was some serious internal problem or error. Therefore the reference to the returned ResultSet is never normally null. The ResultSet can be empty, that is, nothing met the criteria, but the ResultSet object itself still is not null. Instead, the normal way of checking if data was returned is to use the next() method, as if( rs.next() ) or while( rs.next() ), which returns a boolean. For more information, see: ResultSet and the API documentation for java.sql.ResultSet. Can I reuse a Statement or must I create a new one for each query? When using a JDBC compliant driver, you can use the same Statement for any number of queries. However, some older drivers did not always "respect the spec." Also note that a Statement SHOULD automatically close the current ResultSet before executing a new query, so be sure you are done with it before re-querying using the

same Statement. For more information, see: Executing Statements Using Statement Objects.

13.1.1.1

Executing Statements Using Statement Objects

The Statement interface provides three different methods for executing SQL statements: executeQuery, executeUpdate, and execute. The correct method to use is determined by what the SQL statement produces. The method executeQuery is designed for statements that produce a single result set, such as SELECT statements. The method executeUpdate is used to execute INSERT, UPDATE, or DELETE statements and also SQL DDL (Data Definition Language) statements like CREATE TABLE, DROP TABLE, and ALTER TABLE. The effect of an INSERT, UPDATE, or DELETE statement is a modification of one or more columns in zero or more rows in a table. The return value of executeUpdate is an integer (referred to as the update count) that indicates the number of rows that were affected. For statements such as CREATE TABLE or DROP TABLE, which do not operate on rows, the return value of executeUpdate is always zero. The method execute is used to execute statements that return more than one result set, more than one update count, or a combination of the two. Because it is an advanced feature that the majority of programmers will never use, it is explained in its own section later in this overview. All of the methods for executing statements close the calling Statement object's current result set if there is one open. This means that any processing of the current ResultSet object needs to be completed before a Statement object is re-executed. Could we get sample code for retrieving more than one parameter from a stored procedure? Assume we have a stored procedure with this signature: MultiSP (IN I1 INTEGER, OUT O1 INTEGER, INOUT IO1 INTEGER) The code snippet to retrieve the OUT and INOUT parameters follows: CallableStatement cs = connection.prepareCall( "(CALL MultiSP(?, ?, ?))" ); cs.setInt(1, 1); // set the IN parm I1 to 1 cs.setInt(3, 3); // set the INOUT parm IO1 to 3 cs.registerOutParameter(2, Types.INTEGER); // register the OUT parm O1 cs.registerOutParameter(3, Types.INTEGER); // register the INOUT parm IO1 cs.execute(); int iParm2 = cs.getInt(2); int iParm3 = cs.getInt(3); cs.close();

The code really is just additive; be sure that for each IN parameter that setXXX() is called and that for each INOUT and OUT parameter that registerOutParameter() is called.

How can I place a lock on a single row? First, not all databases support row level locks, so check the documentation for your DMBS. If you are using Oracle, you can issue a select...for update statement. Make sure your JDBC connection has autocommit turned off- otherwise, you'll get an ORA01002- "Fetch out of sequence" error. Here's an example: String cmd = "SELECT * FROM my_table WHERE my_column_a = criteria FOR UPDATE OF my_column_b"; ResultSet rset = stmt.executeQuery(cmd); Zac Corbiere adds The important bit is the 'for update' tagged on the end. From your resultset invoke 'rs.getCursorName' and pass that back in to an update statement with 'where current of' like: String updateStmt = "update foo set bar=\"FUBAR\" where current of " + rs.getCursorName(); Will a call to PreparedStatement.executeQuery() always close the ResultSet from the previous executeQuery()? A quote from the Java API docs, java.sql.ResultSet: A ResultSet is automatically closed by the Statement that generated it when that Statement is closed, re-executed, or is used to retrieve the next result from a sequence of multiple results. I think that this should answer your question. It is recommended to retrieve the results into an abitrary datastructure, but be aware that even if in Java parameters are always passed per value; an object variable is a reference (i.e. can be seen as a pointer to an object) and only that reference will be passed per value, but not the object itself. That's a hint for the case that you suddenly get an exception accessing an object you retrieved with myResultSet.getObject(). Ok, when I call a query again the Resultset will be closed and cleared, but, if I call with other resultset, I will lost the result too? Example:

Resultset rs1 = con.executeQuery("SELECT * FROM TABLE1 WHERE ..."); ...; ...; rs1 = con.executeQuery("SELECT * FROM TABLE1 WHERE ..."); ...; Resultset rs2 = con.executeQuery("SELECT * FROM TABLE2"); rs1 will lost its data?

Do I need to commit after an INSERT call in JDBC or does JDBC do it automatically in the DB?

If your autoCommit flag (managed by the Connection.setAutoCommit method) is false, you are required to call the commit() method - and vice versa. What is the advantage of using a PreparedStatement? For SQL statements that are executed repeatedly, using a PreparedStatement object would almost always be faster than using a Statement object. This is because creating a PreparedStatement object by explicitly giving the SQL statement causes the statement to be precompiled within the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement and prepared an execution plan - it simply runs the statement. Typically, PreparedStatement objects are used for SQL statements that take parameters. However, they can also be used with repeatedly executed SQL statements that do not accept parameters. What is the difference between a Statement and a PreparedStatement? Longer answer: Most relational databases handles a JDBC / SQL query in four steps:

1. Parse the incoming SQL query 2. Compile the SQL query 3. Plan/optimize the data acquisition path 4. Execute the optimized query / acquire and return data

A Statement will always proceed through the four steps above for each SQL query sent to the database. A PreparedStatement pre-executes steps (1) - (3) in the execution process above. Thus, when creating a PreparedStatement some preoptimization is performed immediately. The effect is to lessen the load on the database engine at execution time.

Code samples Statement example


// Assume a database connection, conn. Statement stmnt = null; ResultSet rs = null; try { // Create the Statement stmnt = conn.createStatement(); // Execute the query to obtain the ResultSet rs = stmnt.executeQuery("select * from aTable");

} catch(Exception ex) { System.err.println("Database exception: " + ex); } PreparedStatement example // Assume a database connection, conn. PreparedStatement stmnt = null; ResultSet rs = null; try { // Create the PreparedStatement stmnt = conn.prepareStatement("select * from aTable"); // Execute the query to obtain the ResultSet rs = stmnt.executeQuery(); } catch(Exception ex) { System.err.println("Database exception: " + ex); }

Another advantage of the PreparedStatement class is the ability to create an incomplete query and supply parameter values at execution time. This type of query is well suited for filtering queries which may differ in parameter value only:

SELECT firstName FROM employees WHERE salary > 50 SELECT firstName FROM employees WHERE salary > 200
To create a parametrized prepared statement, use the following syntax:

// Assume a database connection, conn. PreparedStatement stmnt = null; ResultSet rs = null; try { // Create the PreparedStatement, leaving a '?' // to indicate placement of a parameter. stmnt = conn.prepareStatement( "SELECT firstName FROM employees WHERE salary > ?");

// Complete the statement stmnt.setInt(1, 200); // Execute the query to obtain the ResultSet rs = stmnt.executeQuery(); } catch(Exception ex) { System.err.println("Database exception: " + ex); }

14 Java Script 15 Servlets :


Which mechanism to choose? HttpSession : There is no limit on the size of the session data kept. The performance is good. This is the preferred way of maintaining state. If we use the HTTP session with the application servers persistence mechanism (server converts the session object into BLOB type and stores it in the Database) then the performance will be moderate to poor. Note: When using HttpSession mechanism you need to take care of the following points: Remove session explicitly when you no longer require it. Set the session timeout value. Your application server may serialize session objects after crossing a certain memory limit. This is expensive and affects performance. So decide carefully what you want to store in a session. Hidden fields : There is no limit on size of the session data. May expose sensitive or private information to others (So not good for sensitive information). The performance is moderate

URL rewriting : There is a limit on the size of the session data. Should not be used for sensitive or private information.

The performance is moderate. Cookies: There is a limit for cookie size. The browser may turn off cookies. The performance is moderate. The benefit of the cookies is that state information can be stored regardless of which server the client talks to and even if all servers go down. Also, if required, state information can be retained across sessions. How do you make a Servlet thread safe? What do you need to be concerned about with storing data in Servlet instance fields? As shown in the figure Servlet Life Cycle in Q11 in Enterprise section, a typical (or default) Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method. The multithreading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner. Having large chunks of code in synchronized blocks in your service methods can adversely affect performance and makes the code more complex. Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure thread safety: Instance pooling where container maintains a pool of servlets. Sequential processing where new requests will wait while the current request is being processed. It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized or used in read-only manner or shared values can be stored in a database table. The single threaded model can adversely affect performance. What is pre-initialization of a Servlet? By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading. The servlet deployment descriptor (web.xml) defines the <load-on-startup> element, which can be configured to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called pre-loading or pre-initializing a servlet. We can also specify the order in which the servlets are initialized. <load-on-startup>2</load-on-startup>

What is a filter, and how does it work? A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses but typically do not themselves create responses. Filters can also be used to transform the response from the Servlet or JSP before sending it back to client. Filters improve reusability by placing recurring tasks in the filter as a reusable unit. A good way to think of Servlet filters is as a chain of steps that a request and response must go through before reaching a Servlet, JSP, or static resource such as an HTML page in a Web application. The filters can be used for caching and compressing content, logging and auditing, image conversions (scaling up or down etc), authenticating incoming requests, XSL transformation of XML content, localization of the request and the response, site hit count etc. The filters are configured through the web.xml file as follows: <web-app> <filter> <filter-name>HitCounterFilter</filter-name> <filter-class>myPkg.HitCounterFilter</filter-class> </filter> <filter-mapping> <filter-name>HitCounterFilter</filter-name> <url-pattern>/usersection/*</url-pattern> </filter-mapping> ... </web-app> The HitCounterFilter will intercept the requests from the URL pattern /usersection followed by any resource name.

Servlet filters use the slightly modified version of the chain of responsibility design pattern. Unlike the classic (only one object in the chain handle the request) chain of responsibility where filters allow multiple objects (filters) in a chain to handle the request. If you want to modify the request or the response in the chain you can use the decorator pattern (Refer Q11 in How would you go about section).

How to do a simple session timeout? In WEB-INF/web.xml , use the following incantation: &lt;webapp&gt; . .

&lt;session-config&gt; &lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;!-- 30 minutes --&gt; &lt;/session-config&gt; . . &lt;/webapp&gt; It's one of the last sub-elements of &lt;webapp&gt;. Check the DTD if you're unsure. When using a dispatcher and calling .forward(), will doGet() or doPost() be called in the target servlet? The RequestDispatcher will call the servlet's service method. If your servlet extends javax.servlet.http.HttpServlet the same 'do' method will be called automatically by the service method, depending on the method used the original request How can I access a configuration and/or log.properties file (stored under WEB-INF) in a web application? place the log.properties and the appconfig.xml file in the WEB-INF/classes directory. (appconfig.xml is the other configuration file I spoke of.) I get the locations as a URL object using the following code: String logFile = getInitParameter("logger"); // or just logFile = "log.properties" URL logurl = this.getClass().getResource("/" + logFile); if(logurl != null) { PropertyConfigurator.configure(logurl); } else { System.out.println("log.properties not found!!"); } I do pretty much the same thing to get my appconfig.xml file read in and parsed. I simply convert the URL into a string format and use that to parse the XML. Can destroy() be called from inside the service() method of my servlet ? destroy() is a servlet life-cycle method called by servlet container to kill the instance of the servlet. The answer to your question is "Yes". You can call destroy() from within the service(). It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't "unload" the servlet instance itself. You do not manage the life cycle of servlets in the program; the servlet engine does. [Alex adds:] On the other hand, if the question is,

"Is it possible that the servlet container will call destroy() while the servlet is still processing a request inside service() on a different thread?" then the answer is also yes, but it's a degenerate case. The servlet container is required to wait a reasonable amount of time for current requests to finish processing. So if your request is not totally lagging, it should work out fine. If you're spending more than a few seconds processing a request, that's a UI problem that you should try to work out first. Check the servlet spec for more details. BTW, destroy() does not imply garbage collection. The instance may live on in memory long after destroy() is called. How do I redirect from a servlet in one context to a servlet in another? Specifically I'd like to know how to share objects between contexts. If you're trying to do a redirection (i.e. response.sendRedirect(String)), it requires an absolute URI (including the context path). If you don't know the context path, you're out of luck. :( If you're trying to forward, you need to get a ServletContext reference pointing to the other context, then get a RequestDispatcher from that other context. Once again, you'll need to know the context path. To get a reference pointing to the other context, just call getContext(String uripath) on the ServletContext reference for your context. The uripath should be a String specifying the context path of another web application in the container. Note, however, that in many cases, you will receive null references--even if you specify a valid context path. In most servlet containers, a context (web application) must explicitly allow other contexts access to its ServletContext . For example, in Tomcat, the crossContext attribute of the Context element of server.xml must be set to true to allow other contexts to access this context. The Servlet specification recommends this behavior for "security conscious" environments. Can we use the constructor, instead of init(), to initialize servlet? No you can't. It's the container who manages the lifecycle of the sevlet not you. Also, you must call super.init() for init() to work properly. Can I have some simple code for my own connection pooling class? public class ConnectionPool { private Connection _connection; public ConnectionPool(Connection connection) { _connection = connection;

} public synchronized Connection getConnection() { while(null == _connection) { try { wait(); } catch (InterruptedException ie) {} } return(_connection); } public synchronized void returnConnection(Connection connection) { if(null != _connection) throw new IllegalStateException(); _connection = connection; notify(); } } This will get you by in a pinch. Code to this interface and then expand the class to include more connections, probably in a "real" data structure like a queue. If you change your implementation but not your interface (except maybe your constructor), you should not have to change any of your servlet What is the difference between using getSession(true) and getSession(false) methods? The difference is as follows: When you say getSession(true), this method will check whether already a session is existing for the user. If a session is existing, it will return that session object, OTHERWISE WILL CREATE A SESSION OBJECT EXPLICITLY AND RETURN TO THE CLIENT. When you say getSession(false), this method will check whether a session is existing. If yes, then it returns the reference of that session object, OTHERWISE IT WILL RETURN 'null'. How can I implement returning part of a large (1000+ rows) result set to the client? Try RowSet. It is pretty fast and provides functionality you outlined above. However, you will never be able to return first n rows "while result set is being loaded." although that is a nice functionality, it would be tremendously hard to implement it in the JDBC driver. you have no control of how data is obtained from the database unless you wrote the JDBC driver yourself. therefore, no luck there. you can try to combine some logic to access first n number of rows from the

database, but request for n+1, n+2... records would require additional queries to the database which can get overly complex. so try RowSets. I am sure that you will be satisfied with the performance and functionality. How do I use a RequestDispatcher to call one servlet from another servlet? To call another servlet you have to use a request dispatcher: RequestDispatcher rd = this.getServletConfig() .getServletContext() .getRequestDispatcher("/path-to-servlet"); rd.forward(); How can I submit an HTTP POST request when the user clicks a normal HREF link? You can post to a servlet using JavaScript through HREF in the following way. Any parameters you need to send can be sent using the "hidden" parameters. <form name="submitForm" method="POST" action="/servlet/ServletName"> <input type="hidden" name="param1" value="param1Value"> <A HREF="javascript:document.submitForm.submit()">Click Me</A> </form> Inside a JSP, how to represent private methods and call them?

[I wrote a servlet, and I want to convert it to a JSP file. Usually it is very simple - all of the code of the "doGet" method directly goes into the JSP. But now I have a private method in that servlet, that the doGet method calls with various arguments. How do I put that in a jsp? ] Use a declaration scriptlet:

<%! private void foo() { System.out.println("foo"); } %> <% foo(); %> How do I get the content (not the name) of an option in a choice box? <form> <select name="dd" onChange="document.forms[0].ddtext.value = document.forms[0].dd[document.forms[0].dd.selectedIndex].text;"> <option value="1">One</option>

<option value="2">Two</option> </select> <input type="hidden" name="ddtext" value=""> </select> </form> What is the ServletConfig object, and why is it useful? The ServletConfig object is an interface. It contains the methods getInitParameter getInitParameterNames getServletContext getServletName You can use the methods to determine the Servlet's initialization parameters, the name of the servlets instance, and a reference to the Servlet Context the servlet is running in. getServletContext is the most valuable method, as it allows you to share information accross an application (context).

I want my servlet page to redirect to a login page if the session has timed out. How can I know if my session has timed out? If the servlet engine does the time-out, following code should help you: //assume you have a HttpServletRequest request if(request.getSession(false)==null) { //no valid session (timeouted=invalid) //code to redirect to login page } What is a Servlet Filter? A filter is basically a component that is invoked whenever a resource is invoked for which the filter is mapped. The resource can be something like a servlet, or a URL pattern. A filter normally works on the request, response, or header attributes, and does not itself send a response to the client.\ What is the difference between ServletContext and ServletConfig? A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object.

This notion of a web application became very significant upon the Servlet 2.1 API, where you could deploy an entire web application in a WAR file. For more specifics on web application, please see this FAQ. Notice that I always said "servlet instance", not servlet. That is because the same servlet can be used in several web applications at one time. In fact, this may be common if there is a generic controller servlet that can be configured at run time for a specific application. Then, you would have several instances of the same servlet running, each possibly having different configurations. This is where the ServletConfig comes in. This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig. What is the difference between response.sendRedirect(), RequestDispatcher.forward(), and PageContext.forward()? In a nutshell, RequestDispatcher.forward() works on the server and response.sendRedirect() works on the browser. When you invoke RequestDispatcher.forward(), the servlet engine transfers control of this HTTP request internally from your current servlet or JSP to another servlet or JSP or static file. When you invoke response.sendRedirect(), this sends an HTTP response to the browser to make another request at a different URL. RequestDispatcher.forward() and PageContext.forward() are effectively the same. PageContext.forward is a helper method that calls the RequestDispatcher method. What is meant by the term "business logic"? Business logic" is just a fancy way of saying "code." :-) More precisely, in a three-tier architecture, business logic is any code that is not specifically related to storing and retrieving data (that's "data storage code"), or to formatting data for display to the user (that's "presentation logic"). It makes sense, for many reasons, to store this business logic in separate objects; the middle tier comprises these objects. However, the divisions between the three layers are often blurry, and business logic is more of an ideal than a reality in most programs. The main point of the term is, you want somewhere to store the logic and "business rules" (another buzzword) of your application, while keeping the division between tiers clear and clean. What is the difference between POST and GET methods? What about PUT, DELETE, TRACE, OPTIONS, and HEAD? GET and POST basically allow information to be sent back to the webserver from a browser (or other HTTP client for that matter). Imagine that you have a form on a HTML page and clicking the "submit" button sends the data in the form back to the server, as "name=value" pairs.

Choosing GET as the "method" will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects! A PUT allows you to "put" (upload) a resource (file) on to a webserver so that it be found under a specified URI. DELETE allows you to delete a resource (file). These are both additions to HTTP/1.1 and are not usually used. HEAD returns just the HTTP headers for a resource. TRACE and OPTIONS are also HTTP/1.1 additions and also rarely used. The Servlet spec allows you to implement separate Java methods implementing each HTTP method in your subclass of HttpServlet. Override the doGet() and/or doPost() method to provide normal servlet functionality. Override doPut() or doDelete() if you want to implement these methods. There's no need to override doOptions() or doTrace(). And the superclass handles the HEAD method all on its own. What are the advantages and disadvantages of the different forms of session tracking (cookies, session objects, hidden fields, URL rewriting)? Here are the advantages and disadvantages I found with them:

Technique Advantages

Cookies

1. simple 2. don't need to send data back to us, browser can participate in this task.

Hidden Fields

1. simple 2. No effect on security level setting in browsers.

Disadvantages 1. size and number of cookies stored are limited. 2. it stored as plain-text in a specific directory, everyone can view and modify them. Personal information is exposed. 3. it won't work if the security level set too high in browser. 1. the documents needs to embedded the data inside, waste bandwidth. e.g., if you have to conduct a web-based survey with multiple pages using hidden fields. You have to embed the result from previous pages in the next page. 2. Everyone can see the embedded data by viewing the original source code. 3. If the user surfs to a different site, or to a static section of the same site, the state is lost.

1. URL is lengthy and the length of the URL is limited, can't store much information. 1. Every data is appended on the URL => 2. The URL contains data. If you URL easy to debug. send this URL to your friends, they Rewriting 2. Works even if users disable cookies might see your information. 3. If the user surfs to a different site, or to a static section of the same site, the state is lost. Session usually use either cookies or URL rewriting (depends on security setting of browser) to make it function. Each user will have its own unique session ID to identify himself. The session data will be Session stored in the server and we can use the Objects : session ID to access these data. The session ID will be sent to user either cookies or URL Rewriting. Since the data are stored in server, the size of data is theoretically unlimited
How do I delete a cookie set by a servlet? Get the cookie from the request object and use setMaxAge(0) and then add the cookie to the response object

16 Web.xml 17 JSP
What are the different scope values or what are the different scope values for <jsp:usebean> ?

Scope Page Request Session Application

Object PageContext Request Session Application

Comment Available to the handling JSP page only. Available to the handling JSP page or Servlet and forwarded JSP page or Servlet. Available to any JSP Page or Servlet within the same session. Available to all the JSP pages and Servlets within the same Web Application.

What are the differences between static and a dynamic include?

Static include <%@ include %> During the translation or compilation phase all the included JSP pages are compiled into a single Servlet.

No run time performance overhead.

Dynamic include <jsp:include ..> The dynamically included JSP is compiled into a separate Servlet. It is a separate resource, which gets to process the request, and the content generated by this resource is included in the JSP response. Has run time performance overhead.

Which one to use: Use static includes when a JSP page does not change very often. For the pages, which change frequently, use dynamic includes. JVM has a 64kb limit on the size of the method and the entire JSP page is rendered as a single method. If a JSP page is greater than 64kb, this probably indicates poor implementation. When this method reaches its limit of 64kb it throws an error. This error can be overcome by splitting the JSP files and including them dynamically (i.e. using <jsp:include.>) because the dynamic includes generate separate JSP Servlet for each included file. Note: The dynamic include (jsp:include) has a flush attribute. This attribute indicates whether the buffer should be flushed before including the new content. In JSP 1.1 you will get an error if you omit this attribute. In JSP 1.2 you can omit this attribute because the flush attribute defaults to false. What are implicit objects and list them? Implicit objects are the objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated Servlet. The implicit objects are:

Implicit object request response pageContext session application out config page exception

Scope Request Page Page Session Application Page Page Page Page

comment request response page environment session same as ServletContext writing to the outputstream same as ServletConfig this pages Servlet exception created on this page.

Note: Care should be taken not to name your objects the same name as the implicit objects. If you have your own object with the same name, then the implicit objects take precedence over your own object.

Is JSP variable declaration thread safe? No. The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated Servlet as an instance variable, not within the body of the _jspservice() method. The following declaration is not thread safe: because these are declarations, and will only be evaluated once when the page is loaded <%! int a = 5 %> The following declaration is thread safe: because the variables declared inside the scriplets have the local scope and not shared. <% int a = 5 %> Q: How do I prevent the output of my JSP or Servlet pages from being cached by the browser? A: You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions. <% response.setHeader("Cache-Control","no-store"); //HTTP 1.1 response.setHeader("Pragma\","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %>

18 Struts
What is a synchronizer token pattern in Struts or how will you protect your Web against multiple submissions? Struts support for synchronisation comes in the form of: ActionServlet.saveToken(HttpRequest) and ActionServlet.isTokenValid(HttpRequest) etc How do you upload a file in Struts? In JSP page set the code as shown below: CO <html:form action="upload.do" enctype="multipart/form-data" name="fileForm" type="FileForm" scope="session"> Please select the file that you would like to upload: <html:file property="file" /> <html:submit /> </html:form>

In the FormBean set the code as shown below: public class FileForm extends ActionForm { private FormFile file; public void setFile(FormFile file){ this.file = file; } public FormFile getFile(){ return file; } }

19 EJB
What is the difference between EJB 1.1 and EJB 2.0? What is the difference between EJB 2.x and EJB 3.0? EJB 2.0 has the following additional advantages over the EJB 1.1: Local interfaces: These are beans that can be used locally, that means by the same Java Virtual Machines, so they do not required to be wrapped like remote beans, and arguments between those interfaces are passed directly by reference instead of by value. This improves performance. ejbHome methods: Entity beans can declare ejbHome methods that perform operations related to the EJB component but that are not specific to a bean instance. Message Driven Beans (MDB): is a completely new enterprise bean type, which is designed specifically to handle incoming JMS messages. New CMP Model. It is based on a new contract called the abstract persistence schema, which will allow to the container to handle the persistence automatically at runtime. EJB Query Language: It is a sql-based language that will allow the new persistence schema to implement and execute finder methods. Lets look at some of the new features on EJB 2.1 Container-managed timer service: The timer service provides coarse-grained, transactional, time-based event notifications to enable enterprise beans to model and manage higher-level business processes. Web service support: EJB 2.1 adds the ability of stateless session beans to implement a Web service endpoint via a Web service endpoint interface. EJB-QL: Enhanced EJB-QL includes support for aggregate functions and ordering of results. Current EJB 2.x model is complex for a variety of reasons: You need to create several component interfaces and implement several unnecessary call-back methods. EJB deployment descriptors are complex and error prone. EJB components are not truly object oriented, as they have restrictions for using inheritance and polymorphism.

EJB modules cannot be tested outside an EJB container and debugging an EJB inside a container is very difficult. Note: EJB 3.0 is taking ease of development very seriously and has adjusted its model to offer the POJO (Plain Old Java Object) persistence and the new O/R mapping model based on Hibernate. In EJB 3.0, all kinds of enterprise beans are just POJOs. EJB 3.0 extensively uses Java annotations, which replaces excessive XML based configuration files and eliminate the need for rigid component model used in EJB 1.x, 2.x. Annotations can be used to define the beans business interface, O/R mapping information, resource references etc. Refer Q18 in Emerging Technologies/Frameworks section.

Explain the difference between the look up of java:comp/env/ejb/MyBean and ejb/MyBean? The logical reference (or alias) java:comp/env/ejb/MyBean is the recommended approach because you cannot guarantee that the physical JNDI location (ejb/MyBean) you specify in your code will be available. Your code will break if the physical location is changed. The deployer will not be able to modify your code. Logical references solve this problem by binding the logical name to the physical name in the application server. The logical names will be declared in the deployment descriptors (web.xml and/or ejb-jar.xml) as follows and these will be mapped to physical JNDI locations in the application server specific deployment descriptors. To look up a JDBC resource from either WEB (web.xml) or EJB (ejb-jar.xml) tier, the deployment descriptor should have the following entry: <resource-ref> <description>The DataSource</description> <res-ref-name>jdbc/MyDataSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> To use it: Context ctx = new InitialContext(); Object ref = ctx.lookup(java:comp/env/jdbc/MyDataSource); To look up EJBs from another EJB or a WEB module, the deployment descriptor should have the following entry: < ejb-ref> <description>myBean</description> <ejb-ref-name>ejb/MyBean</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <ejb-link>Region</ejb-link> <home>com.MyBeanHome</home> <remote>com.MyBean</remote>

</ejb-ref> To use it: Context ctx = new InitialContext(); Object ref = ctx.lookup(java:comp/env/ejb/MyBean);

How does Stateful Session bean store its state ? State will be stored in instance variables.
A stateful session bean have three possible stages in its life cycle, namely: i. does not exists, ii. ready and iii. passive. The state of the bean is to stored in memory when in ready state, while stored in a secondary storage when passivated by calling ejbPassivate method on the bean. When the bean is activated again by calling ejbActivate its state is restored back

What are transactional attributes? EJB transactions are a set of mechanisms and concepts, which insures the integrity and consistency of the database when multiple clients try to read/update the database simultaneously. Transaction attributes are defined at different levels like EJB (or class), a method within a class or segment of a code within a method. The attributes specified for a particular method take precedence over the attributes specified for a particular EJB (or class). Transaction attributes are specified declaratively through EJB deployment descriptors. Unless there is any compelling reason, the declarative approach is recommended over programmatic approach where all the transactions are handled programmatically. With the declarative approach, the EJB container will handle the transactions. Transaction Attributes Required Description Methods executed within a transaction. If client provides a transaction, it is used. If not, a new transaction is generated. Commit at end of method that started the transaction. Which means a method that has Required attribute set, but was called when the transaction has already started will not commit at the method completion. Well suited for EJB session beans. Client of this EJB must create a transaction in which this method operates, otherwise an error will be reported. Well-suited for entity beans. Methods executed within a transaction. If client provides a transaction, it is suspended. If not a new transaction is generated, regardless. Commit at end of method. Transactions are optional. Transactions are not supported. If provided, ignored.

Mandatory

RequiresNew

Supports NotSupported

Never

Code in the EJB responsible for explicit transaction control.

What are isolation levels? Isolation levels provide a degree of control of the effects one transaction can have on another concurrent transaction. Since concurrent effects are determined by the precise ways in which, a particular relational database handles locks and its drivers may handle these locks differently. The semantics of isolation mechanisms based on these are not well defined. Nevertheless, certain defined or approximate properties can be specified as follows: Isolation level TRANSACTION_SERIALIZABLE Description Strongest level of isolation. Places a range lock on the data set, preventing other users from updating or inserting rows into the data set until the transaction is complete. Can produce deadlocks.

TRANSACTION_REPEATABLE_READ

TRANSACTION_READ_COMMITTED

TRANSACTION_READ_UNCOMMITTED

Locks are placed on all data that is used in a query, preventing other users from updating the data, but new phantom recordscan be inserted into the data set by another user and are included in later reads in the current transaction. Can't read uncommitted data by another transaction. Shared locks are held while the data is being read to avoid dirty reads,but the data can be changed before the end of the transaction resulting in non-repeatable reads and phantom records. Can read uncommitted data (dirty read) by another transaction, and non-repeatable reads and phantom recordsare possible. Least restrictive of all isolation levels. No shared locks are issued and no exclusive locks are honoured.

Isolation levels are not part of the EJB specification. They can only be set on the resource manager either explicitly on the Connection (for bean managed persistence) or via the application server specific configuration. The EJB specification indicates that isolation level is part of the Resource Manager. As the transaction isolation level increases, likely performance degradation follows, as additional locks are required to protect data integrity. If the underlying data does not require such a high degree of integrity, the isolation level can be lowered to improve performance. What is a distributed transaction? What is a 2-phase commit? SF TI A 73: A Transaction (Refer Q43 in Enterprise section) is a series of actions performed as a single unit of work in which

either all of the actions performed as a logical unit of work in which, either all of the actions are performed or none of the actions. A transaction is often described by ACID properties (Atomic, Consistent, Isolated and Durable). A distributed transaction is an ACID transaction between two or more independent transactional resources like two separate databases. For the transaction to commit successfully, all of the individual resources must commit successfully. If any of them are unsuccessful, the transaction must rollback in all of the resources. A 2-phase commit is an approach for committing a distributed transaction in 2 phases. Phase 1 is prepare: Each of the resources votes on whether its ready to commit usually by going ahead and persisting the new data but not yet deleting the old data. Phase 2 is committing: If all the resources are ready, they all commit after which old data is deleted and transaction can no longer roll back. 2-phase commit ensures that a distributed transaction can always be committed or always rolled back if one of the databases crashes. The XA specification defines how an application program uses a transaction manager to coordinate distributed transactions across multiple resource managers. Any resource manager that adheres to XA specification can participate in a transaction coordinated by an XAcompliant transaction manager. What is dooming a transaction? A transaction can be doomed by the following method call CO EJBContext.setRollbackOnly(); The above call will force transaction to rollback. The doomed transactions decrease scalability and if a transaction is doomed why perform compute intensive operations? So we can detect a doomed transaction as shown below: CO public void doComputeIntensiveOperation() throws Exception { If ( ejbContext.getRollbackOnly() ) { return; //transaction is doomed so return (why unnecessarily perform compute intensive operation ) } else { performComplexOperation(); } }

20 JMS
What happens to rolled-back messages?

Rolled back messages are re-delivered based on the re-delivery count parameter set on the JMS provider. The re-delivery count parameter is very important because some messages can never be successful and this can eventually crash the system. When a message reaches its redelivery count, the JMS provider can either log the message or forward the message to an error destination. Usually it is not advisable to retry delivering the message soon after it has been rolled-back because the target application might still not be ready. So we can specify a time to re-deliver parameter to delay the re-delivery process by certain amount of time. This time delay allows the JMS provider and the target application to recover to a stable operational condition. Care should be taken not to make use of a single transaction when using the JMS request/response paradigm where a JMS message is sent, followed by the synchronous receipt of a reply to that message. This is because a JMS message is not delivered to its destination until the transaction commits, and the receipt of the reply will never take place within the same transaction. Note: when you perform a JNDI lookup for administered objects like connection factories, topics and/or queues, you should use the logical reference java:comp/env/jms as the environment subcontext. It is also vital to release the JMS resources like connection factories, sessions, queues, topics etc when they are no longer required in a try{} and finally{} block.

21 XML
What is XML? And why is XML important? XML stands for eXtensible Markup Language. XML is a grammatical system for constructing custom markup languages for describing business data, mathematical data, chemical data etc. XML loosely couples disparate applications or systems utilizing JMS, Web services etc. XML uses the same building blocks that HTML does: elements, attributes and values. Lets look at why XML is important. Scalable: Since XML is not in a binary format you can create and edit files with anything and its also easy to debug. XML can be used to efficiently store small amounts of data like configuration files (web.xml, application.xml, struts-config.xml etc) to large company wide data with the help of XML stored in the database. Fast Access: XML documents benefit from their hierarchical structure. Hierarchical structures are generally faster to access because you can drill down to the section you are interested in.

Easy to identify and use: XML not only displays the data but also tells you what kind of data you have. The mark up tags identifies and groups the information so that different information can be identified by different application. Stylability: XML is style-free and whenever different styles of output are required the same XML can be used with different style-sheets (XSL) to produce output in XHTML, PDF, TEXT, another XML format etc. Linkability, in-line useability, universally accepted standard with free/inexpensive tools et What is the difference between a SAX parser and a DOM parser?

SAX parser A SAX (Simple API for XML) parser does not create any internal structure. Instead, it takes the occurrences of components of an input document as events (i.e., event driven), and tells the client what it reads as it reads through the input document. A SAX parser serves the client application always only with pieces of the document at any given time. A SAX parser, however, is much more space efficient in case of a big input document (because it creates no internal structure). What's more, it runs faster and is easier to learn than DOM parser because its API is really simple. But from the functionality point of view, it provides a fewer functions, which means that the users themselves have to take care of more, such as creating their own data structures. Use SAX parser when Input document is too big for available memory. When only a part of the document is to

DOM Parser A DOM (Document Object Model) parser creates a tree structure in memory from an input document and then waits for requests from client.

A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. A DOM parser is rich in functionality. It creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree. But it is space inefficient when the document is huge, and it takes a little bit longer to learn how to work with it.

Use DOM when Your application has to access various parts of the document and using your own structure

be read and we create the data structures of our own. If you use SAX, you are using much less memory and performing much less dynamic memory allocation. SAX Parser example: Xerces, Crimson etc Use JAXP (Java API for XML Parsing) which enables applications to parse and transform XML documents independent of the particular XML parser. Code can be developed with one SAX parser in mind and later on can be changed to another SAX parser without changing the application code.

is just as complicated as the DOM tree. Your application has to change the tree very frequently and data has to be stored for a significant amount of time. DOM Parser example: XercesDOM, SunDOM, OracleDOM etc. Use JAXP (Java API for XML Parsing) which enables applications to parse and transform XML documents independent of the particular XML parser. Code can be developed with one DOM parser in mind and later on can be changed to another DOM parser without changing the application code.

22 WebServices 23 Design Patterns


What is MVC architecture ?
What is a singleton pattern? How do you code it in Java? A singleton is a class that can be instantiated only one time in a JVM per class loader. Repeated calls always return the same instance. Ensures that a class has only one instance, and provide a global point of access. It can be an issue if singleton class gets loaded by multiple class loaders. public class OnlyOne { private static OnlyOne one = new OnlyOne(); private OnlyOne(){ } //private constructor. This class cannot be instantiated from outside. public static OnlyOne getInstance() { return one; } } To use it: //No matter how many times you call, you get the same instance of the object. OnlyOne myOne = OnlyOne.getInstance(); Note: The constructor must be explicitly declared and should have the private access modifier, so that it cannot be instantiated from out side the class. The only way to

instantiate an instance of class OnlyOne is through the getInstance() method with a public access modifier. When to use: Use it when only a single instance of an object is required in memory for a single point of access. For example the following situations require a single point of access, which gets invoked from various parts of the code. Accessing application specific properties through a singleton object, which reads them for the first time from a properties file and subsequent accesses are returned from in-memory objects. Also there could be another piece of code, which periodically synchronizes the in-memory properties when the values get modified in the underlying properties file. This piece of code accesses the in-memory objects through the singleton object (i.e. global point of access). of access). Accessing in-memory object cache or object pool, or non-memory based resource pools like sockets, connections etc through a singleton object (i.e. global point What is the difference between a singleton class and a static class? Static class is one approach to make a class singleton by declaring the class as final so that it cannot be extended and declaring all the methods as static so that you cant create any instance of the class and can call the static methods directly. What is a factory pattern? A Factory method pattern (aka Factory pattern) is a creational pattern. The creational patterns abstract the object instantiation process by hiding how the objects are created and make the system independent of the object creation process. An Abstract factory pattern is one level of abstraction higher than a factory method pattern, which means it returns the factory classes.

What is decorator design pattern ? java.io.* classes use the decorator design pattern. The decorator design pattern attaches responsibilities to objects at runtime. Decorators are more flexible than inheritance because the inheritance attaches responsibility to classes at compile time. The java.io.* classes use the decorator pattern to construct different combinations of behaviour at runtime based on some basic classes. By attaching responsibilities to objects at runtime, you can apply changes to each individual object you want to change. File file = new File(c:/temp);

FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); Decorators decorate an object by enhancing or restricting functionality of an object it decorates. The decorators add or restrict functionality to decorated objects either before or after forwarding the request. At runtime the BufferedInputStream (bis), which is a decorator (aka a wrapper around decorated object), forwards the method call to its decorated object FileInputStream (fis). The bis will apply the additional functionality of buffering around the lower level file (i.e. fis) I/O. Briefly discuss the following patterns Composite view, View helper, Dispatcher view and Service to worker? Or explain J2EE design patterns? Composite View: Creates an aggregate view from atomic sub-views. The Composite View entirely focuses on the View. The View is typically a JSP page, which has the HTML, JSP Tags etc. The JSP display pages mostly have a side bar, header, footer and main content area. These are the subviews of the view. The subviews can be either static or dynamic. The best practice is to have these sub-views as separate JSP pages and include them in the whole view. This will enable reuse of JSP sub-views and improves maintainability by having to change them at one place only. View Helper: When processing logic is embedded inside the controller or view it causes code duplication in all the pages. This causes maintenance problems, as any change to piece of logic has to be done in all the views. In the view helper pattern the view delegates its processing responsibilities to its helper classes. The helper classes JavaBeans: used to compute and store the presentation data and Custom Tags: used for computation of logic and displaying them iteratively complement each other. Benefits Avoids embedding programming logic in the views and facilitates division of labour between Java developers and Web page designers. Service to Worker and Dispatcher View: These two patterns are a combination of Front Controller and View Helper patterns with a dispatcher component. One of the responsibilities of a Front Controller is choosing a view and dispatching the request to an appropriate view. This behaviour can be partitioned into a separate component known as a dispatcher. But these two patterns differ in the way they suggest different division of responsibility among the components Service to Worker Combines the front controller (Refer Q24 in Enterprise section) and dispatcher, with views and view helpers (refer Q25 in Enterprise section) to handle client requests and

dynamically prepares the response. Controllers delegate the content retrieval to the view helpers, which populates the intermediate model content for the view. Dispatcher is responsible for the view management and view navigation. Dispatcher View This pattern is structurally similar to the service to worker but the emphasis is on a different usage pattern. This combines the Front controller and the dispatcher with the view helpers but Controller does not delegate content retrieval to view helpers because this activity is deferred to view processing. Dispatcher is responsible for the view management and view navigation. Design Pattern: JDBC architecture decouples an abstraction from its implementation so that the implementation can vary independent of the abstraction. This is an example of the bridge design pattern. The JDBC API provides the abstraction and the JDBC drivers provide the implementation. New drivers can be plugged-in to the JDBC API without changing the client code. What is a business delegate? Why should you use a business delegate? Problem: When presentation tier components interact directly with the business services components like EJB, the presentation components are vulnerable to changes in the implementation of business services components. Solution: Use a Business Delegate to reduce the coupling between the presentation tier components and the business services tier components. Business Delegate hides the underlying implementation details of the business service, such as look-up and access details of the EJB architecture. Business delegate is responsible for: Invoking session beans in Session Facade. Acting as a service locator and cache home stubs to improve performance. Handling exceptions from the server side. (Unchecked exceptions get wrapped into the remote exception, checked exceptions can be thrown as an application exception or wrapped in the remote exception. unchecked exceptions do not have to be caught but can be caught and should not be used in the method signature.) Re-trying services for the client (For example when using optimistic locking business delegate will retry the

method call when there is a concurrent access.). What is a session faade? Problem: Too many method invocations between the client and the server will lead to network overhead, tight coupling due to dependencies between the client and the server, misuse of server business methods due to fine grained access etc. Solution: Use a session bean as a faade to encapsulate the complexities between the client and the server interactions. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients. Session faade is responsible for Improving performance by minimising fine-grained method calls over the network. Improving manageability by reducing coupling, exposing uniform interface and exposing fewer methods to clients. Managing transaction and security in a centralised manner. What is a value object pattern? Problem: When a client makes a remote call to the server, there will be a process of network call and serialization of data involved for the remote invocation. If you make fine grained calls there will be performance degradation. Solution: Avoid fine-grained method calls by creating a value object, which will help the client, make a coarsegrained call. What is a Service Locator? Problem: J2EE makes use of the JNDI interface to access different resources like JDBC, JMS, EJB etc. The client looks up for these resources through the JNDI look-up. The JNDI look-up is expensive because the client needs to get a network connection to the server first. So this look-up process is expensive and redundant. Solution: To avoid this expensive and redundant process, service objects can be cached when a client performs the JNDI look-up for the first time and reuse that service object from the cache for the subsequent look-ups. The service locator pattern implements this technique. Refer to diagram below: Finally get familiarised with some of the key Java & J2EE design patterns like: 1. MVC design pattern: J2EE uses this design pattern or architecture. 2. Chain of responsibility design pattern: Servlet filters use a slightly modified version of chain of responsibility design pattern. 3. Front controller J2EE design pattern: provides a centralized access point for HTTP request handling to

support the integration system services like security, data validation etc. This is a popular J2EE design pattern. 4. Composite view J2EE design pattern: creates an aggregate view from atomic sub-views. 5. View helper J2EE design pattern: avoids duplication of code. The helper classes are JavaBeans and custom tags (e.g. Struts tags, JSF tags, JSTL tags etc). 6. Service to worker and dispatcher view J2EE design pattern: These two patterns are a combination of front controller and view helper patterns with a dispatcher component. These two patterns differ in the way they suggest different division of responsibility among components. 7. Bridge design pattern: Java Data Base Connectivity (JDBC) uses the bridge design pattern. The JDBC API provides an abstraction and the JDBC drivers provide the implementation. 8. Proxy design pattern: RMI & EJB uses the proxy design pattern. A popular design pattern. 9. Business delegate J2EE design pattern: used to reduce the coupling between the presentation tier and the business services tier components. 10. Session faade J2EE design pattern: too many fine-grained method calls between the client and the server will lead to network overhead and tight coupling. Use a session bean as a faade to provide a coarse-grained service access layer to clients. 11. Value object J2EE design pattern: avoid fine-grained method calls by creating a value object, which will help the client, make a coarse-grained call. 12. Fast-lane reader J2EE design pattern: access the persistence layer directly using a DAO (Data Access Object) pattern instead of using entity beans. 13. Service locator J2EE design pattern: expensive and redundant JNDI lookups can be avoided by caching and reusing the already looked up service objects.

24 ANT 25 UML
What is the difference between aggregation and composition? Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole. For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship. Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part

cannot exist without a whole. If a whole is deleted then all parts are deleted. For example An order is a whole and line items are parts. If an order deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship. What is the difference between a collaboration diagram and a sequence diagram?

26 Log4J 27 Eclipse/NetBeans 28 Weblogic/Websphere/Jboss/Tomcat 29 VSS/CVS

cvsmaptoeclipse.doc

30 Spring 31 Hibernate 32 Java Performance tuning


How would you improve performance of a Java application? Pool valuable system resources like threads, database connections, socket connections etc. Emphasise on reuse of threads from a pool of threads. Creating new threads and discarding them after use can adversely affect performance. Also consider using multi-threading in your single-threaded applications where possible to enhance performance. Optimze the pool sizes based on system and application specifications and requirements. Optimize your I/O operations: use buffering (Refer Q21 in Java section) when writing to and reading from files and/or streams. Avoid writers/readers if you are dealing with only ASCII characters. You can use streams instead, which are faster. Avoid premature flushing of buffers. Also make use of the performance and scalability enhancing features such as non-blocking and asynchronous I/O, mapping of file to memory etc offered by the NIO (New I/O). Minimize network overheads by retrieving several related items simultaneously in one remote invocation if

possible. Remote method invocations involve a network round-trip, marshalling and unmarshalling of parameters, which can cause huge performance problems if the remote interface is poorly designed. (Refer Q125 in Enterprise section). Establish whether you have a potential memory problem and manage your objects efficiently: remove references to the short-lived objects from long-lived objects like Java collections etc (Refer Q64 in Java section) to minimise any potential memory leaks. Also reuse objects where possible. It is cheaper to recycle objects than creating new objects each time. Avoid creating extra objects unnecessarily. For example use mutable StringBuffer/StringBuilder classes instead of immutable String objects in computation expensive loops as discussed in Q17 in Java section. Automatic garbage collection is one of the most highly touted conveniences of Java. However, it comes at a price. Creating and destroying objects occupies a significant chunk of the JVM's time. Wherever possible, you should look for ways to minimise the number of objects created in your code: If repeating code within a loop, avoid creating new objects for each iteration. Create objects before entering the loop (i.e. outside the loop) and reuse them if possible. For complex objects that are used frequently, consider creating a pool of recyclable objects rather than always instantiating new objects. This adds additional burden on the programmer to manage the pool, but in select cases can represent an order of magnitude performance gain. Use lazy initialization when you want to distribute the load of creating large amounts of objects. Use lazy initialization only when there is merit in the design. Where applicable apply the following performance tips in your code: Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc where possible. This is because the methods in ArrayList, HashMap etc are not synchronized (Refer Q13 in Java Section). Even better is to use just arrays where possible. Set the initial capacity of a collection (e.g. ArrayList, HashMap etc) and StringBuffer/StringBuilder appropriately. This is because these classes must grow periodically to accommodate new elements. So, if you have a very large ArrayList or a StringBuffer, and you know the size in advance then you can speed things up by setting the initial size appropriately. (Refer Q15, Q17 in Java Section). Minimise the use of casting or runtime type checking like instanceof in frequently executed methods

or in loops. The casting and instanceof checks for a class marked as final will be faster. Using instanceof construct is not only ugly but also unmaintainable. Look at using visitor pattern (Refer Q11 in How would you go about? section) to avoid instanceof construct. Do not compute constants inside a large loop. Compute them outside the loop. For applets compute it in the init() method. Exception creation can be expensive because it has to create the full stack trace. The stack trace is obviously useful if you are planning to log or display the exception to the user. But if you are using your exception to just control the flow, which is not recommended, then throw an exception, which is precreated. An efficient way to do this is to declare a public static final Exception in your exception class itself. Avoid using System.out.println and use logging frameworks like Log4J etc, which uses I/O buffers (Refer Q21 in Java section). Minimise calls to Date, Calendar, etc related classes. Minimise JNI calls in your code. How would you detect and minimise memory leaks in Java? In Java memory leaks are caused by poor program design where object references are long lived and the garbage collector is unable to reclaim those objects. Detecting memory leaks: Use tools like JProbe, OptimizeIt etc to detect memory leaks. Use operating system process monitors like task manager on NT systems, ps, vmstat, iostat, netstat etc on UNIX systems. Write your own utility class with the help of totalMemory() and freeMemory() methods in the Java Runtime class. Place these calls in your code strategically for pre and post memory recording where you suspect to be causing memory leaks. An even better approach than a utility class is using dynamic proxies (Refer Q11 in How would you go about section) or Aspect Oriented Programming (AOP) for pre and post memory recording where you have the control of activating memory measurement only when needed. (Refer Q3 Q5 in Emerging Technologies/Frameworks section).

33 SQL

Вам также может понравиться