Tuesday, 19 April 2011

What are the standard actions available in JSP?

The standard actions available in JSP are as follows:
<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.

Why is it not a good practice to create HttpSessions in JSPs by default?

By default, JSP files create HttpSessions. This is in compliance with J2EETM to facilitate the use of JSP implicit objects, which can be referenced in JSP source and tags without explicit declaration. HttpSession is one of those objects. If you do not use HttpSession in your JSP files then you can save some performance overhead with the following JSP page directive:
<%@ page session="false"%>

Why to use the HttpServlet Init method to perform expensive operations that need only be done once?

 Because the servlet init() method is invoked when servlet instance is loaded, it is the perfect location to carry out expensive operations that need only be performed during initialization. By definition, the init() method is thread-safe. The results of operations in the HttpServlet.init() method can be cached safely in servlet instance variables, which become read-only in the servlet service method.

How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.

<% response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

What are implicit objects? List them?

Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are listed below:

request
response
pageContext
session
application
out
config
page
exception

Difference between forward and sendRedirect?

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

What is a Expression?

An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression.

What is the difference between custom JSP tags and JavaBeans?

In the context of a JSP page, both accomplish similar goals but the differences are:
Custom Tags JavaBeans
Can manipulate JSP content. Can't manipulate JSP content.
Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up. Easier to set up.
Used only in JSPs in a relatively self-contained manner. Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page.

Custom Tags JavaBeans
Can manipulate JSP content. Can't manipulate JSP content.
Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up. Easier to set up.
Used only in JSPs in a relatively self-contained manner. Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page.



Custom Tags JavaBeans
Can manipulate JSP content. Can't manipulate JSP content.
Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up. Easier to set up.
Used only in JSPs in a relatively self-contained manner. Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page.
Custom Tags JavaBeans
Can manipulate JSP content. Can't manipulate JSP content.
Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up. Easier to set up.
Used only in JSPs in a relatively self-contained manner. Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page.
Custom Tags JavaBeans
Can manipulate JSP content. Can't manipulate JSP content.
Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up. Easier to set up.
Used only in JSPs in a relatively self-contained manner. Can be used in both Servlets and JSPs. You can define a bean in one Servlet and use them in another Servlet or a JSP page.

JavaBeans declaration and usage example:
<jsp:useBean id="identifier" class="packageName.className"/>
<jsp:setProperty name="identifier" property="classField" value="someValue" />
<jsp:getProperty name="identifier" property="classField" />
<%=identifier.getclassField() %>

What are custom tags? Explain how to build custom tags?

Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. So basically it is a reusable and extensible JSP only solution. The pre-built tags also can speed up Web development.
Step 1
Create a Custom tag class using only doStartTag()

 package myTagPkg;
  public class MyTag extends TagSupport
   {
    int attr = null;
    public int setAttr(int a ttr){this.attr = a ttr}
    public int getAttr(){return attr;}
    public int doStartTag() throws JspException {
    .......
    return 0;
    }
    public void release(){.....}
   }


Step 2 The Tag library descriptor file (*.tld) maps the XML element names to the tag implementations. The code sample MyTagDesc.tld is shown below:
<taglib>
  <tag>
   <name>tag1</name>
   <tagclass>myTagPkg.MyTag</tagclass>
   <bodycontent>empty</bodycontent>
   <attribute>
    <name>attr</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
   </attribute>
  </tag>
</taglib>


Step 3
The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library Descriptor) file. The code sample web.xml file is shown below:

 <web-app>
  <taglib>
   <taglib-uri>/WEB-INF/MyTagURI</taglib-uri>
   <taglib-location>/WEB-INF/tags/MyTagDesc.tld</taglib-location>
  </taglib>
 </web-app>

STEP: 4
The JSP file declares and then uses the tag library as shown below:
<%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %>
< myTag:tag1 attr=�abc� />
<taglib>
  <tag>
   <name>tag1</name>
   <tagclass>myTagPkg.MyTag</tagclass>
   <bodycontent>empty</bodycontent>
   <attribute>
    <name>attr</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
   </attribute>
  </tag>
</taglib>

Explain JSP URL mapping? What is URL hiding or protecting the JSP page?

 The JSP resources usually reside directly or under subdirectories (e.g. myPath) of the document root, which are directly accessible to the user through the URL. If you want to protect your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files, css (cascading style sheets) files, Java Script files, pdf files, image files, html files etc from direct access. The request should be made to a servlet who is responsible for authenticating and authorising the user before returning the protected JSP page or its resources.

Is JSP variable declaration thread safe?

No. The declaration of variables in JSP is not thread-safe, because the declared variables end up in the generated Servlet as an instance variable, not within the body of the _jspservice() method.
The following declaration is not thread safe: because these are declarations, and will only be evaluated once when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets have the local scope and not shared.
<% int a = 5 %>;

What are different type of scripting elements?

Declaration Element: is the embedded Java declaration statement, which gets inserted at the Servlet class level.
<%! Calendar c = Calendar.getInstance(); %>
Important: declaring variables via this element is not thread-safe, because this variable ends up in the generated Servlet as an instance variable, not within the body of the _jspservice() method. Ensure their access is either read-only or synchronized.

Expression Element: is the embedded Java expression, which gets evaluated by the service method.
<%= new Date()>

Scriptlet Elements: are the embedded Java statements, which get executed as part of the service method.
(Note: Not recommended to use Scriptlet elements because they don’t provide reusability and maintainability. Use custom tags (like JSTL, JSF tags, etc) or beans instead).
<%
//Java codes
String userName=null;
userName=request.getParameter("userName");
%>


Action Elements: A JSP element that provides information for execution phase.
<jsp:useBean id="object_name" class="class_name"/>
<jsp:include page="scripts/login.jsp" />

Directive Elements: A JSP element that provides global information for the translation phase.
<%@ page import=�java.util.Date� %>
<%@ include file=�myJSP� %>
<%@ taglib uri=�tagliburi� prefix=�myTag�%>

Explain the life cycle methods of a JSP?

Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls this method for each request.
Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.

What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation phase?

JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(“….. �) statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.

The JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution phase (run time) where they can handle requests and send response.

Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On large production sites, or in situations involving complicated JSP files, compilation may cause unacceptable delays to users first accessing the JSP page. The JSPs can be compiled ahead of time (ie precompiled) using application server tools/settings or by writing your own script.

What are the advantages of immutability?

The advantages are:
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
  4) The best use of the immutable objects is as the keys of a map.

Which classes in java are immutable?

All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger

Immutable objects are automatically thread-safe –true/false?

True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.

How to create an immutable class?


To create an immutable class following steps should be followed:
  1. Create a final class.
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private
  4. Do not provide any setters for these properties.
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    1. Don't provide methods that modify the mutable objects.
    2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
E.g.
public final class FinalPersonClass {

      private final String name;
      private final int age;
     
      public FinalPersonClass(final String name, final int age) {
            super();
            this.name = name;
            this.age = age;
      }
      public int getAge() {
            return age;
      }
      public String getName() {
            return name;
      }
     
}
Q3) Immutable objects are automatically thread-safe –true/false?
Ans) True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
To create an immutable class following steps should be followed:
  1. Create a final class.
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private
  4. Do not provide any setters for these properties.
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    1. Don't provide methods that modify the mutable objects.
    2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
E.g.
public final class FinalPersonClass {

      private final String name;
      private final int age;
     
      public FinalPersonClass(final String name, final int age) {
            super();
            this.name = name;
            this.age = age;
      }
      public int getAge() {
            return age;
      }
      public String getName() {
            return name;
      }
     
}
Q3) Immutable objects are automatically thread-safe –true/false?
Ans) True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
To create an immutable class following steps should be followed:
  1. Create a final class.
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private
  4. Do not provide any setters for these properties.
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    1. Don't provide methods that modify the mutable objects.
    2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
E.g.
public final class FinalPersonClass {

      private final String name;
      private final int age;
     
      public FinalPersonClass(final String name, final int age) {
            super();
            this.name = name;
            this.age = age;
      }
      public int getAge() {
            return age;
      }
      public String getName() {
            return name;
      }
     
}

How to create an immutable class?

To create an immutable class following steps should be followed:
  1. Create a final class.
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private
  4. Do not provide any setters for these properties.
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    1. Don't provide methods that modify the mutable objects.
    2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
E.g.
public final class FinalPersonClass {

      private final String name;
      private final int age;
     
      public FinalPersonClass(final String name, final int age) {
            super();
            this.name = name;
            this.age = age;
      }
      public int getAge() {
            return age;
      }
      public String getName() {
            return name;
      }
     
}

What is an immutable class?

Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class

To serialize an array or a collection all the members of it must be serializable. True /False?

true.

If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from super class after deserialization?

The values of the instance variables inherited from superclass will be reset to the values they were given during the original construction of the object as the non-serializable super-class constructor will run.E.g.
public class ParentNonSerializable {
    int noOfWheels;
   
    ParentNonSerializable(){
        this.noOfWheels = 4;
    }
   
}


public class ChildSerializable extends ParentNonSerializable implements Serializable {
  
    private static final long serialVersionUID = 1L;
    String color;


    ChildSerializable() {
        this.noOfWheels = 8;
        this.color = "blue";
    }
}


public class SubSerialSuperNotSerial {

    public static void main(String [] args) {

        ChildSerializable c = new ChildSerializable();
        System.out.println("Before : - " + c.noOfWheels + " "+ c.color);
        try {
        FileOutputStream fs = new FileOutputStream("superNotSerail.ser");
        ObjectOutputStream os = new ObjectOutputStream(fs);
        os.writeObject(c);
        os.close();
        } catch (Exception e) { e.printStackTrace(); }

        try {
        FileInputStream fis = new FileInputStream("superNotSerail.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        c = (ChildSerializable) ois.readObject();
        ois.close();
        } catch (Exception e) { e.printStackTrace(); }
        System.out.println("After :- " + c.noOfWheels + " "+ c.color);
        }

}
Result on executing above code –
Before : - 8 blue
After :- 4 blue
The instance variable ‘noOfWheels’ is inherited from superclass which is not serializable. Therefore while restoring it the non-serializable superclass constructor runs and its value is set to 8 and is not same as the value saved during serialization which is 4.

How can one customize the Serialization process? or What is the purpose of implementing the writeObject() and readObject() method?

When you want to store the transient variables state as a part of the serialized object at the time of serialization the class must implement the following methods –
private void wrtiteObject(ObjectOutputStream outStream)
{
//code to save the transient variables state as a part of serialized object
}
private void readObject(ObjectInputStream inStream)
{
//code to read the transient variables state and assign it to the de-serialized object
}
e.g.
public class TestCustomizedSerialization implements Serializable{

    private static final long serialVersionUID =-22L;
    private String noOfSerVar;
    transient private int noOfTranVar;

    TestCustomizedSerialization(int noOfTranVar, String noOfSerVar) {
        this.noOfTranVar = noOfTranVar;
        this.noOfSerVar = noOfSerVar;
    }

    private void writeObject(ObjectOutputStream os) {

     try {
     os.defaultWriteObject();
     os.writeInt(noOfTranVar);
     } catch (Exception e) { e.printStackTrace(); }
     }

     private void readObject(ObjectInputStream is) {
     try {
     is.defaultReadObject();
     int noOfTransients = (is.readInt());
     } catch (Exception e) {
         e.printStackTrace(); }
     }

     public int getNoOfTranVar() {
        return noOfTranVar;
    }
   
}
The value of transient variable ‘noOfTranVar’ is saved as part of the serialized object manually by implementing writeObject() and restored by implementing readObject().
The normal serializable variables are saved and restored by calling defaultWriteObject() and defaultReadObject()respectively. These methods perform the normal serialization and de-sirialization process for the object to be saved or restored respectively.

Does the order in which the value of the transient variables and the state of the object using the defaultWriteObject() method are saved during serialization matter?

 Yes.  As while restoring the object’s state the transient variables and the serializable variables that are stored must be restored in the same order in which they were saved.

What will be the value of transient variable after de-serialization?

It’s default value.
e.g. if the transient variable in question is an int, it’s value after deserialization will be zero.

public class TestTransientVal implements Serializable{
   
    private static final long serialVersionUID = -22L;
    private String name;
    transient private int age;
    TestTransientVal(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public static void main(String [] args) {
        TestTransientVal c = new TestTransientVal(1,"ONE");
        System.out.println("Before serialization: - " + c.name + " "+ c.age);
        try {
        FileOutputStream fs = new FileOutputStream("testTransients.ser");
        ObjectOutputStream os = new ObjectOutputStream(fs);
        os.writeObject(c);
        os.close();
        } catch (Exception e) { e.printStackTrace(); }


        try {
        FileInputStream fis = new FileInputStream("testTransients.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        c = (TestTransientVal) ois.readObject();
        ois.close();
        } catch (Exception e) { e.printStackTrace(); }
        System.out.println("After de-serialization:- " + c.name + " "+ c.age);
        }

}


Result of executing above piece of code –
Before serialization: - Value of non-transient variable ONE Value of transient variable 1
After de-serialization:- Value of non-transient variable ONE Value of transient variable 0

Explanation –
The transient variable is not saved as the part of the state of the serailized variable, it’s value after de-serialization is it’s default value.

What is a transient variable?

These variables are not included in the process of serialization and are not the part of the object’s serialized state.

Are the static variables saved as the part of serialization?

No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object.

What happens if an object is serializable but it includes a reference to a non-serializable object?

If you try to serialize an object of a class which implements serializable, but the object includes a reference to an non-serializable class then a ‘NotSerializableException’ will be thrown at runtime.
e.g. public class NonSerial {
    //This is a non-serializable class
}

public class MyClass implements Serializable{
    private static final long serialVersionUID = 1L;
    private NonSerial nonSerial;
    MyClass(NonSerial nonSerial){
        this.nonSerial = nonSerial;
    }
    public static void main(String [] args) {
        NonSerial nonSer = new NonSerial();
        MyClass c = new MyClass(nonSer);
        try {
        FileOutputStream fs = new FileOutputStream("test1.ser");
        ObjectOutputStream os = new ObjectOutputStream(fs);
        os.writeObject(c);
        os.close();
        } catch (Exception e) { e.printStackTrace(); }
        try {
        FileInputStream fis = new FileInputStream("test1.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        c = (MyClass) ois.readObject();
        ois.close();
            } catch (Exception e) {
            e.printStackTrace();
          }
    }
}
On execution of above code following exception will be thrown  –
java.io.NotSerializableException: NonSerial
            at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java)

What happens if the object to be serialized includes the references to other serializable objects?

If the object to be serialized includes the references to other objects whose class implements serializable then all those object’s state also will be saved as the part of the serialized state of the object in question. The whole object graph of the object to be serialized will be saved during serialization automatically provided all the objects included in the object’s graph are serializable.

Do we need to implement any method of Serializable interface to make an object serializable?

 No. Serializable is a Marker Interface. It does not have any methods.

Other than Serialization what are the different approach to make object Serializable?

 Besides the Serializable interface, at least three alternate approaches can serialize Java objects:

1)For object serialization, instead of implementing the Serializable interface, a developer can implement the Externalizable interface, which extends Serializable. By implementing Externalizable, a developer is responsible for implementing the writeExternal() and readExternal() methods. As a result, a developer has sole control over reading and writing the serialized objects.
2)XML serialization is an often-used approach for data interchange. This approach lags runtime performance when compared with Java serialization, both in terms of the size of the object and the processing time. With a speedier XML parser, the performance gap with respect to the processing time narrows. Nonetheless, XML serialization provides a more malleable solution when faced with changes in the serializable object.
3)Finally, consider a "roll-your-own" serialization approach. You can write an object's content directly via either the ObjectOutputStream or the DataOutputStream. While this approach is more involved in its initial implementation, it offers the greatest flexibility and extensibility. In addition, this approach provides a performance advantage over Java serialization.

What is the need of Serialization?

The serialization is used :-
  • To send state of one or more object’s state over the network through a socket.
  • To save the state of an object in a file.
  • An object’s state needs to be manipulated as a stream of bytes.

What is use of serialVersionUID?

During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:

  • Add fields
  • Change a field from static to non-static
  • Change a field from transient to non-transient
  • Add classes to the object tree
List of incompatible changes:
  • Delete fields
  • Change class hierarchy
  • Change non-static to static
  • Change non-transient to transient
  • Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly metion the suid using the statement:

private final static long serialVersionUID = <integer value>


then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

What is Serialization?

Serializable is a marker interface. When an object has to be transferred over a network ( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs to implement Serializable interface. Implementing this interface will allow the object converted into bytestream and transfer over a network.

Can an anonymous class implement an interface and also extend a class at the same time?

No. An anonymous class can either extend a class or implement a single interface. If the anonymous class is extending a class then it becomes the implementer of all the interfaces implemented by its superclass automatically.

Can an anonymous class implement multiple interfaces directly?

No. An anonymous class can implement only one interface. If the anonymous class is extending a class then it becomes the implementer of all the interfaces implemented by its superclass automatically.

Can an anonymous class define method of its own?

Yes. But there will be no way by which the methods defined in the anonymous class which are not present in its superclass be invoked. As only those methods which are defined in the suprclass which the anonymous class extends be invoked defining the methods in the anonymous class will be of no use.

Can a method which is not in the definition of the superclass of an anonymous class be invoked on that anonymous class reference?

 No. There is no this reference available in the static method .The static method class can not have access to any members of the outer class other than static members.

Can a local class declared inside a static method have access to the instance members of the outer class?

 No. There is no this reference available in the static method .The static method class can not have access to any members of the outer class other than static members.

Which modifiers can be applied to the method local inner class?

Only abstract or final keyword isallowed.

Can a method local inner class access the local final variables?Why?

Yes. Because the final variables are stored on heap and they live as long as the method local inner class object may live.

Can the method local inner class object access method’s local variables?

No, a method local inner class object can not access the method local variable.
Reason: The local variables are not guaranteed to live as long as the local inner class object. The method local variable live on stack and exist only till the method lives, their scope is limited only code inside the method they are declared in. But the local inner class object created within the method lives on heap and it may exist even after the method ends if in case the reference of this local inner class is passed into some other code and is stored in an instance variable. So we can not be sure that the local variables will live till the method local inner class object lives, therefore the method local inner class object can not access the method local variable. To access the method local variables, the variable has to be declared as final.

Which modifiers can be applied to the inner class?

Following are modifiers that can be applied to the inner:
     public
     private
     abstract
     final
     protected
     strictfp
     static – turns the inner class into static nested class.

How to refer to the outer this i.e. outer class’s current instance from inside the inner class?

The outer this reference i.e. the outer class’ current instance’ reference can be refered using ‘OuterClassName.this’. E.g
 class EnclosingOuter {
           class Inner{
          System.out.println(“Inner class reference is “ + this); // inner class instance

System.out.println(“Outer class reference is “ + EnclosingOuter.this); //outer class instance
 }
}
To refer the inner class reference from within the inner class use this.

How to create an inner class instance from outside the outer class instance code?

To create an instance of the inner class you must have the instance of its enclosing class.
e.g. class EnclosingOuter {
class Inner{ }
}
 To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}

2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }

How to access the inner class from code within the outer class?

The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
           Inner in = new Inner();
System.out.println(“No Of Inner classes is : “+ in.getNoOfClassesFromOuter());
}
class Inner{

public int getNoOfClassesFromOuter(){ return noInnerClass; }

}
Here the method getNoOfInnerClasses() is called on the outer class’s instance through this outer class instance the inner class instance in is created.

If you compile a file containing inner class how many .class files are created and what are all of them accessible in usual way?

 If a inner class enclosed with an outer class is compiled then one .class file for each inner class an a .class file for the outer class is created. e.g.
class EnclosingOuter {
    class Inner{ }
 }
 If you compile the above code with command
% javac EnclosingOuter.java
Two files
EnclosingOuter.class
EnclosingOuter$Inner.class

will be created. Though a separate inner class file is generated, the inner class file is not accessible in the usual way like,
% java EnclosingOuter$Inner

What are different types of anonymous classes?

 Plain old anonymous class type one
e.g.
class superClass{
         void doSomething() {
                  System.out.println(“Doing something in the Super class”);
         }
 }

class hasAnonymous{
               superClass anon = new superClass(){
                       void doSomething() {
                               System.out.println(“Doing something in the Anonymous class”);
                     }
            };
Here anon is the reference which is of type superClass which is the class extended by the anonymous class i.e. superclass of the anonymous class. The method doSomething() is the super class method overridden by the anonymous class.
2) Plain old anonymous class type two

interface Eatable{
       public void prepareSweets();
 }
class serveMeal{
 Eatable food = new Eatable(){
              public void prepareSweets(){ //come implementation code goes here }
     };
}
 food is reference variable of type Eatable interface which refers to the anonymous class which is the implementer of the interface Eatable. The anonymous implementer class of the interface Eatable implements its method prepareSweets() inside it.
3) Argument defined anonymous class – e.g.

interface Vehicle {
   void getNoOfWheels();
 }
class Car {
       void getType(Vehical v) { }
}
class BeautifulCars {
        void getTheBeautifilCar() {
             Car c = new Car ();
             c.getType (new Vehicle () {
                          public void getNoOfWheels () {
                                 System.out.println("It has four wheels");
                          }
             });
        }
 }
 Anonymous class is defined as the argument of the method getTheBeautifilCar(), this anonymous class is the implementer of the interface Vehicle. The method of class Car getTheBeautifilCar() expects the argument as an object of type Vehicle. So first we create an object of Car referenced by the variable ‘c’. On this object of Car we call the method getTheBeautifilCar() and in the argument we create an anonymous class in place which is the implementer of interface Vehicle hence of type Vehicle.

What are disadvantages of using inner classes?

1. Using inner class increases the total number of classes being used by the application. For all the classes created by JVM and loaded in the memory, jvm has to perform some tasks like creating the object of type class. Jvm may have to perform some routine tasks for these extra classes created which may result slower performance if the application is using more number of inner classes. 2. Inner classes get limited support of ide/tools as compared to the top level classes, so working with the inner classes is sometimes annoying for the developer.

What are the advantages of Inner classes?

The embedding of inner class into the outer class in the case when the inner class is to be used only by one class i.e. the outer class makes the package more streamlined. Nesting the inner class code where it is used (inside the outer class) makes the code more readable and maintainable.
The inner class shares a special relationship with the outer class i.e. the inner class has access to all members of the outer class and still have its own type is the main advantages of Inner class. Advantage of inner class is that they can be hidden from the other classes in the same package and still have the access to all the members (private also) of the enclosing class. So the outer class members which are going to be used by the inner class can be made private and the inner class members can be hidden from the classes in the same package. This increases the level of encapsulation.
If a class A is written requires another class B for its own use, there are two ways to do this. One way is to write a separate class B or to write an inner class B inside class A. Advantage of writing the inner class B in the class A is you can avoid having a separate class. Inner classes are best used in the event handling mechanism and to implement the helper classes. The advantage of using inner class for event handling mechanism is that the use of if/else to select the component to be handled can be avoided. If inner classes are used each component gets its own event handler and each event handler implicitly knows the component it is working for. e.g.

Button btn1 = new Button("Submit");
Btn.addActionListener(new ActionListener(){/br>

Public void actionPerformed(ActionEvent ae){ submitClicked(); }
} );
The advantage of using static nested class is that to instantiate a static nested class you need not create an instance of the enclosing class which reduces the number of objects the application creates at runtime.

Does a static nested class have access to the enclosing class' non-static methods or instance variables?

No .

What are non static inner classes?

The different type of static inner classes are: Non - static inner classes – classes associated with the object of the enclosing class. Member class - Classes declared outside a function (hence a "member") and not declared "static".
The member class can be declared as public, private, protected, final and abstract. E.g.

public class InnerClass {
class MemberClass {
public void method1() { }
}
}
Method local class – The inner class declared inside the method is called method local inner class. Method local inner class can only be declared as final or abstract. Method local class can only access global variables or method local variables if declared as final
public class InnerClass {
int i = 9;
public void method1() {
final int k = 6;
class MethodLocal {
MethodLocal() {
System.out.println(k + i);
}
}
}
}

Anonymous inner class - These are local classes which are automatically declared and instantiated in the middle of an expression.  Also, like local classes, anonymous classes cannot be public, private, protected, or static. They can specify arguments to the constructor of the superclass, but cannot otherwise have a constructor. They can implement only one interface or extend a class.
Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
Also, like local classes, anonymous classes cannot be public, private, protected, or static

Some examples:
public class MyFrame extends JFrame {
JButton btn = new JButton();
MyFrame() {
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
}

Anonymous class used with comparator
List<Parent> l = new ArrayList<Parent>();
l.add(new Parent(2));
l.add(new Parent(3));
Collections.sort(l, new Comparator() {
public int compare(Object o1, Object o2) {
Parent prt1 = (Parent) o1;
Parent prt2 = (Parent) o2;

if (prt1.getAge() > prt2.getAge()) {
return -1;
}else if(prt1.getAge()<prt2.getAge()) {

return 1;
} else {

return 0;
}
}
});

What is static member class?

 A static member class behaves much like an ordinary top-level class, except that it can access the static members of the class that contains it. The static nested class can be accessed as the other static members of the enclosing class without having an instance of the outer class. The static class can contain non-static and static members and methods. public class InnerClass {
      static class StaticInner {
            static int i = 9;
            int no = 6;

            private void method() {}
            public void method1() {}
            static void method2() {}
            final void method3() {}
      }
}

      The static inner class can be accessed from Outer Class in the following manner:
InnerClass.StaticInner staticObj= new InnerClass. StaticInner ();

No outer class instance is required to instantiate the nested static class because the static class is a static member of the enclosing class.

What are the different types of inner classes?

There are two main types of inner classes –
  • Static member class
  • Inner class
    • Member class
    • Anonymous class
    • Local class

What is an inner class?

Inner class is a class defined inside other class and act like a member of the enclosing class.

Which design pattern Iterator follows?

What is WeakHashMap?

A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently than other Map implementations.

What is identityHashMap?

The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap

HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.

Which data structure HashSet implements

HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key in hashmap with null as value.

Which is faster to iterate LinkedHashSet or LinkedList?

LinkedList.

What is ConcurrentHashMap?

A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

How to make a List (ArrayList,Vector,LinkedList) read only?

A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

How to sort list of strings - case insensitive?

using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Can a null element added to a Treeset or HashSet?

A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.

How to sort list in reverse order?

To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
List list = new ArrayList();
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)

What is difference between iterator access and index access?

Index based access allow access of the element directly on the basis of index. The cursor of the datastructure can directly goto the 'n' location and get the element. It doesnot traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.

Why is it preferred to declare: List list = new ArrayList(); instead of ArrayList = new ArrayList();

It is preferred because:
  1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
    When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible

Is it better to have a HashMap with large number of records or n number of small hashMaps?

It depends on the different scenario one is working on:
1) If the objects in the hashMap are same then there is no point in having different hashmap as the traverse time in a hashmap is invariant to the size of the Map.
2) If the objects are of different type like one of Person class , other of Animal class etc then also one can have single hashmap but different hashmap would score over it as it would have better readability.

Which design pattern Iterator follows?

It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation. Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.

Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it.

For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?

 It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.

When to use ArrayList or LinkedList ?

Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.

What is difference between Arrays and ArrayList ?

Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :
    1. int [] intArray= new int[6];
    2. intArray[7]   // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
  1. Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
  1. ArrayList is one dimensional but array can be multidimensional.
            int[][][] intArray= new int[3][2][1];   // 3 dimensional array    
  1. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.

What is difference between List and a Set?

1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)

Which all classes implement Set interface?

A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

What are the classes implementing List interface?

There are three classes that implement List interface:
1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.

2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.

3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.

What is difference between HashMap and HashTable?

Both collections implements Map. Both collections store value as key-value pairs. The key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Fail-safe - “if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException�

3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.

If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?

1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
2) Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.

How can Arraylist be synchronized without using Vector?

Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)

What is difference between ArrayList and vector?

1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.
2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

What are the different states of a thread's lifecycle?

The different states of threads are as follows: 1) New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread starts running and the thread is said to be in Running state.
 4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked. 5)      Dead – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

What is a Thread?

In Java, "thread" means two different things:
  • An instance of class java.lang.Thread.
  • A thread of execution.
An instance of Thread is just…an object. Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack—or, to think of it in reverse, one call stack per thread. Even if you don't create any new threads in your program, threads are back there running.
The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main thread. If you looked at the main call stack (and you can, any time you get a stack trace from something that happens after main begins, but not within another thread), you'd see that main() is the first method on the stack— the method at the bottom. But as soon as you create a new thread, a new stack materializes and methods called from that thread run in a call stack that's separate from the main() call stack.