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