Tuesday, May 31, 2011

XML-SAX

================== ===================================
When to Use SAX
SAX key points 
===================================================== 

SAX event model is used when you want to convert existing data to XML.
ITs an event-driven, serial-access mechanism for accessing XML documents. This protocol is frequently used by servlets and network-oriented programs that need to send and receive XML documents, because it's the fastest and least memory-intensive mechanism that is currently available for dealing with XML documents.


SAX is fast and efficient, and its event model makes it most useful for such state-independent filtering. For example, a SAX parser calls one method in your application when an element tag is encountered and calls a different method when text is found. If the processing you're doing is state-independent (meaning that it does not depend on the elements have come before), then SAX works fine.

SAX requires much less memory than DOM, because SAX does not construct an internal representation (tree structure) of the XML data, as a DOM does. Instead, SAX simply sends data to the application as it is read.

SAX API act like a serial I/O stream. You see the data as it streams in, but you can't go back to an earlier position or leap ahead to a different position. In general, SAX parsers work well when you simply want to read data and have the application act on it.

SAX was developed by the members of the XML-DEV mailing list, and the Java version is now a SourceForge project

SAX has no official standards body; it is not maintained by the World Wide Web Consortium (W3C) or any other official body


Disadvantages:

1) Setting up a program to use SAX requires a bit more work than setting up to use the Document Object Model (DOM).
2) SAX is an event-driven model and that makes it harder to visualize
3) Finally, you can't "back up" to an earlier part of the document, or rearrange it. For those reasons, developers who are writing a user-oriented application that displays an XML document and possibly modifies it will want to use the DOM mechanism

Saturday, May 21, 2011

Java Interview Questions

SQL Injection in java


SQL Interview Questions

======================================
What is sql inject attack
What is sql injeciton
======================================

 This is the way you can pass INVALID or VUNARABLE input parameters to query and retrive information more than expected. This is the way to break the Security of Database lavel. for eg.
 
Suppose you have sql query like statement 
 
 "SELECT * FROM `users` WHERE `name` = '" + userName + "';"
 
    This SQL code is designed to pull up the records of the specified username from its table of users.
You can see here that query is taking parameter dynamically. Here you may use prepared statement. At the run time value of userName variable will be added to query.
If you pass the userName=' or '1'='1 the actual statement will look like
 SELECT * FROM `users` WHERE `name` = '' OR '1'='1';

If this code were to be used in an authentication procedure then this example could be used to force the selection of a valid username because the evaluation of '1'='1' is always true.
The following value of "userName" in the statement below would cause the deletion of the "users" table as well as the selection of all data from the "userinfo" table using an API that allows multiple statements:
 
a';DROP TABLE `users`; SELECT * FROM `userinfo` WHERE 't' = 't

The above scenario which I explained is comes under Incorrectly filtered escape characters scenario
There are following way you can do query injection
1)Incorrectly filtered escape characters
2) Incorrect type handling
3) Conditional responses
4) Parameterized statements etc.

Memory Management in java

Memory management is the process of recognizing when allocated objects are no longer needed, deallocating (freeing) the memory used by such objects, and making it available for subsequent allocations. Garbage collection solves many, but not all, memory allocation problems. You could, for example, create objects indefinitely and continue referencing them until there is no more memory available. Garbage collection is also a complex task taking time and resources of its own.



===========================
When does GarbageCollector will run
What will happen if garbage collector is not able to free memory
===========================
Consider the possibility that the garbage collector may never even run during an application's lifetime. There is no guarantee as to when or if the JVM will invoke the garbage collector -- even if a program explicitly callsSystem.gc(). Typically, the garbage collector won't be automatically run until a program needs more memory than is currently available. At this point, the JVM will first attempt to make more memory available by invoking the garbage collector. If this attempt still doesn't free enough resources, then the JVM will obtain more memory from the operating system until it finally reaches the maximum allowed.
 Garbage Collection Algorithms
1 – Reference Counting:
2 – Tracing Collectors:
3 – Mark-Sweep collectors:
4 – Copying Collectors:
5 – Heap Compaction:
6 – Mark-compact collectors:
JDK uses all of the algorithms in some sense. Early JDK used mark-sweep and mark-compact while version 1.2 and later employed a hybrid approach.
 
An object is created in the heap and is garbage-collected after there are no more references to it. 
The sequence of the garbage collection process is as follows:

1. Root set tracing and figure out objects that are not referenced at all.
2. Put the garbage objects from above in finalizer Q
3. Run finalize() of each of these instances
4. Free memory

The JavaHeap is separated into three regions
1. New Generation objects
2. Old Generation objects
3. Permenent Generation objects
The New Object Regions is subdivided into three smaller regions:
 1. Eden , where objects are allocated
 2. Survivor semi-spaces:  From
3. Survivor semi-spaces:  To
When the Eden area is full, the GC does a reachability test and then copies all the live objects from Eden to the To region. objects get created in New generation and then move to survivor Spaces at every GC run, and if they survive for long to be considered old, they get moved to the Tenured generation
By default, Java has 2 separate  threads for GC, one each for young(minor GC) and old generation(major GC). When ever there is requirment for memory then, first minor GC will runs if it could not release memory, then major Gc thread will run, even it could not release memory then JVM increase heap memory. This cycle run untill current memory reaches the MaxMemory for the JVM (default is 64MB for client JVM), after which JVM throws OutOfMemory Error.

Permanent Generation
Class information is stored in the perm generation. Also constant strings are stored there. Strings created dynamically in your application with String.intern() will also be stored in the perm generation.Reflective objects (classes, methods, etc.) are stored in perm. It holds all of the reflective data for the JVM

Tuesday, May 10, 2011

Difference between Compareble and Comparator interface

What is difference between Comparable and Comparator interface
1)
Comparable interface is in java.lang package
Comparator interface is in java.util package
================================
2)
int compareTo(Object o1) method takes input as only object
int compare(Object o1, Objecto2) method takes input as 2 object
================================
3)
java.lang.Comparable: int compareTo(Object inuptObject1)
This method compares this object with inputObject1. Returned int value has the following meanings.

   1. positive (this) object is greater than inuptObject1
   2. zero     (this) object equals to inuptObject1
   3. negative (this) object is less than inuptObject1


java.util.Comparator: int compare(Object object1, Object object2)
This method compares object1 and object2 objects. Returned int value has the following meanings.

   1. positive  object1 is greater than object2
   2. zero      object1 equals to object2
   3. negative  object1 is less than object2

===============================================
===============================================
Why do we need tow interface for object comparison?
Ans With Comparable you can not add comparison by custom attribute. or more specific you can not sort or  compare object with more than  one attribute.

Sunday, May 8, 2011

equals and hashCode method key points


equals and hashCode method key points

The Java super class java.lang.Object has two very important methods defined in it. They are -

    * public boolean equals(Object obj)
    * public int hashCode()

public boolean equals(Object obj)
This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked. The default implementation of this method in Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison".


public int hashCode()
This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet

if tow object are NOT equls as per equlas(object) method, then they still may have same hashCode, i.e.
unequal objects need not produce distinct hash codes.
Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

When we override equals mthod we have to consider following points
1) Compare objects with (this == obj)
    a)Cheking with "==" will check if both the object has same heap memory reference, then its equals
    b) This will save time as equlas(object) method is cpu expensive

2) Compare the argument with null, if input object is null then return false
    if((obj == null) || (obj.getClass() != this.getClass())) return false; // prefer
    dont use instanceOf operator if(!(obj instanceof Test)) return false; // avoid
    as Test class may have child that will return true here

3) Compare the object with equlas(object) method
4) Implement hashcode method

================================================== 
if I override equlas method and dont implement hashCode then was potential problme will I face
==================================================
Whenever you override the equals method, you must override the hashCode method as well. If you dont do so then it, results in undetermined, undesired behavior of the class when confronted with Java hash based collection classes or any other Java classes. When you insert object to HashMap or HashTable it will give you unpredictable result.

Object which is not implementing hashcode(), and if you use that object as a key, then you have to use same object  which you have use while giving call to put(). Then only you will get expected value for the key, else it will return null. The object which you will use for put() and get() must be same else error prone result.