Thursday, May 12, 2011

What are the differences between SAX and DOM parser.


SAX DOM
Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.
Parses node by node Stores the entire XML document into memory before processing
Doesn’t store the XML in memory Occupies more memory
We cant insert or delete a node We can insert or delete nodes
Top to bottom traversing Traverse in any direction.
SAX is an event based parser DOM is a tree model parser
SAX is a Simple API for XML Document Object Model (DOM) API
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
 
doesn’t preserve comments preserves comments
SAX generally runs a little faster than DOM SAX generally runs a little faster than DOM
If we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Interview Question


JSP Interview Question


1.      After hitting submit button, a JSP page processes a database transaction. You have accidentally closed the browser window. Will the database transaction continue or will get over?
2.      What is the difference between http GET and POST methods ?
3.      There are 10 servlets in your web application, and they are frequently used (sticky Servlet). How will you optimize their loading?
4.      How will you communicate across Servlets? (or, how will you achieve Inter Servlet communication?)
5.      Hope, you know the difference between RequestDispatcher.forward() and RequestDispatcher.sendRedirect(). So, which one is desirable to use?
6.      What is the class path hierarchy for a Servlet?
7.      You can’t read files (located out of tomcat directory) from JSP and Servlets for security purpose. But, how will you access those files from JSP or Servlets, in case if you need them?
Answers:
The database transaction will still continue; Because a Servlet thread was created when you hit the JSP page and that runs the database transaction. Closing the browser window will not kill the Servlet thread.
a) GET method passes the form fields as part of URL, but POST method wraps or encrypts the form fields in request data; b) Also, you can pass only 255 characters to the action page with GET method.
Add <load-on-startup> tag to the Servlet in web.xml. This will load your Servlet on startup, and doXXX() method will be ready for any further requests.
Use RequestDispatcher.forward() and RequestDispatcher.include();
RequestDispatcher.sendRedirect() is desirable. Because, forward() can’t work across different JVM.
First, lookup in WEB-INF/classes, then WEB-INF/lib then from tomcat’s central library folder (<tomcat-home>/lib)
Any class from WEB-INF/classes or WEB-INF/lib can access files. So, use those classes to do the job for your JSP and Servlets.

Design Pattern:

1.      How will you design your Singleton Patten class to be thread-safe? (a standard interview question!)
2.      What Design Pattern can be used for classical Producer Consumer problem? (a simple question)
3.      M.S Word can store million lines of text. Each character in the text will have set of properties like font-color, font-size, font-style and etc. So, M.S Word application has to maintain a property structure for each and every character and that may lead to heavy storage. What design pattern will you apply to overcome this problem?
4.      Your application uses 1000 classes and they have interaction among each other. This will lead to complex communication across objects, so what design pattern can solve this problem?
5.      An application reads input from various clients in multiple stages and creates a binary tree structure out of all received inputs. Which design pattern can be used to design such application?
6.      You have to design a budget management application for global users. But, have to provide an option to configure their native tax rules. Which design pattern, do you think, can solve this?
7.      You have a core application class. But, you have to be able assign extra functionalities to the core class on the fly (at runtime). Which patterns deserves this purpose?

1. ANSWER: Adding synchronized keyword tothe getSingleton() method is inefficient solution. Initialize the static private Singleton object within Synchronized block. In this way you can achieve it.
2.ANSWER: Use observer pattern (publisher subscriber model)
3. ANSWER: You have to create property group for each possible styles (font-size, font-color, font-face & etc). So, common characters will be part of a property group, there by reducing the storage of each character. This is called FlyWeight Pattern.
4. ANSWER: Use Mediator pattern to separate the direct communication across objects.
5. ANSWER: Building an object in multiple set - you call it Builder pattern! The realworld example is XSDBuilder class in Java.
6. ANSWER: Use Template Pattern. It provides templates of methods and allowing you to override certain portion of logic.
7. ANSWER: Decorator Pattern. This is similar to the pattern designed for java.io.* classes(BufferedReader, DataInputStream and etc.)

Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency
26/06/2010
These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.
Association
Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.
http://javapapers.com/wp-content/uploads/2010/06/association.jpg
Example: A Student and a Faculty are having an association.
Aggregation
Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.
http://javapapers.com/wp-content/uploads/2010/06/aggregation.jpg
Composition
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
http://javapapers.com/wp-content/uploads/2010/06/composition.jpg
Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.
Difference between aggregation and composition
Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!
Abstraction
Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.
Generalization
Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.
http://javapapers.com/wp-content/uploads/2010/06/generalization.jpg
Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.
Realization
Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.
http://javapapers.com/wp-content/uploads/2010/06/realization.jpg
Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.
Dependency
Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.
http://javapapers.com/wp-content/uploads/2010/06/dependency.jpg
Example: Relationship between shape and circle is dependency.


Tuesday, May 10, 2011

Threads In JAVA.............

QUESTIONS
1. Write a Java program to create three threads namely A, B, C and make them run one after another. (C has to run after B completes, B has to run after A completes).
2. What happens when a thread calls notify() but no thread(s) is waiting?
3. How will you declare a timer variable that will be accessed by multiple threads very frequently?
4. How will you synchronize static variables?
5. What happens when threads are waiting, but never being notified?
ANSWERS:
1. Many ways to do it. I prefer join(). When a thrad A calls b.join(), then A runs only after thread b completes. So, for this problem, C has to call b.join() and B has to call a.join()
2. Actually…, nothing :) the notify() call simply returns.
3. Declare the variable as volatile. Every thread caches a copy of instance variable, work with local copy, and then sync it with master copy. But, threads do not cache a copy of volatile instance variable.
4. Obtain class level lock. synchronized( obj.getClass()) {……..}
5. Leaving the answer to readers! :)

serialVersionUID


Give the use and an example of the scenario where you would use serialVersionUID in a your Java class?

Ans) During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass’s computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.
Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:
•Add fields
•Change a field from static to non-static
•Change a field from transient to non-transient
•Add classes to the object tree
List of incompatible changes:
•Delete fields
•Change class hierarchy
•Change non-static to static
•Change non-transient to transient
•Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.
If we explicitly metion the suid using the statement:
private final static long serialVersionUID =
then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Java Collections API Interview Questions

1. You need to insert huge amount of objects and randomly delete them one by one. Which Collection data structure is best pet?
2. What goes wrong if the HashMap key has same hashCode value?
3. If hashCode() method is overridden but equals() is not, for the class ‘A’, then what may go wrong if you use this class as a key in HashMap?
4. How will you remove duplicate element from a List?
5. How will you synchronize a Collection class dynamically?
ANSWERS:

1. Obviously, LinkedList.
2. It leads to ‘Collision’ wherein all the values are stored in same bucket. Hence, the searching time increases quad radically.
3. Left to Readers.
4. Add the List elements to Set. Duplicates will be removed.
5. Use the utility method 
REference :http://excusemeworld.com/java-j2ee-interview-questions/java-collections-api-interview-questions/

Monday, May 9, 2011

Tuesday, May 3, 2011

What is ConcurrentHashMap-identityHashMap-WeakHashMap ?

Q) What is ConcurrentHashMap?
Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

Q) What is identityHashMap?
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.
Q) What is WeakHashMap?
Ans) A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.

Soft references act like a data cache. When system memory is low, the garbage collector can arbitrarily free an object whose only reference is a soft reference. In other words, if there are no strong references to an object, that object is a candidate for release. The garbage collector is required to release any soft references before throwing an OutOfMemoryException.

Weak references are weaker than soft references. If the only references to an object are weak references, the garbage collector can reclaim the memory used by an object at any time. There is no requirement for a low memory situation. Typically, memory used by the object is reclaimed in the next pass of the garbage collector.
 

Difference between ArrayList, LinkedList and Vector



  • ArrayList is in most cases what you want to use. It is a list backed by an array, which means it has fast access to each element via the get method.




  • Vector is a leftover from the early days of Java, retrofitted with the List interface. The chief difference from ArrayList is that its methods are synchronized (ArrayList's are not). That means it is easier to use in multi-threaded environments, but it does incur the synchronization overhead.




  • LinkedList is backed by a doubly-linked list, not an array. That means it's fast to access elements at the start and the end of the list, but less so in the middle. On the other hand, inserting and deleting elements is fast compared to ArrayList






  • When to use ArrayList or LinkedList ?
    Ans)  Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list. 
    Source : Read More - from java.sun

    ArrayList

    Now for some implementation notes. The ArrayList is actually encapsulating an actualy Array, an Object[]. When you instanciate ArrayList, an array is created, and when you add values into it, the array changes its size accordingly. This gives you strengths and weaknesses:
    • Fast Random Access
    • You can perform random access without fearing for performence. Calling get(int) will just access the underlying array.
    • Adding values might be slow When you don’t know the amount of values the array will contain when you create it, a lot of shifting is going to be done in the memory space when the ArrayList manipulates its internal array.
    • Slow manipulation When you’ll want to add a value randomly inside the array, between two already existing values, the array will have to start moving all the values one spot to the right in order to let that happen.

    LinkedList

    The LinkedList is implemented using nodes linked to each other. Each node contains a previous node link, next node link, and value, which contains the actual data. When new data is inserted, a node is inserted and the links of the surrounding nodes are updated accordingly. When one is removed, the same happens – The surrounding nodes are changing their links and the deleted node is garbage collected. This, as well, gives strengths and weaknesses:
    • Fast manipulation As you’d expect, adding and removing new data anywhere in the list is instantanious. Change two links, and you have a new value anywhere you want it.
    • No random access Even though the get(int) is still there, it now just iterates the list until it reaches the index you specified. It has some optimizations in order to do that, but that’s basically it.

    Some Conclusions

    ArrayList is very useful when a well defined set of data is needed in a List interface as opposed to an array. It can be dynamically changed, but try not to do so frequently throughout the life of the application. LinkedList is there for you to do just that: Manipulating it is very easy, and as long as its used for iteration purposes only and not for random accessing, it’s the best solution. Further, if you need random accessing from time to time, I suggest toArray for that specific moment.
    Another point I didn’t raise here is the Queue issue. LinkedList implements extended abilities to the normal List interface which allows it to add and remove elements from its beginning and end. This makes the LinkedList perfect for Queue and Stack purposes – Although in Java 5 they already added a Stack class.
    Hope this helped someone. Tell me if you want to differ.

     

    How to Print your Blogger Posts?

    How to Print your Blogger Posts

    To notify your readers that your posts can be printed effectively, you'll probably want to add a "Print" link beneath each of your Blogger posts.

    Follow steps

    1. Log in Blogger Dashboard

    2. Click Design --> edit HTML --> click "expand widget templates" and search for this tag </head>

    3. Immedietly before this line, add the following lines of code:
    <style media='print' type='text/css'>
    #header-wrapper, #header, .header, #sidebar-wrapper, .sidebar, #footer-wrapper, #footer, .date-header, .post-meta-data, .comment-link, .comment-footer, #blog-pager, #backlinks-container, #navbar-section, .subscribe_notice, .noprint {display: none;}
    #main-wrapper {width: 95%}
    </style>

    4. Now search for this code:
    <p><data:post.body/></p>

    5. Immediately after this line, paste following lines of code:
    <b:if cond='data:blog.pageType == &quot;item&quot;'>
    <a href='javascript:window.print()'>Print this post</a>
    </b:if>

    6. Save Template.

    How do you swap two variables in JAVA without using a third one bu using bitwise operator ?


    Answer:
    /*Program to swap 2 values without using the temporary variable and Arithmetic operators*/

    class Swap
    {
    public static void main(String args[])
    {
    int a=1;
    int b=2;
    System.out.println("Before swap: a="+a+"b="+b);
    a=a^b;
    b=a^b;
    a=a^b;
    System.out.println(" After swap: a="+a+"b="+b);
    }
    }

    Another Method

    class Swap
    {

    • public static void Swap()

    • {

    • int num1 = 10;

    • int num2 = 20;

    • System.out.println("Before Swapping");

    • System.out.println("Value of num1 is :" + num1);

    • System.out.println("Value of num2 is :" +num2);

    • //add both the numbers and assign it to first

    • num1 = num1 + num2;

    • num2 = num1 - num2;

    • num1 = num1 - num2;

    • System.out.println("Before Swapping");

    • System.out.println("Value of num1 is :" + num1);

    • System.out.println("Value of num2 is :" +num2);
    • }
    • }
    •