Thursday, June 3, 2010

Singleton - Multiple Users [Thread Safe]

Following is the way by which we can use Singleton Design pattern for multiple users.

public class Singleton {
         private volatile static Singleton singleton; //volatile is needed so that multiple thread can reconcile the instance
         private Singleton(){
         }

         public static Singleton getSingleton(){ //synchronized keyword has been removed from here
         if(singleton = = null)
         {          //needed because once there is singleton available no need to aquire monitor again & again as it is costly
                synchronized(Singleton.class)
                {
                        //this is needed if two threads are waiting at the monitor at the time when singleton was getting instantiated
                      if(singleton==null)
                      {      
                              singleton= new Singleton();
                       }
                  }
          }
          return singleton;
    }
}

Thursday, May 13, 2010

wait(), notify() and notifyAll()

The wait(), notify() and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

Monday, May 10, 2010

Volatile Modifiers in Java

Volatile Modifier

       The volatile modifier requests the Java Virtual Machine to always access the shared copy of the variable so the its most current value is always read. If two or more threads access a member variable, and one or more threads might update that variable’s value, and all of the threads do not use synchronization to read and/or write the variable value, then that member variable must be declared volatile to ensure all threads should get the updated value.
       We will discuss the java volatile modifier using following example.
       In our example, we take two threads Thread T1 and Thread T2 accessing member variable x of class C and here Thread T1 is not using synchronization and Thread T2 uses synchronization. If Thread T2 updates value of variable x from 0 to 1. But if the variable x is not declared as volatile then meanwhile Thread T1 tried to access variable then it will get value of variable x as 0. But as variable x is updated to 1 by Thread T2, To avoid this mess the variable x should be declared as volatile so Thread T1 should get updated value 1.

Thursday, May 6, 2010

HashMap vs ConcurrentHashMap

Both HashMap and ConcurrentHashMap are inherits some characteristics of Hashtable. But they have some prominent differences in context with performance, scalability.

HashMap
  1. Since Java 1.2
  2. Allows null key and value
  3. Poor performance in highly threaded applications
  4. Not much scalable
  5. Throws a ConcurrentModificationException
  6. Faster in non-multi threading applications

ConcurrentHashMap
  1. Since Java 1.5
  2. Doesn't allow null key or value
  3. Better performance in Highly threaded applications
  4. Highly scalable
  5. Do not throw ConcurrentModificationException
  6. Slower in non-multi threading applications


Wednesday, May 5, 2010

Read value from Java properties

Here, you will find the source code to read value of the key from properties file. java.util.Properties class extends Hashtable. Properties class creates the properties file which stores key - value pair using Hashtable. To retrieve value from properties file we have to follow following steps.
  1. Create an object of Properties class.
  2. Load properties file using FileInputStream into properties object.
  3. Get value from properties object using getProperty() method passing key as an input.
The below code will help to understand more...

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class PropertiesReadTest {

    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("C:\\temp\\test.properties"));
            String value = properties.getProperty("key");
            System.out.println("Value = " + value);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output is shown here in following image





Tuesday, May 4, 2010

Source code to read content of File

Here you will find the source code to read the content of file.

Steps
  1. Create the FileReader object using file name as an input to FileReader constructor.
  2. Pass that FileReader object to BufferedReader.
  3. Read the line from BufferedReader object till readline gets null.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReadTest {

    public static void main(String[] args) {
         try {
            BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
            String line = "";
            while((line = br.readLine()) != null)
            {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Monday, May 3, 2010

Access file using JSP & Servlets

Given source code used for accessing file from server using

Servlets


String path = getServletContext( ).getRealPath ("xyz.xml" ) ;
System.out.println ( path ) ;
File file = new File ( path ) ;

JSP
String path = application.getRealPath ("xyz.xml" ) ;
System.out.println ( path ) ;
File file = new File ( path ) ;

In above jsp code, "application" is jsp implicit object.



Friday, April 30, 2010

Java pass by value or pass by reference

  • Java manipulates objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
  • Java is strictly pass-by-value, exactly as in C.
  • Java has pointers and is strictly pass-by-value.


Thursday, April 29, 2010

Encapsulation in JAVA

Encapsulation in java means declare instance variables of class as private and access that instance variables using public methods.
Following is the example which shows that Person class having name and age are private instance variables and those are accessed by public getter and setter methods.

public class Person {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}


OOPs concepts in JAVA

  • Abstraction: Hides certain details and only show the essential features of the object.
  • Encapsulation: The internal representation of an object is generally hidden from view outside of the object's definition.
  • Inheritance: Defines relationships among classes in an object-oriented language.  
  • Polymorphism: Define more than one method with the same name.


    finally block not executed

    Finally block is always executed except some of the following cases.
    • If the JVM exits while the try or catch code is being executed, then the finally block may not execute. 
              e.g. System.exit(0);
    • If the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. 
             e.g. Thread.interrupted();


    J2EE Design Patterns

    1. Business Delegate
    2. Composite Entity
    3. Composite View
    4. Data Access Object (DAO)
    5. Fast Lane Reader
    6. Front Controller
    7. Intercepting Filter
    8. Model-View-Controller
    9. Service Locator
    10. Session Facade
    11. Transfer Object
    12. Value List Handler
    13. View Helper

    Tuesday, April 20, 2010

    Static vs Transient variables

    Static variables
    • Static variables are class variables.
    • Static variables can be serialized.
    • static modifier applies to static variables.
           class TestClass{
              static int testVariable;
              . . .
          }

    Transient variables
    • Transient variables are member or instance variables of class.
    • Transient variables can not be serialized.
    • transient modifier applies to transient variables.
           class TestClass{
              transient int testVariable;
              . . .
          }

    Thursday, April 15, 2010

    JDK 5 Enhancements in Java Language


    1.      Generics - This is an enhancement to the type system allows a type or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting.
    e.g.
    Previously
    Array List numbers = new ArrayList();

    Now in JDK 5.0
    Array List<Integer> numbers = new ArrayList<Integer> ();

    2.      Enhanced for Loop - This new language construct eliminates the drudgery and error-proneness of iterators and index variables when iterating over collections and arrays.
    e.g.      
    Previously
    Iterator itr = numbers.iterator();
    while
     (itr.hasNext()) 
    {
          Integer element = (Integer)itr.next();
          System.out.println (number);
    }

    Now in JDK 5.0
    for (Integer number: numbers)
    {
                System.out.println (number);
    }

    3.      Autoboxing/Unboxing - This facility eliminates the drudgery of manual conversion between primitive types (such as int, long) and wrapper types (such as Integer, Long).
    e.g.      
    int number = 1;
    Previously
    Integer number2 = (Integer) number;

    Now in JDK 5.0
    Integer number2 = number;

    4.      Typesafe Enums - This flexible object-oriented enumerated type facility allows you to create enumerated types with arbitrary methods and fields. It provides all the benefits of the Typesafe Enum pattern ("Effective Java," Item 21) without the verbosity and the error-proneness.
    e.g.
    Previously
    public static final int SEASON_WINTER = 0;
    public static final int SEASON_SPRING = 1;
    public static final int SEASON_SUMMER = 2;
    public static final int SEASON_FALL   = 3;

    Now in JDK 5.0
    enum Season {WINTER, SPRING, SUMMER, FALL}

    5.      Varargs - This facility eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists.
    e.g.
    Previously
    Object[] arguments = {
        new Integer(7),
        new Date(),
        "a disturbance in the Force"
    };

    String result = MessageFormat.forma("At {1,time} on {1,date}, there was {2} on planet "
         + "{0,number,integer}.", arguments);

    Now in JDK 5.0
    Using Varargs no need to create object array separately, we can give arguments directy.

    String result = MessageFormat.format("At {1,time} on {1,date}, there was {2} on planet "
        + "{0,number,integer}.",
        7, new Date(), "a disturbance in the Force");

    6.      Static Import - This facility lets you avoid qualifying static members with class names without the shortcomings of the "Constant Interface antipattern."
    e.g.
    Previously
    double r = Math.cos(Math.PI * theta);

    Now in JDK 5.0
    import static java.lang.Math.*;
    Once the static members have been imported, they may be used without qualification or class names:
    double r = cos(PI * theta);

    7.      Annotations (Metadata) - This language feature lets you avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a "declarative" programming style where the programmer says what should be done and tools emit the code to do it. Also it eliminates the need for maintaining "side files" that must be kept up to date with changes in source files. Instead the information can be maintained in the source file.
    Now in JDK 5.0
    public @ interface Test{}





    Wednesday, April 14, 2010

    Retrieve key from HashMap using value

    Below is the code to retrieve the key from HashMap using value
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    import java.util.Map.Entry;

    public class TestClass {

        public static void main(String[] args) {
            Map<Integer, Person> people = new HashMap<Integer, Person>();
            Person person1 = new Person();
            person1.setName("Mack");
            person1.setPost("Dev");
           
            Person person2 = new Person();
            person2.setName("John");
            person2.setPost("Dev");
           
            people.put(1, person1);
            people.put(2, person2);

            Set<Entry<Integer, Person>> peopleSet = people.entrySet();
            for (Entry<Integer, Person> entry : peopleSet) {
                Integer key = entry.getKey();
                Person value = entry.getValue();
                if (value.equals(person2)) {
                    System.out.println("Key = " + key);
                }
            }
        }
    }


    Tuesday, April 13, 2010

    Servlet Chaining

    Servlet Chaining means the output of one servlet given as a input to another servlet. Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with a common servlet alias. The output from first Servlet is sent as input to other Servlet and so on. The Output from the last Servlet is sent back to the browser. The entire process is called Servlet Chaining.

    How to do Servlet Chaining in Servlet Programming?

    Using include
    RequestDispatcher rd = req.getRequestDispatcher("SecondServlet"); 
    rd.include(request, response);

    Using forward
    RequestDispatcher rd = req.getRequestDispatcher("SecondServlet"); 
    rd.forward(request, response);



    Monday, April 12, 2010

    JDBC driver types

    JDBC drivers are divided into four types.
    • Type 1: JDBC-ODBC Bridge
    • Type 2: Native-API/partly Java driver
    • Type 3: Net-protocol/all-Java driver
    • Type 4: Native-protocol/all-Java driver

    Java Database Connectivity (JDBC)

    JDBC is Java Database Connectivity helps to write java applications using databases.

    Steps to use JDBC in java applications as follows
    1. Load the JDBC driver.
    2. Define the connection URL.
    3. Establish the connection.
    4. Create a statement object.
    5. Execute a query or update.
    6. Process the results.
    7. Close the connection. 
    try {
                Class.forName("driveClassName");
                Connection con = DriverManager.getConnection(
                        "jdbc:driveName:databaseName", "login", "password");

                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM Table");
                while (rs.next()) {
                    int a = rs.getInt("column1");
                    String b = rs.getString("column2");
                    float c = rs.getFloat("column3");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                // close the connection
            }





    Serialization and Deserialization

    1. Serialization is the process of transforming an in-memory object to a byte stream
    2. An object is serialized by writing it to an ObjectOutputStream. 
    3. Serialization Code 
               FileOutputStream out = new FileOutputStream("test.txt" );
               ObjectOutputStream oos = new ObjectOutputStream( out );
               oos.writeObject(new String ());
               oos.close ();
    1. Deserialization is the inverse process of reconstructing an object from a byte stream to the same state in which the object was previously serialized. 
    2. An object is deserialized by reading it from an ObjectInputStream.
    3. Deserialization Code
    FileInputStream in = new FileInputStream( "test.txt" );
    ObjectInputStream ois = new ObjectInputStream( in );
    String s = (String) ois.readObject();
    ois.close();



    JAR WAR and EAR Files

    JAR Files (Java Archive):

    1. These files are with the .jar extension.
    2. The .jar files contain the classes, libraries, resources and accessories files like property files.

    WAR Files (Web Archive):

    1. These files are with the .war extension.
    2. The war file contains JSP, html, JavaScript and other files for necessary for the development of web applications.
    3. The war file contains the web application that can be deployed on the any servlet/jsp container.

    EAR Files:

    1. These files are with the .ear extension.
    2. The .ear file contains the EJB modules of the applications.
    3. The ear file contains the ejb application that can be deployed on the any application server with ejb container.


     

    Difference between customTags and JavaBeans


    1. JavaBeans are the data handlers of JSP and aid in encapsulating data management logic. They are used for storage Tags on the other hand, aid computational logic related to a particular request. 
    2. Tags are thread safe; beans are not. Beans like other separate utility classes, have to be made thread safe by the developers. 
    3. Tags are aware of the environment (the page context) in which they execute. Beans are not. 
    4. Tags remain in the translation unit.We can think of tags as events occuring in the execution of a JSP page. Beans are object stores that reside outside the translation unit. 
    5. Tags can access implicit objects. Beans are cannot. 
    6. Tags only have page scope. They are created and destroyed withen a single request and in a single page. They can access other objects in all the scopes, though. Beans, on the other hand. Are themselves objects that reside in different scopes. Therefore, tags can access and manipulte beans, while beans do not access and manipulate tags. 
    7. The Tag Extension API designed closely with the concept of a JSP page in mind. They may not be used in other applications. Beans, on the other hand are supposed to be resuable compnents and can be used by other container. 
    8. Tags are not persistent objects. Beans have properties, and properties have values. A set of values is called the state of the bean. This state can be persisted via serialization and resued later.

    Sunday, April 11, 2010

    JSP Standard Actions

    JSP standard actions are commands given to the JSP engine. They direct the engine to perform certain tasks during the execution of a page.
    e.g. The following line instructs the engine to forward request to another JSP page, welcome.jsp from current JSP page.

    <jsp:forward page="welcome.jsp"/>


    There are six standard JSP actions:
    1. jsp:include
    2. jsp:forward
    3. jsp:useBean
    4. jsp:setProperty
    5. jsp:getProperty
    6. jsp:plugin

    Saturday, April 10, 2010

    Difference between GET Method and POST Method

    GET Method
    1. Target resource type is Active or passive
    2. Type of data is Text
    3. The amount of data handled by GET Method is not more than 255 characters.
    4. Data is part of the URL and is visible to the user in the URL field of browser.
    5. Data can be cached in the browser's URL History.
    POST Method
    1. Target resource type is Active
    2. Type of data is Text as well as Binary
    3. The amount of data handled by POST Method is unlimited.
    4. Data is not a part of the URL and is sent as the request message body. It is not visible to the user in the URL field of browser.
    5. Data is not cached in the browser's URL History.

    Thursday, April 8, 2010

    Difference between abstract class and interface

    What is an Abstract Class?

    1. An abstract class is a special kind of class that cannot be instantiated.So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
    2.  A class may inherit only one abstract class.
    3. An abstract class can contain access modifiers for the subs, functions, properties
    4. Fast
    5. An abstract class can have fields and constants defined

    What is an Interface?

    1. An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class.
    2. A class may inherit several interfaces.
    3. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
    4. Requires more time to find the actual method in the corresponding classes.
    5. No fields can be defined in interfaces

    Friday, March 26, 2010

    What are implicit objects?

    Implicit Objects:

    Implicit Objects in JSP are objects that are automatically available in JSP. Implicit Objects are Java objects that the JSP Container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.

    Following are the implicit Objects

    request
    response
    session
    application
    page
    pageContext
    out
    config
    exception


    What is difference between HashMap and HashTable and HashSet and TreeSet?

    Hashtable
    Hashtable is basically a data structure to retain values of key-value pair
    •  It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
    • It is synchronized. So it comes with its cost. Only one thread can access in one time. So It is slow.
    HashMap
    Like Hashtable it also accepts key value pair.
    • It allows null for both key and value. 
    • It is unsynchronized. So come up with better performance(fast)

    HashSet
    It is from Set family.
    • HashSet does not allow duplicate values. 
    • It provides add method rather put method. 
    • You also use its contains method to check whether the object is already available in HashSet. 
    • HashSet can be used where you want to maintain a unique set but not the order. 


    TreeSet
     It is also from Set family.
    • Likely HashSet, TreeSet does not allow duplicate values.
    • It provides add method rather put method. 
    • You also use its contains method to check whether the object is already available in TreeSet. 
    • TreeSet can be used where you want to maintain a unique set as well as the order. 



    Monday, February 15, 2010

    JSP Life Cycle

    1. JSP Page Translation:

    A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

    2. JSP Page Compilation:

    The generated java servlet file is compiled into a java servlet class.
    Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

    3. Class Loading:

    The java servlet class that was compiled from the JSP source is loaded into the container.

    4. Execution phase:

    In the execution phase the container manages one or more instances of this class in response to requests and other events.
    The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

    5. Initialization:

    jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

    6. _jspService() execution:

    This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.

    7. jspDestroy() execution:

    This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
    jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

    Friday, February 12, 2010

    Servlet Life Cycle

    Servlet Life Cycle Methods

    The following are the life cycle methods of a servlet instance:
    • init()
    • service()
    • destroy()
    We will look into the each method in detail.

    init()

    This method is called once for a servlet instance. When first time servlet is called, servlet container creates instance of that servlet and loaded into the memory. Future requests will be served by the same instance without creating the new instance. Servlet by default multithreaded application.init() method is used for inilializing servlet variables which are required to be passed from the deployment descriptor web.xml. ServletConfig is passed as the parameter to init() method which stores all the values configured in the web.xml. It is more convenient way to initialize the servlet.

    service()

    This method is called for the each request. This is the entry point for the every servlet request and here we have to write our businesslogic or any other processes. This method takes HttpServletRequest and HttpServletresponse as the parameters. It is not mandatory to write this method, normally developers are interested in writing doGet() or doPost() methods which is by default called from the service() method. If you override service(), it is your reponsibility to call the appropriate methods. If you are not overridden the service() method, based on the types of the request the methods will be called.

    destroy()

    This method will be called once for a instance. It is used for releasing any resources used by the servlet instance. Most of the times it could be database connections, Fill IO operations, etc. destroy() is called by the container when it is removing the instance from the servlet container. Servlet instance is deleted or garbage collected by the container only when the web server issues shut down or the instance is not used for a long time.


    What is difference between final and finally and finalize?

    final:
    1. final keyword can be applied to variables,method,class. 
    2. final variable - You can't reassign/modify values to the variables. final class- You cannot extends(inherit) the class.
    3. final method- You cannot override the final methods.
    finally:
    1. finally is used in try-catch (i.e exception handling in java).
    2. Each try contain only one finally blocks not more than one.
    3. There is no statement between catch block and try block. It muse execute if exception is occurred or not. Mostly used for memory release (closes connections).

    finalize():
    1. This is method used to release the occupied memory.
    2. finalize() method must be protected or public otherwise compile time error.

    What is difference between Overloading and Overriding?

    Overloading: The methods with the same name but it differs by types of arguments and number of arguments.

    Overriding:  The methods with the same name and same number of arguments and types but one is in base class and second is in derived class.


    What is difference between Unchecked and Checked Exceptions?

    Unchecked exceptions :
    • represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."
    • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
    • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)
    Checked exceptions :
    • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
    • are subclasses of Exception
    • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

    Thursday, February 11, 2010

    What is difference between Synchronized method and Synchronized block?

    What is difference between Synchronized method and Synchronized block?


    The key difference is this: if you declare a method to be synchronized, then the entire body of the method becomes synchronized; if you use the synchronized block, however, then you can surround just the "critical section" of the method in the synchronized block, while leaving the rest of the method out of the block.
    If the entire method is part of the critical section, then there effectively is no difference. If that is not the case, then you should use a synchronized block around just the critical section. The more statements you have in a synchronized block, the less overall parallelism you get, so you want to keep those to the minimum.

    What is difference between ArrayList and Vector ?

    1. The Vector class is synchronized, the ArrayList is not.
    2. ArrayList is fast than the Vector.