Tuesday, October 15, 2013

Java Quiz - 7

1)What is a java bean? What is an enterprise bean?What is the difference?
*java beans are local components  * Ejbs are distributed components
*java beans can be a UI Component as well as no UI  * Ejbs are server side components
*java beans can be serialized and it has setters and getter. * Its not the case with ejb.

2)What is entity bean?How do you write an Entity Bean?
Entity bean is referred  as data . There are 2 types of entity bean,
*Container managed Persistence : Container takes care of persisting the data into the database.
*Bean Managed Persistence : we need to write the code to persist the data into the database.
Bean represents a business entity. Entity bean should be persistent, i.e its state should be persisted in database even though the  server shuts down.
Eg. CreditcardBean
CreditCardVerificationBean is a session bean because it doesnt contain only data but also methods to talk to the databse.

3)What is public static void main?
It has to be called from the jvm, so the main method should be public since it should be visible from outside, also class loader uses the object of classloader and loads the class with the main() method first , jvm never uses the object of the class to call the main() method, so it has to be static. and since it never returns any value it has to be void.
If you write any other main() method signature, it is just considered as a method, not used by the jvm.
you can have number of main() methods but not with the same signature.

4)What is the structure of java class?
A.java
 Class A{
             public static void main(String[] args){
                  ----------
               -------------
           }
}
    
5)Why should private method cannot be static?
It can be static , compiler will not throw any error ,if it is private static method.
depending on the scenario we can use private static methods.

6)What is platform independence?
 Java classes are converted into byte codes, when the java source code is compiled .class file is created which is a bytecode, this is picked up by the class loader and loads the class into jvm, Class loader is a namespace , Class loader is basically an object, using which the classes are loaded into jvm ,Classes are loaded into method area (a place for classes in memory). The import statements, i.e the classes that we refer in the class will also get loaded will be converted into memory addresses of that particular class in the memory (i.e import statements will refer to the actual memory addresses of the imported classes) and all these conversion of memory addresses is done by byte code verifier.
And this byte code can run on any hardware or any software which makes it platform independent.
JVM has a execution engine which is nothing but an interpreter(or hot spot compiler with a cache memory) which converts the byte code into machine language.

7)What are the features of java?
 *Abstraction
*Polymorphism
*Inheritance
*Encapsulation
*Security
*Multithreading
*jdbc   

8)What is polymorphism?
Polymorphism means more than one form.
There are 2 types of polymorphism :
a)Method overloading
b)Method overriding

Method Overloading : 2 methods in a same class or in the child class which has same name but different number of arguments is called method overloading.
2 methods with same arguments but different returntype is not considered as method overloading.
E.g public void setName(String name){
          this.name = name;
        }
    public String detName(String name){
        this.name=name;
        return name;
    }
is not method overloading.

Method overriding : Method overriding happens in Super class subclass relationship.you can have the same method signature in the subclass.depending on the object passed, the appropriate method is called. E.g.
package com.java.overriding;

class Employee{
    public String name;
    public String getName(){
       this.name = "SuperClassName";
       return name;
    }
}

class Address extends Employee{
  public String name;
  public String getName(){
      this.name="SubClassName";
      return name;
  }
}

public class test{
    public static void main(String args[]){        
         Employee e2 = new Employee();
         System.out.println(e2.getName());        
         Employee e1 = new Address ();
         System.out.println(e1.getName());
    }

}

9)What is the difference b/w abstract class and interface?
Abstract classes can have partial implementations , Interfaces are purely abstract, they can have only public abstract methods and final static constants.
Abstract classes can extend an abstract class. Interfaces can extend multiple interfaces.
Its recommended to use interfaces when the design changes frequently. you can declare the methods , and parameters it takes and fix the contract so that as per the design, different implementing classes can implement.Also you cannot extend multiple classes, A class can extend only one class,but it can implement many interfaces. In such scenarios, we can go for interfaces.
implementing an interface takes less cpu usage since it just contains method signatures and constants.
Abstract classes are expensive when compared to interfaces as it contains some code inside it.
Abstract classes lets you provide some default behavior.

10)What are the objects available in jsp / servlets?
There are 8 implicit objects available in jsp.
request >>HttpServletRequest object associated with request
response >> HttpServletResponse object associated with response
session>> HttpSession object associated with the request
application >>servletcontext associated with application context

out >>printwriter object
config>> ServletConfig object
exception >> exception object allows the exception data to be accessed by exception page
page >> page refers to this.
pagecontext>> using this all other objects are derieved.

11)What are the ways in which you can pass the control to another jsp or another servlet?    
 a) using  <a href="" />
b)<form action="" > </form>
c)from servlet you can use
RequestDispatcher rd = getServletContext().getRequestDispatcher(URI);
rd.forward(req,res) >> To forward the control to another servlet
rd.include(req,res)>> To include a jsp inside your jsp.
or
res.sendRedirect(URL); >> If some page is moved to another jsp, then you can point to the new jsp using this send redirect and providing the URL.

Tuesday, October 8, 2013

Java Quiz - 6

1) How does deserialization works in java?
We read the object from the external device for eg. a file and then we create a new instance of the object and make the object referene point to the deserialized object's state.
    try{
FileInputStream door = new FileInputStream("name_of_file.sav");
ObjectInputStream reader = new ObjectInputStream(door);
MyObject x = new MyObject();
x = (MyObject) reader.nextObject();
}catch (IOException e){
e.printStackTrace();
}

2)Hierarchy of exceptions in java?
java.lang.object ==> Throwable >> Exception >> RunTime Exceptions(unchecked)
                                                              Error              IO Exceptions(Checked)
                                                                                      SqlException(Unchecked)

3)When do u use checked exceptions and when do u not use unchecked exceptions?
Checked exceptions are compile time exceptions . i.e,  In Java whenever you access an IO, or DB there may be chances of failure always,  Java wanted to handle it separately it is categorized as  checked Exceptions.

4)What is the runtime of an arraylist.sort()?
ArrayList sorts the smaller arrays size<7 using insertion sort and larger arrays using merge sort.
Although merge sort runs in O(n*logn) worst-case time and insertion sort runs in O(n*n) worst-case time, the constant factors in insertion sort can make it faster in practice for small problem sizes on many machines.

5)How a form data is passed into another jsp? or another servlet?
  * using hidden fields
*using sessions
*using request objects

6)What is the difference b/w  using req.getAttribute("name") and request.getParameterName("name") ?
We can refer to the form data by using request.getParameterName("Name") and we can refer to the attributes which we have set it in our servlet to the request scope by using request.getAttribute();
There will not be any clash if two same names occur because, one is set at client another one at server side. So both are different.

7)How do you write your own custom tag?
* Write a tag handler class which extends Tagsupport / Body TagSupport
* Write a .tld file where mention <taglib> <tag><attribute></attribute> </tag> </taglib>
* Write <@taglib prefix="mytag" uri="taghandler" />

8)How do you get access to ServletContext from your jsp page?
${pageContext.servletContext}
or 
application 
 

Java Quiz - 5

1. What is the difference between hashmap and hashtable?
    hashtable is synchronized.
    hashmap is not synchronized.
    hashtable doesnot allow null keys or null values.
    hashmap allows 1 null key and multiple null value.

2.What is fail fast and fail safe in java? 
Fail fast : if we use iterator to iterate through the collection, in a multithreaded environment, if one thread is iterating the collection and other thread modifies the collection, then it throws concurrent modification Exception.So it fails fast.
Fail-safe: If we use the concurrent collections , like CopyOnWriteArrayList , BlockingQueue , ConcurrentHashMap it will not throw ConcurrentModificationException even though if we try to modify the collection when it is getting iterated.
Fail-safe Collections works with a copy of collection i.e clone of a collection so even if try to modify the collection i.e concurrent hashmap,then it will not throw concurrentmodification exception.

3.What is serialization in java?
Serialization is the process of storing the state of an object into an external System,to do that we need to convert the object into byte array.Serializable is a marker interface. which flags the jvm the objects of the serializable class to save the state of the object into a external system.

4.What is externalizable and serializable?
java.io.externalizable and java.io.serializable both are used to serialize an object and to save the state of the object into a database or a file.In earlier versions of jvm, the reflection was very slow and to handle the situation, java was provided with the java.io.externalizable interface.
This provides 2 methods : readExternal() and writeExternal() which we need to implement. we need to implement the marshalling and unmarshalling logic in these methods.This gives a workarround to performance to reflection problem.but modern jvms gives lot of performance when compared to  previous JVMs.so no need to use externalizable interface.also , JBOSS provides third party serialization which is very quick when compared to default serialization.      
One drawback of externalization is u need to maintain the logic of serialization. once a new field is added to the class , the object of which is getting serialized, then you need to add those fields in your readExternal() and writeExternal() interface.
The following code lines illustrate how to write MyObject (or any serializable object) to a file or disk.
try{
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyObject.ser"));
out.writeObject(object);
out.close();

// Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();

// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}

//read it from the disc
   
    try{
FileInputStream door = new FileInputStream("name_of_file.sav");
ObjectInputStream reader = new ObjectInputStream(door);
MyObject x = new MyObject();
x = (MyObject) reader.nextObject();
}catch (IOException e){
e.printStackTrace();
}
   
5.What is a Threadpool?
Its a pool of threads, which can be reused instead of creating large number of threads in an application we can reuse the threads by maintaining a finite number of threads in a pool of threads.

6.if you want to create an application with number of users want to access at the same time what will u do?
Create a pool of threads.and  assign it to each users.
   
7.what is executor in Java?
Executor is an interface in java.In large scale applications it makes sense to separate thread management from the thread creation.So we use executor Interface.Executor interface has only one method execute(r). execute(Runnable r) method takes only one object.
If e is an executor object then we can call e.execute(r) which does the same thing as [ {new Thread(r)} . start();] this is asynchronous so executes the given command(runnable object) sometimes in future.

8.What is the difference b/w Concurrent collections and Synchonized collections?
We use Collections.SynchronizedMap() to synchronize the collections. These are synchronized collections. but java 5 provides some of the concurrent collections like ConcurrentHashMap, BlockingQueue and CopyOnwriteArrayList.
It synchronizes a portion of arraylist or map ,  based on the concurrency level,so its performance is higher.however the hashtable provides better thread safety on a cost of performance.   

9.What happens to java generics at runtime?
The main advantage of generics is for type casting, type safety, type checks, the information of generics is lost at runtime. The impossibility to inspect generic-types at runtime, because they had to be implemented with Type Erasure. One way to handle this is to store the Type information in seperate class, like we have java.lang.reflect.Type; using this we can create a separate class and store the Type info.

10.what is the life cycle of a servlet?
Container loads the sevlet into the jvm, It creates the Class object of the Servlet and calls the getInstance() method on the class object  which calls the private constructor of the class there by creating an instance, and using that it instantiates the servlet by calling init() method , Every Servlet has to call this init() method, you can implement init() method, to initialize a resource like getting the  database Connection,open a file(All one time task can be performed using init()), or you dont have to implement init(ServletConfig) method in your servlet class .init(ServletConfig) takes one parameter , i.e Servlet Config, which is used to pass the initial parameters to the servlet ,from web.xml Then it calls the Service(ServletRequest,ServletResponse) of  Generic Servlet, which then calls the overriden Service(ServletReq, ServletRes) from HTTPServlet class , which then calls the protected Service(Httpreq,Httpres) this has a req.getMethod() which returns the method is post/get .
protected Service(Httpreq,Httpres){
        req.getMethod();

using this info either doget() or doPost() method is called, so once this is finishes the execution, the 
destroy() method is called which releases the resources acquired in init() method.

11.How does hashmap works in java?
Hashmap works on hashing mechanism.Hashing mechanism is a way of assigning a unique code to an object by applying some formula to the members of that object.Hashmap has a inner class Entry which impements Map.Entry.which has a final key, a value, next and hash.The instance of this Entry class is stored in an array.Now 2 unequal objects may have same hashcode. then how it(put(key,value)) will determine the location to store the object?
That's why we have next pointer. It is stored in a linkedlist(linked list is inside the arrayindex, which is nothing but a hash bucket) inside the Array. it traverses through the linked list and gets the null position of the linked list.Because there may be already some objects which r having same hashcode might have been saved in the same bucket i.e same array index.So Linked list is traversed and the new unequal object with same hashcode is placed in the null position.
When you give key to retrieve the object get(key) hashmap uses keys hashcode to retrieve the value.
 if 2 object has same hashcode they have 2 objects in the same bucket. thats when we use equals() to compare the contents of the objects and return the correct object.

12.What happens On HashMap in Java if the size of the HashMap  exceeds a given treshhold defined by load factor ?
Resizing happens and race condition occurs when one thread is trying to resize and refill more new buckets as in arraylist it does, putting all the old values in the new buckets, the other thread also tries to resize it by putting the old contents into new buckets.This process is called rehashing. while rehashing it may leads to race condition.

13.Why String, Integer and other wrapper classes are considered good keys ?
They are immutable, they are final and returns the same hashcode always .They have implemented equals() and hashcode(). They are threadsafe.

Java Quiz - 4

1) Write a program to produce the following output:
1
2
BOB
HARRY
5
BOB
7
HARRY
BOB
10
11
VINH
13
14
BOB
HARRY
17
BOB
.......
.......
100

Answer:
For(int i =1;i<=100 ; i++){
     if( (i%12)==0){System.out.println("VINH");  // catch 12 should be checked first
     if((i%3)==0){System.out.println("BOB");
     if((i%3)==0){System.out.println("HARRY");
}

2) What is wrong in the below program?

public class ConnectionManager{
........
........
try{
Class.forname("oracle.jdbc.oracledriver);
 Connection con= DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","SCOTT","Tiger");
Statement stmt = con.createstatement("Select * from Employee");
ResultSet res = stmt.executeQuery();
while(res.next()){
.....
......
}
 --------
-------
}catch(Exception e){
   e.printStackTrace();
}

}

Answer : you need to have a finally block to avoid the memory leaks in java.
finally{
         res.close();
         stmt.close();
        con.close();
}


3) HashMap<String, String> hm = new HashMap<String,Integer>();Will it work?
No. Compilation error because, you cannot associate a <String,String> with <String,Integer>

4)Write a program to display each key with a value from the below code:-
Map<String,String[]> m1 = new HashMap<String,String[]>();      
        String[] strarr={"TOM","David","Robert","Harry"};
        m1.put("mary",strarr);
        m1.put("kally",strarr);
        m1.put("Rossy",strarr);
E.g.
Rossy,TOM
Rossy,David
Rossy,Robert
Rossy,Harry
kally,TOM
kally,David
kally,Robert
kally,Harry
mary,TOM
mary,David
mary,Robert
mary,Harry




Answer:
Map<String,String[]> m1 = new HashMap<String,String[]>();       
        String[] strarr={"TOM","David","Robert","Harry"};
        m1.put("mary",strarr);
        m1.put("kally",strarr);
        m1.put("Rossy",strarr);
        int strlen = strarr.length;
       
        Set s = m1.keySet();
        Iterator itr = s.iterator();
        while(itr.hasNext()){
            String key = (String)itr.next();
           
            for(int i=0;i<=(strlen-1);i++){           
                System.out.println(key +","+strarr[i]);
            }
        }

5)   ===================================================================
       Author_ID      Author_Name                         Book_ID    Book_Name     Author_ID
     =====================================================================
         101                  Shakes Sphere                               1           PoeteryWorks       102
         102                  William WordsWorth                    2           Romeo Juliet         101





         103                  Jhonspace                                      3           Small Poems         102


Find the poet who has maximum number of books?



       





Sunday, October 6, 2013

Java Quiz - 3

1) Write a program to reverse a String
String  str="navya";
int strlen = str.length();
int j=0;
Char[] chararray = new Char[strlen];
for(int i = (strlen-1) ; i >0; i--){
   chararray[j] = str.charAt(i);
   j=j+1;
  if(j == strlen-1)
{
   chararray[strlen-1] = str.charAt(0);
}
System.out.print(chararray);

2)What is a Transaction in Java?
 Transaction is a way to make sure that data is consistent in database. Suppose you dont want to show the month to date unless year to date gets updated, otherwise yeartodate will point to a old value which leads to data inconsistencies.Transaction makes sure that either both the statements gets executed or none of the statement gets executed.
Transaction is used to group together the statements.

3)How to disable the Auto Commit?
Connection con = DriverManager.getConnection("jdbc.oracle:thin:@localhost :1521:orcl","username","password");
con.setAutoCommit(false);
once the autocommit is disabled, till you call the commit, no statement is going to get updated in the database.All the statements are executed as a single transaction ,once the commit is called.
It is advisable to use setautocommit(false) in case of transactions mode.This way you avoid holding the lock for Database till the multiple statements get executed.

4)Explain the real world scenario where transactions are useful?
Transactions are useful when multiple users are trying to update the database. 
For E.g in a ticket reservation system, one counter is trying to update the (available ticket - no of ticket sold), while the other counter is trying to update may see the older value of available ticket and it also tries to update(available ticket - no of ticket sold), this leads to data inconsistency.
For e.g in a price tool, when multiple users are trying to update the new price for an item,or a new discount for an item.
This kind of situations can be avoided by using the transactions, which provides some level of protections against the data conflicts.

5)What is a lock on the Database row?
To avoid conflicts in the database during a transaction, Database uses locks mechanism to prevent other users to access the data which is accessed by the transaction.Once the lock is set, it remains till the transaction is committed or rolled back.In auto commit mode, locks are held for each statement.

6)What is Transaction isolation level?
How the locks are set into the database is determined by transaction isolation level.
usually you do not need to do anything about your Transaction Isolation Level. DBMS has default transaction Isolation Level set. you can make use of default Transaction Isolation Level,

There are 5 Transaction Isolation Levels : These values are in CONNECTION Interface
TRANSACTION_NONE >> Transactions not supported
TRANSACTION_READ_UNCOMMITTED >>dirty phantom and non repeatable reads are allowed.
TRANSACTION_READ_COMMITTED  >> dirty reads are prevented.
TRANSACTION_REPEATABLE_READ >>dirty and non-repeatable reads are prevented.
TRANSACTION_SERIALIZABLE>>dirty , phantom, non-repeatable reads are prevented.
JDBC provides method to get the transaction isolation level of the DBMS.using connection.getTransactionIsolation()

7)What are dirty phantom and non-repeatable read?
 Dirty Read :
value can be accessed before it is committed and once it is changed by the other user.
Non-Repeatable Read :
A Non-repeatable read occurs when transaction A retrieves a row, and transaction B subsequently updates the new Row, then if the transaction A later retrieves the same row again, it sees a different data.
Phantom Read:
 A phantom read occurs when transaction A retrieves a set of rows satisfying a given condition, transaction B subsequently inserts or updates a row such that the row now meets the condition in transaction A, and transaction A later repeats the conditional retrieval. Transaction A now sees an additional row. This row is referred to as a phantom.

8) What are the differences between ArrayList and Linked List?
Array-List is backed by an array and Linked List is backed by a Doubly Linked List .
index based search is possible using an ArrayList whereas you need to traverse through the Linked list to search for a particular element.Array list is best used on set() and get() whereas worst on Add() remove() elements , whereas Linked List is () remove() and worst on get() set(). Linked List implements List and Queue whereas Array List implements only List, so Linkedlist has more methods like pool(),peek() etc. Its good practice to create an arrayist with a higher initial capacity to avoid the re-size cost.

9)Explain singleton and factory pattern.
Singleton pattern can be achieved in various ways in java.
·         Eager initialization
·         Lazy initialization
·         Double Checked Locking
 Eager initialization:- the instance is created much before it is required i.e. instance is created as static variable when the class is loaded all the static variables are created. So new instance also created. Please ensure that you are using volatile keyword on your instance variable , otherwise you enter into out of order write error.(This means, JVM has just allocated the memory for your instance, but not executed the constructor yet, so it may return null pointer exception or crash application with out of write error)
public class Singleton {
      private static volatile Singleton instance = new Singleton();
      // private constructor
      private Singleton() {
      }
      public static Singleton getInstance() {
      return instance;
      }
}  
Lazy Initialization: So to solve this problem, just declare the instance, and if the instance is null then only create a new instance. On the first call it checks if the instance is null, if the instance is null, then a new instance is created. if it is not null, the same instance is returned.
 public final class Singleton {
            private static volatile Singleton instance = null;
            // private constructor
            private Singleton() {
            } 
      public static Singleton getInstance() {
                  if (instance == null){
                        synchronized (Singleton.class) {
                              instance = new Singleton();
                        }
                  }
                  return instance;
                  }
            }
 but there is a problem with this method, two threads T1 and T2 comes to the block (instance== null) and both can create the instance of the Singleton class, so u need to have double checked locking.
public final class Singleton {
private static volatile Singleton instance = null;
// private constructor
private Singleton() {
} 
public static Singleton getInstance() {
            if (instance == null){
                  synchronized (Singleton.class) {
                         // Double check
                        if(instance == null){
                              instance = new Singleton();
                        }
                  }
            }
            return instance;
      }
}
 This is the Correct implementation of Double checked locking.

Factory pattern: We usually use "new" to create an instance in java. but that is old fashioned now, especially when you have lot of initializations to do or if you want to change the method of creating an object in various places of application, you need to go to different places of application to make the code changes.In Such scenarios we can use factory pattern.Factory Pattern provides loose Coupling between the classes which is important principal while designing the architecture.

E.g Spring Dependency Injection.

10) What is the javascript library you have used?
To use a JavaScript framework library in your web pages, just include the library in a <script> tag:
Including jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>


11)How would you programatically get unique list of primarykeys, (E.g you have a list of primarykeys with duplicates in it from a webservice) and save the unique records to database?

Use HashSet 

12)What is agile methodology?  
  • Rapid delivery of the software.
  • Welcome changing requirements even in late development 
  • Working software is delivered in weeks
  • Daily cooperation between business and developers
  • face to face conversations
  • technical excellence and good design
  • regular adoption to changing circumstances.

Java Quiz - 2


1) What is volatile in java?               
Volatile is only applicable on variables in java ,not to methods. By making a variable as volatile , you are asking the JVM to read the values of the variable from the memory and not from the cache. Java reads and writes are atomic using volatile variable including  long and double variables. Using Volatile variable reduces the risk of memory inconsistency errors in java .An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.

2) Why wait(), notify() and notifyall() methods are defined in Object class not in thread class?
Because Lock is placed on the object not on the calling Thread.

3)What are the differences between synchronized and volatile keyword in Java ?
Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods. Synchronized requires a lock to be placed on the object, where as volatile does not require any lock to be placed on the object. Other Threads will be blocked on the monitored area i.e. synchronized block or Synchronized method, whereas Volatile variables are not blocked. Synchronized method affects performance whereas Volatile doesn't affect performance as much as Synchronized. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory  and "main" memory ,while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile. Volatile can be applied on null, whereas Synchronized cannot be applied on null.

4)What is the difference between hash map and hash table in java?
 Hashmap is Synchronized, Hashtable is not Synchronized. Hashmap accepts one null key and multiple null values, where as hashtable doesn't  accept null keys and null values.

5) How HashMap can be Synchronized?
Map map = new HashMap(); It can be Synchronized using Collections.SynchronizedMap(map);

6)What are the design patterns you have worked on?
Singleton, Factory, MVC

7)What is Double checked Locking in Singleton?
Singleton pattern can be achieved in various ways in java.
·         Eager initialization
·         Lazy initialization
·         Double Checked Locking
 Eager initialization:- the instance is created much before it is required i.e. instance is created as static variable when the class is loaded all the static variables are created. So new instance also created. Please ensure that you are using volatile keyword on your instance variable , otherwise you enter into out of order write error.(This means, JVM has just allocated the memory for your instance, but not executed the constructor yet, so it may return null pointer exception or crash application with out of write error)
public class Singleton {
      private static volatile Singleton instance = new Singleton();
      // private constructor
      private Singleton() {
      }
      public static Singleton getInstance() {
      return instance;
      }
}  
Lazy Initialization: So to solve this problem, just declare the instance, and if the instance is null then only create a new instance. On the first call it checks if the instance is null, if the instance is null, then a new instance is created. if it is not null, the same instance is returned.
 public final class Singleton {
            private static volatile Singleton instance = null;
            // private constructor
            private Singleton() {
            } 
      public static Singleton getInstance() {
                  if (instance == null){
                        synchronized (Singleton.class) {
                              instance = new Singleton();
                        }
                  }
                  return instance;
                  }
            }
 but there is a problem with this method, two threads T1 and T2 comes to the block (instance== null) and both can create the instance of the Singleton class, so u need to have double checked locking.
public final class Singleton {
private static volatile Singleton instance = null;
// private constructor
private Singleton() {
} 
public static Singleton getInstance() {
            if (instance == null){
                  synchronized (Singleton.class) {
                         // Double check
                        if(instance == null){
                              instance = new Singleton();
                        }
                  }
            }
            return instance;
      }
}
 This is the Correct implementation of Double checked locking.


8)What is weak reference?
you create weak reference using
WeakReference weakWidget = new WeakReference(widget);
and then elsewhere in the code we can use
 weakWidget.get()
to get the actual widget object.
The weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null. we use it in case if we want listeners to register it to the service. Listener objects are created as Weak references.

9)What is the difference b/w Action support and Action?
       Action is an interface which has only one method execute() and Some constants like LOGIN, ERROR , SUCCESS,INPUT, NONE.
ActionSupport is a class which extends Serializable,  validatable, ValidationAware Interfaces which provides methods for field level validation. E.g. validate() addFieldError(fieldname, Errormessage) .

10)What is the difference between OGNL and EL?
Object Graph Navigational Language is specific to Struts2
EL is specific to Servlets.
OGNL is more powerful and provides lambda expressions to navigate through objects in value stack. OGNL provides more sophisticated way to traverse through request, session, application and web context.

11) What is the dynamic method invocation in struts2?
In Struts2 , we can provide method name using method attribute,
<action name="getFormResult" class = "MyPackage.MyClass" method="myFormResult">
     <result name="Success" > /Success.jsp </result>
</action>

This can also be configured dynamically depending on the action name passed, using Action Wild cards ,For E.g.
<action name="get*Result" class = "MyPackage.MyClass" method="my{1}Result">
     <result name="Success" > /Success.jsp </result>
</action>
So whatever the value passed to the * will  be substituted to {1}


12)What is the difference b/w struts1 and struts2?
    In Struts1, we have not configured the controller as filter where as in struts 2 we have configured Struts2PrepareAndExecuteFlter as controller which is a filter.
So no need to provide <LoadOnStartup>1</LoadOnStartup> in Struts2.
Struts2 has some automatic features like event validation, automatic transfer of parameters from jsp form to value stack before the initialization of Action class so that the parameters are available to the Action class from input form. So it's a Pull MVC Architecture whereas in Struts1 , you need to push the objects from Form to Action class, and Action class needs to retrieve the values explicitly.
The Automatic features of struts2 is due to Interceptors where as the Struts1 doesn't have Interceptors concept.

13) Are interceptors threadsafe?
     No , Interceptors are not thread safe whereas action classes are thread safe. That's why when the request comes, a new instance of action class is created and we can store the data in the member variables as it is specific to the action class instance , where as in Servlets, Every request is Serviced by a different thread and the data stored in the servlet is shared by different threads So we use Request, session objects to pass the data from one form to other.

14)What is the flow of struts2 ? data flow ? or architecture?
When the user hits the URL, a jsp form is displayed which is either configured as the welcome file list or a url in the namespace. then the user fills the form and submits the data, the control is passed to container , the container looks at web.xml, web.xml has Struts2PrepareAndExecteFilter is configured as a filter, so Container calls the Controller and controller looks at the action mapper and invokes Action Proxy, Action proxy calls the Configuration Manager and looks at struts.xml, here the form's  method="" and action="" attributes are compared with the Action mappings , and appropriate  Action Class's information, and the interceptor's associated with the Action class is retrieved and control is passed to Action Invocation, Action Invocation is the big brother, it passes its own instance to Interceptor's invoke (ActionInvocation ai)method , and executes the pre-logic and post logic methods,
and finally the control is passed to Action class , Whose execute() method gets called. and the appropriate HttpResponse gets generated. This is passed to the client back.

15)What  is an Outer Join?
Outer join is of 2 types.
    1)Left join.
        Left join is the intersection of the 2 table and the left table.
        Select empno, empname from Employee
        LeftJoin Address
        On Employee.empid = Address.empid;
    2)Right join
        Its the intersection of 2 tables + the right table.
        Select empno,empname from Employee
        RightJoin Address
        On Employee.empid = Address.empid;