Monday, 17 December 2012

Over Loading and overriding

OverLoading :
Method overloading means having two or more methods with the same name but different signatures in the same scope.
These two methods may exist in the same class or anoter one in base class and another in derived class.
   Ex:
  

class Person

{

    private String fName;

    private String lName;

    Person()

    {

        this.fName = "";

        this.lName = "";

    }

    Person(String fName)

    {

        this.fName = fName;

        this.lName = "";

    }

    Person(String fName, String lName)

    {

        this.fName = fName;

        this.lName = lName;

    }

}

In the above example calling the over loaded method as follows
    Person(); /* as a constructor and call method without parameter*/
    Person(userFirstName); /* as a constructor and call method with one parameter(like User's first Name)*/
    Person(userFirstName,userLastName); /*as a constructor and call method with one parameter(like User's first Name)*/
When you have required same reason that take different signatures, but conceptually do the same thing.
   
Overriding:
Method overriding means having a different implementation of the same method in the inherited class.
These two methods would have the same signature, but different implementation.
One of these would exist in the base class and another in the derived class. These cannot exist in the same class.


In a derived class, if you include a method definition that has the same name and exactly the same number and types of
parameters as a method already defined in the base class, this new definition replaces the old definition of the method.

Explanation

A subclass inherits methods from a superclass.
Sometimes, it is necessary for the subclass to modify the methods defined in the superclass. This is referred to as method overriding.
The following example demonstrates method overriding.

class Circle
{

    //declaring the instance variable

    protected double radius;

    public Circle(double radius)
    {
          this.radius = radius;
    }

    // other method definitions here

    public double getArea()
    {
          return Math.PI*radius*radius;

    }//this method returns the area of the circle

}// end of class circle

When the getArea method is invoked from an instance of the Circle class, the method returns the area of the circle.
The next step is to define a subclass to override the getArea() method in the Circle class. The derived class will be the Cylinder class. The getArea() method in the Circle class computes the area of a circle, while the getArea method in the Cylinder class computes the surface area of a cylinder.

The Cylinder class is defined below.

class Cylinder extends Circle
{

    //declaring the instance variable

    protected double length;

    public Cylinder(double radius, double length)
    {
         super(radius);
         this.length = length;
    }

    // other method definitions here

    public double getArea()
    {
         // method overriden here
         return 2*super.getArea()+2*Math.PI*radius*length;
    }//this method returns the cylinder surface area

}// end of class Cylinder

When the overriden method (getArea) is invoked for an object of the Cylinder class,
 the new definition of the method is called and not the old definition from the superclass(Circle).

instantiate the above two classes as shown below:
Circle myCircle;
myCircle = new Circle(1.20);
Cylinder myCylinder;
myCylinder = new Cylinder(1.20,2.50);

Saturday, 1 December 2012

Collection Important questions

Convert ArrayList to String 

Here is the simple exam how we can convert an array list to string 
import java.util.ArrayList;
import java.util.List;
 
public class Java4s {
 
public static void main(String args[]){
 
    List al = new ArrayList<String>();// creating list
 
    al.add("One");
    al.add("Two");
    al.add("Three");
    al.add("Four");
    al.add("Five");
 
    String[] stringArrayObject = new String[al.size()];// creating string array
    al.toArray(stringArrayObject);//converting list to string array
 
    for(String temp : stringArrayObject)
    System.out.println(temp);
 
}
}
 

Difference between Arraylist and Vector

  • ArrayList and Vector both having same data structure internally, which is Array
  • Vector is by default synchronized, means at a time only one thread can access its methods from out side, where as ArrayList is non-synchronized means N number of threads can access at a time
  • But we can make ArrayList as synchronized by using Collections class, see it bellow
  • Both Vector and ArrayList  have capability to re-size dynamically, means Vector will Doubles the size of its array when its size increased, but ArrayList increased by Half only

    How to make ArrayList Synchronized

    As we discussed above ArrayList is not synchronized by default, so will see how to make it as Synchronized.
    We have direct method in Collections class to make ArrayList synchronized..

    List li = new ArrayList()
    Collections.synchronizedList(li)

    ArrayList vs Vector Speed and Performance Differences

    Always ArrayList will shows better performance compared to Vector,  except Synchronization both are almost same in their performance.  Vector is Synchronized means thread safe, only 1 thread can access so its very slow compared to ArrayList, because in our real time projects we should not require synchronized methods always.
    What am saying is always try to use ArrayList rather Vector if its not required any Synchronization in your requirements,  even if so you know how to make ArrayList as synchronized right (just like above).
    Let us see how to sort values in java collections, List/ArrayList.  We can achieve this by using Collections class, Collections class contains a method sort(Collection Object), just give your collection object to the sort() method that’s it, consider this example….

    Example:
    mport java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
     
    public class SortCollection {
     
        public static void main(String... args)
        {
     
                List li = new ArrayList();
     
                li.add("India");
                li.add("United States");
                li.add("Malaysia");
                li.add("Australia");
                li.add("Lundon");
     
                Collections.sort(li);// this is the method of collections interface to sort
     
                for(String temp: li)
                {
                    System.out.println("Countries : "+temp);
                }
        }
    }

    Set (Interface)

  • Set is an un-ordered collection which doesn’t allows duplicate (no-duplicate) elements
  • We can iterate the values by calling iterator() method
Set s = new HashSet();
Iterator iter = s.iterator();

List (Interface)

  • List is an ordered collection which allows duplicate elements
  • We can iterate the values by calling iterator() method
List li = new ArrayList();
Iterator iter = li.iterator();

Map (Interface)

  • In Map we used to store the data in key and value pairs, we may have duplicate values but no duplicate keys
  • In Map we don’t have iterator() method, but we can get the keys by calling the method keySet()
    Map m; // insert values
    Set s = m.keySet();
    // Get Map keys into the Set and then iterate this Set object normally
    // m.keySet() returns Set object with Map keys
    Iterator iter = s.iterator();


 

 

 

Sunday, 4 November 2012

JSP



JSP
Here is some basics of jsp technology

JSP Tags
TAGS
Syntax
1.Directive
<%@ Directive %>
1. <%@ page attribute-list %>
2. <%@ include attribute-list %>
3. <%@ taglib attribute-list %>

2.Declaration
<%! Java Declarations %>
3.Expression
<%= An Expression %>
4.Scriptlet
<% Some Java code %>
5.Action
<jsp:actionName />

jsp:include
jsp:forward
jsp:useBean
jsp:setProperty
• jsp:getProperty
jsp:plugin
6.Comment
<%-- Any Text --%>

JSP Life cycle
A JSP page goes through seven phases in its lifetime. These phases are called life-cycle
phases. Although, structurally, a JSP page looks like an HTML page, it actually runs as a servlet.
The JSP engine parses the JSP file and creates a corresponding Java file. This file
declares a servlet class whose members map directly to the elements of the JSP file. The
JSP engine then compiles the class, loads it into memory, and executes it as it would
any other servlet. The output of this servlet is then sent to the client.
You might have observed that when a JSP page is accessed for the first time, the server
is slower in responding than it is in the second, third, and subsequent accesses. This is
because, as we mentioned previously, every JSP page must be converted into an
instance of a servlet class before it can be used to service client requests. For each
request, the JSP engine checks the timestamps of the source JSP page and the corresponding
servlet class file to determine if the JSP page is new or if it has already been
converted into a class file. Therefore, if we modify a JSP page, the whole process of converting
the JSP page into a servlet is performed again.
Phase name
Description
1. Page translation
The page is parsed and a Java file containing the corresponding servlet
is created.

2. Page compilation
The Java file is compiled
3. Load class
The compiled class is loaded
4. Create instance
An instance of the servlet is created.

5. Call jspInit()
This method is called before any other method to allow initialization.

6. Call _jspService()
This method is called for each request.

7. Call jspDestroy()
This method is called when the servlet container decides to take the
servlet out of service.


JSP Page Directive Attribute
A page directive informs the JSP engine about the overall properties of a JSP page.
This directive applies to the entire translation unit and not just to the page in which
it is declared.
  1. Import Attribute:
The import attribute of a page directive is similar to the import statement in a
Java class. For example, if we want to use the Date class of the package java.util,
then we have to either use the fully qualified class name in the code or import it using
the page directive. At the time of translation, the JSP engine inserts an import statement
into the generated servlet for each of the packages declared using this attribute.
Ex:
<%@ page import="java.util.* " %>
<%@ page import="java.io.* " %>
<%@ page import="java.text.* " %>
<%@ page import="com.mycom.*, com.mycom.util.MyClass " %>
  1. Session Attribute:
The session attribute indicates whether the JSP page takes part in an HTTP session.
The default value is true, in which case the JSP engine declares the implicit
variable session. (We will learn more about implicit variables in chapter 11.) If we
do not want the page to participate in a session, then we have to explicitly add the
following line:
<%@ page session="false" %>
  1. errorPage and isErrorPage attributes:
In this approach, a JSP page uses the errorPage attribute to delegate the exception to another JSP page that has the errorhandling code.
Ex:
Hello.jsp
<%@ page errorPage="errorHandler.jsp" %>
<html>
<body>
<%
if (request.getParameter("name")==null)
{
throw new RuntimeException("Name not specified");
}
%>
Hello, <%=request.getParameter("name")%>
</body>
</html>

errorHandler.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Unable to process your request: <%=exception.getMessage()%><br>
Please try again.
</body>
</html>

  1. language and extends attributes:
The language attribute specifies the language used by a page in declarations,
scriptlets, and expressions. The default value is java, which is also the only value
allowed by the JSP Specification 2.0. Needless to say, adding the following line to a
JSP page is redundant:
<%@ page language="java" %>
The extends attribute specifies that the supplied class be used as a base class of the
generated servlet. This is useful only if we want to customize the behavior of the generated
servlet class. The default base class is vendor specific and is designed to work
efficiently with the rest of the framework. Consequently, this attribute is seldom used.
The following line shows the syntax for this attribute:
<%@ page extends="mypackage.MySpecialBaseServlet" %>

  1. buffer and autoFlush attributes:
The buffer attribute specifies the minimum size required by the output buffer that
holds the generated content until it is sent to the client. The default size of the buffer
is JSP engine implementation dependent, but the specification mandates it to be at
least 8kb.
<%@ page buffer="32kb" %>

The autoFlush attribute specifies whether the data in the output buffer should
be sent to the client automatically as soon as the buffer is full. The default value for
autoFlush is true. If it is set to false and the buffer is full, an exception is raised
when we attempt to add more data to the buffer. Here is the syntax for this attribute:
<%@ page autoFlush="false" %>

  1. info attribute:
The info attribute allows us to specify the value of the string returned by the get-
ServletInfo() method of the generated servlet. The following line shows one possible
use:
<%@ page info="This is a sample Page. " %>
The default value of this attribute is implementation dependent.

  1. contentType and pageEncoding attributes
The contentType attribute specifies the MIME type and character encoding of the
output. The default value of the MIME type is text/html; the default value of the
character encoding is ISO-8859-1. The MIME type and character encoding are separated
by a semicolon, as shown here:
<%@ page contentType="text/html;charset=ISO-8859-1" %>

This is equivalent to writing the following line in a servlet:
response.setContentType("text/html;charset=ISO-8859-1");
The pageEncoding attribute specifies the character encoding of the JSP page. The
default value is ISO-8859-1. The following line illustrates the syntax:
<%@ page pageEncoding="ISO-8859-1" %>