Pages

Wednesday, August 22, 2012

interface-Abstract

Difference Between Interface and Abstract Class

  1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
  2. Variables declared in a Java interface is by default final. An  abstract class may contain non-final variables.
  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
  4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
  5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
  6. A Java class can implement multiple interfaces but it can extend only one abstract class.
  7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
  8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

 

Interface

Java interface

A java class containing all the methods as abstract is called an interface. A method that has no implementation and which is expected to be implemented by a subclass is called an abstract method. Java interface can contain constants. When an interface needs to be instantiated it should be implemented by a class and all its abstract methods should be defined. If all the methods are not implemented in the class then it becomes a java abstract class and so cannot be instantiated. Variables declared in a java interface by default is final

interface interf
{
public void show();
public void display();
}

Filter

What is a filter?

A filter is used to dynamically intercept request and response objects and change or use the data present in them. Filters should be configured in the web deployment descriptor. Filters can perform essential functions like authentication blocking, logging, content display style conversion, etc.

Abstract

What is an abstract method?

A method that has no implementation and which is expected to be implemented by a subclass is called an abstract method.
ex:   public void display();

What is an abstract class?

A class containing atleast one abstract method is called an abstract class. A method that has no implementation and which is expected to be implemented by a subclass is called an abstract method. An Abstract class cannot be instantiated. It is expected to be extended by a subclass. An abstract class may contain static variables declared. Any class with an abstract method must be declared explicitly as abstract. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

ex:
public abstract class AAA
{
}

Tuesday, August 14, 2012

UsingEnums Example

public class UsingEnums {

    private UsingEnums(Weekdays testday) {

        switch
         (testday) {
            case Saturday:
            case Sunday:
                System.out.println("It's the weekend!");
                break;
            case Wednesday:
                System.out.println("It's Humpday!");
                break;
            case Friday:
                System.out.println("TGIF!");
                break;
            default:
                System.out.println("Backto work!");
        }
    }

    public enum Weekdays {

        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    };

    public UsingEnums() {
        Weekdays weekDays = null;
        System.out.println(weekDays.Friday);
    }

    public static void main(String[] args) {
        UsingEnums myUE = new UsingEnums();
        UsingEnums myUE1 = new UsingEnums(Weekdays.Monday);
    }
}

StringBuilder Example

public class StringBuilder_IN {

    public static void main(String args[]) {
        String myString = "How";
        StringBuilder myStrBldr = new StringBuilder("How");
        myString += " now";
        myString += " Brown";
        myString += " Cow?";
        myStrBldr.append(" now");
        myStrBldr.append(" Brown");
        myStrBldr.append(" Cow?");
        System.out.println("String= " + myString);
        System.out.println("StringBuilder= " + myStrBldr);
    }
}

StaticImportDemo

public class StaticImportDemo {

    public static void main(String[] args) {
        String intValue = "123";
        String dblValue = "567.80";
        double resultValue = 0;
        try {
            resultValue = parseInt(intValue) + parseDouble(dblValue);
            System.out.println("resultValueis " + resultValue);
        }
        catch (NumberFormatException e) {
            System.out.println("EitherintValueor dblValuenot numeric");
        }
    }
}

Scanner Example

public class NewClass {

    public static void main(String args[]) {
        String lastName;
        System.out.print("Pleaseenter your last name => ");
        Scanner fromkeyboard = new Scanner(System.in);
        lastName = fromkeyboard.next();
    }
}

Formatter Example

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        double balance = 1234.56;
        System.out.format("Balanceis $%,6.2f", balance);
        Formatter myUSformat = new Formatter();
        Formatter myFRformat = new Formatter();
        String balUS = myUSformat.format("Balanceis $%,6.2f", balance).toString();
        String balFR = myFRformat.format(Locale.ITALY, "Balance is $%,6.2f", balance).toString();
        System.out.println("\nUS" + balUS);
        System.out.println("FRANCE" + balFR);
    }
}

Monday, August 13, 2012

Generic_Example

public class Generic_IN
{
    public static void main(String args[])
    {
       ArrayList newStyle= new ArrayList();
       newStyle.add(new String("abc0"));
     //  newStyle.add(new Int(10));
       newStyle.add("abc2");
       newStyle.add("101");

       Iterator it = newStyle.iterator();

       while(it.hasNext())
       {
           System.out.println(it.next());
       }



       
    }

}

New For example

public class For_IN
{
    public static void main(String args[])
    {
        String[] str = new String[5];
        str[0]="abc0";
        str[1]="abc1";
        str[2]="abc2";
        str[3]="abc3";
        str[4]="abc4";

        for(String newstr : str)
        {
            System.out.println(newstr+" ;");
        }

        int[] intary = {10,11,12,13};
        System.out.println(Arrays.toString(intary));

    }

}

AutoBoxing_Example

public class AutoBoxing_IN
{
    public static void main(String args[])
    {
        Integer intObject= new Integer(123);
        System.out.println(intObject);
        int intintPrimitive= intObject;
        System.out.println(intintPrimitive);
        double doublePrimitive= 123.45;
        System.out.println(doublePrimitive);
        Double doubleObject= doublePrimitive;
        System.out.println(doubleObject);
    }

}

Thursday, January 12, 2012

OOPs


Brief Introduction to OOP
Object Oriented Programming or OOP is the technique to create programs based on the real world. Unlike procedural programming, here in the OOP programming model programs are organized around objects and data rather than actions and logic. Objects represent some concepts or things and like any other objects in the real Objects in programming language have certain behavior, properties, type, and identity. In OOP based language the principal aim is to find out the objects to manipulate and their relation between each other. OOP offers greater flexibility and compatibility and is popular in developing larger application. Another important work in OOP is to classify objects into different types according to their properties and behavior. So OOP based software application development includes the analysis of the problem, preparing a solution, coding and finally its maintenance.
Java is a object oriented programming  and to understand the functionality of OOP in Java, we first need to understand several fundamentals related to objects. These include class, method, inheritance, encapsulation, abstraction, polymorphism etc.
Class - It is the central point of OOP and that contains data and codes with behavior. In Java everything happens within class and it describes a set of objects with common behavior. The class definition describes all the properties, behavior, and identity of objects present within that class. As far as types of classes are concerned, there are predefined classes in languages like C++ and Pascal. But in Java one can define his/her own types with data and code.  
Object - Objects are the basic unit of object orientation with behavior, identity. As we mentioned above, these are part of a class but are not the same. An object is expressed by the variable and methods within the objects. Again these variables and methods are distinguished from each other as instant variables, instant methods and class variable and class methods. 
Methods -  We know that a class can define both attributes and behaviors. Again attributes are defined by variables and behaviors are represented by methods. In other words, methods define the abilities of an object. 
Inheritance - This is the mechanism of organizing and structuring software program. Though objects are distinguished from each other by some additional features but there are objects that share certain things common. In object oriented programming classes can inherit some common behavior and state from others. Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition. This saves work as the special class inherits all the properties of the old general class and as a programmer you only require the new features. This helps in a better data analysis, accurate coding and reduces development time. 
Abstraction - The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface). 
Encapsulation - This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component. In Java there are four different terms used for hiding data constructs and these are public, private, protected and package. As we know an object can associated with data with predefined classes and in any application an object can know about the data it needs to know about. So any unnecessary data are not required by an object can be hidden by this process. It can also be termed as information hiding that prohibits outsiders in seeing the inside of an object in which abstraction is implemented.  
Polymorphism - It describes the ability of the object in belonging to different types with specific behavior of each type. So by using this, one object can be treated like another and in this way it can create and define multiple level of interface. Here the programmers need not have to know the exact type of object in advance and this is being implemented at runtime.

Monday, January 9, 2012

Draw and Drag in JavaScript

    <HTML>
    <HEAD>
    <META http-equiv=imagetoolbar content=no>
    <TITLE>
    
    </TITLE>
    <STYLE>
    #rubberBand {
    position: absolute;
    visibility: hidden;
    width: 0px; height: 0px;
    border: 2px solid red;
    }
    </STYLE>
<script language="JavaScript1.2">
<!--

var ie=document.all;
var nn6=document.getElementById&&!document.all;

var isdrag=false;
var x,y;
var dobj;

function movemouse(e)
{
  if (isdrag)
  {
    dobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
    dobj.style.top  = nn6 ? ty + e.clientY - y : ty + event.clientY - y;
    return false;
  }
}

function selectmouse(e)
{
  var fobj       = nn6 ? e.target : event.srcElement;
  var topelement = nn6 ? "HTML" : "BODY";

  while (fobj.tagName != topelement && fobj.className != "dragme")
  {
    fobj = nn6 ? fobj.parentNode : fobj.parentElement;
  }

  if (fobj.className=="dragme")
  {
    isdrag = true;
    dobj = fobj;
    tx = parseInt(dobj.style.left+0);
    ty = parseInt(dobj.style.top+0);
    x = nn6 ? e.clientX : event.clientX;
    y = nn6 ? e.clientY : event.clientY;
    document.onmousemove=movemouse;
    return false;
  }
}

document.onmousedown=selectmouse;
document.onmouseup=new Function("isdrag=false");

//-->
</script>


    
    </HEAD>
    <BODY>
    <img name="myImage"  id="myImage" src="Winter.jpg" height=100%
    width=100%>
    
    
    <DIV ID="rubberBand" class="dragme"></DIV>
    
    <SCRIPT>
    
    var IMG;
    
    function startRubber (evt) {
    if (document.all) {
    // IE
    var r = document.all.rubberBand;
    r.style.width = 0;
    r.style.height = 0;
    r.style.pixelLeft = event.x;
    r.style.pixelTop = event.y;
    r.style.visibility = 'visible';
    IMG.ondragstart = cancelDragDrop; // otherwise IE will try to drag the image
    }
    else if (document.getElementById) {
    // firefox
    evt.preventDefault();
    var r = document.getElementById('rubberBand');
    r.style.width = 0;
    r.style.height = 0;
    r.style.left = evt.clientX + 'px';
    r.style.top = evt.clientY + 'px';
    r.style.visibility = 'visible';
    r.onmouseup = stopRubber;
    }
    IMG.onmousemove = moveRubber;
    }
    function moveRubber (evt) {
    if (document.all) { // IE
    var r = document.all.rubberBand;
    r.style.width = event.x - r.style.pixelLeft;
    r.style.height = event.y - r.style.pixelTop;
    }
    else if (document.getElementById) { // firefox
    var r = document.getElementById('rubberBand');
    r.style.width = evt.clientX - parseInt(r.style.left);
    r.style.height = evt.clientY - parseInt(r.style.top);
    }
    return false; // otherwise IE won't fire mouseup :/
    }
    function stopRubber (evt) {
    IMG.onmousemove = null;
    }
    
    function cancelDragDrop()
    {
    window.event.returnValue = false;
    }
    
    IMG = document.getElementById('myImage');
    IMG.onmousedown = startRubber;
    IMG.onmouseup = stopRubber;
    
    </SCRIPT>
    </BODY>
    </HTML>
    

Tuesday, January 3, 2012

Struts Flow


Steps 1. 
ActionServlet 
The central component of the Struts Controller is the ActionServlet. It is 
a concrete class and extends the javax.servlet.HttpServlet. It performs 
two important things. 
On startup, its reads the Struts Configuration file and loads it into memory in 
the init() method. 
In the doGet() and doPost() methods, it intercepts HTTP request and 
handles it appropriately. 

In the web.xml 

 
action 
org.apache.struts.action.ActionServlet 
 
 
config 
/WEB-INF/struts-config.xml 
 
1 
 

 
action 
*.do 
 

If the user types http://localhost:8080/App1/submitDetails.do in the 
browser URL bar. Server will call ActionServlet class because in the url-pattern the mapping is 
*.do. Any *.do will call ActionServlet class. 
ActionServlet calls the process() method of RequestProcessor class 

Step 2. 
ActionServlet calls the process() method of RequestProcessor class. 
The RequestProcessor first retrieves appropriate XML block for 
the URL from struts-config.xml. This XML block is referred to as 
ActionMapping in Struts terminology. In fact there is a class called 
ActionMapping in org.apache.struts.action package. 
ActionMapping is the class that does what its name says ? it holds the mapping 
between a URL and Action. 

A sample ActionMapping from struts-config.xml 

 

type="mybank.example.CustomerAction" 
name="CustomerForm" 
scope="request" 
validate="true" 
input="CustomerDetailForm.jsp"> 

path="ThankYou.jsp" 
redirect=?true?/> 
 
 

Step 3. 

The RequestProcessor looks up the configuration file for the URL 
pattern /submitDetails. and finds the XML block (ActionMapping) shown above. 
The type attribute tells Struts which Action class has to be instantiated. 

Step 4. 
The RequestProcessor instantiates the CustomerForm and puts 
it in appropriate scope ? either session or request. The RequestProcessor 
determines the appropriate scope by looking at the scope attribute in the same 
ActionMapping. 

Step 5. 
Next, RequestProcessor iterates through the HTTP request parameters 
and populates the CustomerForm properties of the same name as the HTTP 
request parameters using Java Introspection. 

Step 6. 
Next, the RequestProcessor checks for the validate attribute in the 
ActionMapping. If the validate is set to true, the RequestProcessor invokes 
the validate() method on the CustomerForm instance. This is the method 
where you can put all the html form data validations. If any error then 
RequestProcessor checks for the input attribute in the ActionMapping 
and forward to page mentioned in the input tag. 
If no error in validate() method then continue. 

Step 7. 

The RequestProcessor instantiates the Action class specified in the 
ActionMapping (CustomerAction) and invokes the execute() method on 
the CustomerAction instance. The signature of the execute method is as 
follows. 
public ActionForward execute(ActionMapping mapping, 
ActionForm form, 
HttpServletRequest request, 
HttpServletResponse response) throws Exception 

The execute() method returns ActionForward. 

ActionForward forward = mapping.findForward(?success?); 
return forward. will forward to ThankYou.jsp. 
ActionForward forward = mapping.findForward(failure); 
return forward. will forward to error.jsp.