Friday, July 30, 2010

Comparison of Struts 1 and Struts 2

Let us see the basic difference between Struts 1 and 2 framework.

  1. Unlike Struts 1, Struts 2 does not need to implement Action class. The Action in Struts 2 is a POJO object. Thus making it easy to unit test the code.
  2. Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
  3. Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation.
  4. Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties.
  5. Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called “Object Graph Notation Language” (OGNL).
  6. Struts 1 uses the standard JSP mechanism for binding objects into the page context for access. Struts 2 uses a “ValueStack” technology so that the taglibs can access values without coupling your view to the object type it is rendering.
  7. Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle. Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.

Thursday, July 29, 2010

PREVIEW_JAVA_J2EE_BOOK

http://www.lulu.com/items/volume_9/192000/192463/3/preview/PREVIEW_JAVA_J2EE_BOOK.pdf

equals and hashCode

The hashcode method is inherited from the Object class. The signature of hashcode is
public int hashCode()

Generally a hashcode value will be the memory address of the object. You can demonstrate this to yourself quite easily with some trivial code such as.

public class ShowHash{
public static void main(String argv[]){
ShowHash sh = new ShowHash();
System.out.println(sh.hashCode());
}
}

When I compiled and ran this code I got an output of : 7474923
Which is a representation of the memory address of that class on that run of the program.

equals and hashCode

Every object has access to an equals method because it is inherited from the Object. However this default object does not always do anything useful as by default it simply compares the memory address of the object. To make the objects equal on your semantics, you need to override this method. Let us assume that If the String class did not implement its own version of the equals method comparing two Strings would compare the memory address rather than the character sequence. This is rarely what you would want, and for this reason the String class implements it's own version of the equals method that makes a character by character comparison.

Here is another of the points from the API documentation
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

This principle is illustrated with the following code,

public class CompStrings{
public static void main(String argv[]){
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
System.out.println(i1.hashCode());
System.out.println(i2.hashCode());
}
}

This code will print out the same hashCode value for s1 and s2 and i1 and i2 on each run of the program. Objects that are equal according to the equals method must return the same hashCode value.
What if I ask otherwise . if objects have same hashcode are they equal ?

Not necessarily... inverse is not true. If two objects are not equal according to equals, they are not required to return different hashCode values.

"The summary is if two things are equal (according to equal()), they must have the same hashCode".

One more thing you must keep in mind is if you override anyone of these you should be overridding the other also.

The hashcode is of particular use with the hash based Collection classes like HashTable, HashSet, HashMap etc ... The nature of hash based collections is to store keys and values. The key is what you use to look up a value.

Illusteration : How Hashtable works.

  • Hash table implementations uses the hash code value to quickly get to the memory location where an object is stored as a key in a hash table. It is not necessary that hashCode() return a unique integer for an object. If two objects return the same hash code, equals() method is used to pick the one the hash table is looking for.

  • So, what does happen when two unequal objects return the same hash code? When Java goes to put objectA as a key and some other object as its value in a hash table using myHashtable.put(objectA, someValue), it first goes to the location indicated by objectA's hash code. If there is already an object there - may be because objectB has been stored there as a key previously, Java checks to see if objectA.equals(objectB). If yes, it replaces the value of key objectB with "soemValue". If no, Java puts objectA and someValue at a different location and creates a link from objectB to objectA. Next time Java needs to get the value of a key, say objectA, from the hash table, it goes to the location indicated by the hash code of the key object. Finding two objects there, it checks if the first object (objectB) equals the object in hand (objectA). If yes, it returns the value for the first object. If no, it goes down the link and checks if the second object (objectA) equals the object in hand (objectA). If yes, it returns the value of the second object. And so on.

  • When two unequal objects return the same hash code, it is called a "collision". It sounds dreadful and you would think some damage occurred. But no, nothing bad happened and you don't need any collision insurance. It just slows down the process of storing and retrieving those objects a bit. From JDK documentation: "Note that the hash table is open: in the case a "hash collision", a single bucket stores multiple entries, which must be searched sequentially." It will be nice if all objects returned unique hash codes. But in real life, it is not so. After all, a hash code can return a maximum of 2 billion or so combinations (maximum Java integer value) where as you can have infinite number of objects. Some of them will necessarily return the same hash code. Collisions are inevitable.

  • From JDK documentation: "An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the capacity is roughly doubled by calling the rehash method."

    "As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur."
  • Servlet interview questions

    This summary is not available. Please click here to view the post.

    Wednesday, July 28, 2010

    SCJP Mack exams URLs

    1. http://scjptest.com/mock-test.xhtml?execution=e1s2

    2 . http://www.javabeat.net/javabeat/scjp5/mocks/

    3) http://j2eefolks.blogspot.com/2008/07/java-5-jconsole-is-visulavm-in-java-60.html

    http://sureshjavablog.blogspot.com/2009/08/java-enums-five-minute-discussion.html

    http://www.javaprepare.com/quests/test.html

    http://www.jchq.net/mockexams/exam1.htm


    http://www.developersbook.com/struts/interview-questions/struts-interview-questions-faqs.php(IMP struts questions)

    Why we need to serialize the object

    For an example,if you are suppose to send some data from
    obe JVM to other JVM, in that case state of ojects are not
    known and will not persist if you dont serialize the object
    and sent over a network.

    because you allocate seperate heap for seperate JVM.

    So you have to tell JAVA that please treat my object, in a
    different way because i have make them serialised...

    Once the data(object) is serialised, you cant send it any
    wr like, write in to DB,othere JVM,files etc. and later
    point of time you can deserialise them and you can the same
    state of the object.


    Serialization is the process of saving the state of an object
    by converting it to a stream of bytes.the main purpose of serialize
    the object is to save the state of an object in order to have the
    ability to recreate the same object when required.

    if you don't serialize and send ur data over the network
    there may be loss of data.
    say for example if you declare your variable as a transient


    and sent over network you will loose the data.

    Can an Interface have an inner class?

    Yes.
     public interface abc
    {
    static int i=0; void dd();
    class a1
    {
    a1()
    {
    int j;
    System.out.println("inside");
    };
    public static void main(String a1[])
    {
    System.out.println("in interfia");
    }
    }
    }

    what is the difference between sleep() and Wait()?

    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.

    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.



    thread.sleep(2000) - this will block the thread exactly 2000
    milliseconds.

    thread.wait(2000) - this will block the thread upto 2000
    milliseconds.

    i.e if thread.notify() calls before 2000 milliseconds, the
    thread will become active incase if the thread is blocked by
    wait().

    for java io streams

    http://tutorials.jenkov.com/java-io/io-exception-handling.html

    Can we write a java program with out a main() method?

    Yes. You can write in a static block what ever you want to execute.
    for ex: public class myclass{
    static {
    S.o.p("my class without main() method ");
    System.exit(0);

    }
    }
    now you can execute the above class and it will print the above output.
    note that the line System.exit(0) is necessary , otherwise it will throws an exception that no main() method is found

    Java Abstract Class vs. Interface: which one to use?

    When to use an abstract class?

    1) If you want to declare some sensitive data use abstract class

    2) If you want to provide common implementation to all the subclasses then use an abstract class

    3) If you want to be free to add new public methods in the future,then use abstract class

    4) If you have to provide some default implementation(impl) and others should not use your impl.(should have thier own) except in some rare cases, then use abstract classes

    5) Accessing a method may be a bit faster (may not be) when compared to interfaces


    Note:1) We can declare a class as abstract without having any of its methods as abstract.The compiler will still accepts it.

    2) "abtract" modifier can be applied to toplevel and nested classes.

    3) A class implementing an interface can it self be declared as abstract.



    When to use an interface?

    1) If you want to start implementation from the scratch and your impl. and other's impl. may not be same then use intrefaces

    2) If all the future implementations should share the method signatures, then use an interface

    3) If you want to make some API and if you are sure that the API lives long in future, then use an interface

    4) If you want to provide the implementing classes the opportunity to inherit from other sources at the same time, then use an interface

    5) If your implementation changes frequently , then use an interface

    6) Accessing a method may be a bit slow, when compared to an abstract class , since an extra redirection is needed to get the actual method from the class which the interface is referring to.


    Note:1) Even though we do not specify the fields of an intreface as final or static or public in their declaration , by default compiler treats them as public + static + final.

    2) Even though we dont specify an interface method declaration as public or abstract in the declaration, by default the compiler treats then as public + abstract. So be careful while overriding them in the subclasses.

    3) Interface methods must not be static or final or strictfp or native.

    4) Interfaces can also be nested as in case of classes.

    5) Interfaces body declaraations can be empty.
    for ex: public interface myinterface{
    }
    These type of interfaces are called marker types, indicating that they possesses certain properties or behaviour for ex: java.lang.Cloneble,java.io.Serilizable

    The Java serialization algorithm revealed

    This link clearly explains what is serialization and why it is required
    http://www.javaworld.com/community/node/2915

    Tuesday, July 27, 2010

    What is the difference between hibernate and jdbc ?

    There are so many

    1) Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc.

    In case of JDBC query must be data base specific.

    2) As Hibernate is set of Objects , you don?t need to learn SQL language.

    You can treat TABLE as a Object . Only Java knowledge is need.

    In case of JDBC you need to learn SQL.

    3) Don?t need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.

    In case of JDBC you need to tune your queries.

    4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.

    In case of JDBC you need to implement your java cache .

    5) Hibernate supports Query cache and It will provide the statistics about your query and database status.

    JDBC Not provides any statistics.

    6) Development fast in case of Hibernate because you don?t need to write queries

    7) No need to create any connection pool in case of Hibernate. You can use c3p0.

    In case of JDBC you need to write your own connection pool

    8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.

    9) You can load your objects on start up using lazy=false in case of Hibernate.

    JDBC Don?t have such support.



    10 ) Hibernate Supports automatic versioning of rows but JDBC Not.

    The information you are posting should be related to java and ORACLE technology. Not political.

    what is lazy fetching in hibernate?

    Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.Lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.Exampleslazy=true (default)Address child of User class can be made lazy if it is not required frequently.lazy=falseBut you may need to load the Author object for Book parent whenever you deal with the book for online bookshop

    Monday, July 26, 2010

    Implementing Singletons

    There are a few ways to implement Singletons. Although you can get Singleton-like behavior with static fields and methods [for example, java.lang.Math.sin(double)], you gain more flexibility by creating an instance. With Singletons implemented as single instances instead of static class members, you can initialize the Singleton lazily, creating it only when it is first used. Likewise, with a Singleton implemented as single instance, you leave open the possibility of altering the class to create more instances in the future. With some implementations of the Singleton, you allow writers of subclasses to override methods polymorphically, something not possible with static methods.

    Most commonly, you implement a Singleton in Java by having a single instance of the class as a static field. You can create that instance at class-loading time by assigning a newly created object to the static field in the field declaration, as seen in Listing 1.

    Listing 1
    public class MySingleton {
    private static MySingleton _instance =
    new MySingleton();

    private MySingleton() {
    // construct object . . .
    }

    public static MySingleton getInstance() {
    return _instance;
    }

    // Remainder of class definition . . .

    Alternatively, you can instantiate it lazily, on first demand, as seen in Listing 2. You keep the constructor private to prevent instantiation by outside callers.

    Listing 2
    public class MySingleton {
    private static MySingleton _instance;

    private MySingleton() {
    // construct object . . .
    }

    // For lazy initialization
    public static synchronized MySingleton getInstance() {
    if (_instance==null) {
    _instance = new MySingleton();
    }
    return _instance;
    }
    // Remainder of class definition . . .
    }

    Both Singleton implementations do not allow convenient subclassing, since getInstance(), being static, cannot be overridden polymorphically. Other implementations prove more flexible. While I don't have the space to describe alternative implementations in detail, here are a couple of possibilities:

    Creational Patterns

    - Factory Pattern


    Factory of what? Of classes. In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.

    When to use a Factory Pattern?
    The Factory patterns can be used in following cases:
    1. When a class does not know which class of objects it must create.
    2. A class specifies its sub-classes to specify which objects to create.
    3. In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.



    Abstract Factory Pattern


    This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes.


    When to use Abstract Factory Pattern?
    One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.


    Singleton Pattern:



    Difference between static class and static method approaches:
    One question which a lot of people have been asking me. What’s the difference between a singleton class and a static class? The answer is static class is one approach to make a class “Singleton”.

    We can create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any instance of class and can call the static methods directly.








    Monday, July 19, 2010

    Object Serialization And De-Serialization In Java

    Implementing serialization in Java is pretty straight forward just a little step task. The class you want to be serialized just have to implements a marker Interface Serializable no override nothing extra work.

    The JVM will take care of serialization and deserialization process automatically. Now you can write your object to any persistent technology e.g. database, file system or even over the network.

    Serialization: The process of writing bits and bytes of a java object to physical stream.

    Deserialization: The process of reading bits and bytes from physical stream to construct a java object.

    Implementing serialization straight forward or lightly may cause problems in future. Let’s discuss some issues that can be faces.

    If you not implement serialVersionUID, when you are saving the object JVM automatically calculate serialVersionUID depending upon the various class factors. So when deserialization reading object back it again calculate the serialVersionUID of the persistent object and to whom class it going to referenced. If class structure changed after saving object then a ClassCastException will be thrown.

    JVM takes significant time to generate serialVersionUID at runtime, so having serialVersionUID generated will also improve the performance.

    So always be sure to have serialVersionUID, follow the guidelines to implement serialVersionUID.

    • Always include it as field, “private static final long serialVersionUID = 1L”, include this field even in the first version of the class, as a reminder of its important.
    • Do not alter the value of this field in future versions, unless you are knowingly making changes to the class which will result in incompatible with all old serialized objects.
    • In Windows, generate serialVersionUID using JDK’s graphical tool like so: issue the like following
      serialver –show persistentClassName/Path
    • Most of modern IDEs can generate serialVersionUID, like in My Eclipse if you are implement Serializable interface, it will show a bulb sign clicking on it will indicate to generate serialVersionUID automatically by the IDE.