Tuesday 12 March 2013

JAVA INTERVIEW QUESTIONS

1)  project related questions
2) what is reenterenet lock
3) diff with syn v/s reenterenent
4) diff between ? and T extend ?
5) diff between lock v/s synchronized
6) diff bet concurrentHashmap ,synchronizedHashmap-- how it works
7) treeset v/s hashset
8) hashing algorithm
9) how to do db table partitioning
10) how can increase performance of db tables...getting records
11) how to merge two sorted int array
12) how to sort int array of n number --- various ways
13) recusive method of factorial/fibonacci
14) deadlock v/s race v/s starvation v/s live lock
15) how to prevent from above condition
16) compile time v/s runtime polymorphism
17) how to prevent child class from serialozation if parent is serlizable
18) JDBC
19) char array given ,how to reverse this array without using api or creating new object
20) concurrent hashmap and its functionality.
21) Reenterent lock and functionality.
22) Singleton pattern implementation.
23) String class implementation.
24) Executor pattern.
25) Final char[] arr = {'a','b','c'}; then char[0] = 'd'; possible or not?
26) Immutable objects.
27) Servlet destroy() call in init() ,wht will happen?
28) struts v/s spring?
29) spring DI
30) Spring MVC flow
31) singleton code
32) hibernate association,configuration
33) immutable class
34) dispatch action
35) empname,mgrname from same emp table which have col empid,name,mgrid
36) used design patterns
37) service locator
38) jndi how confirgured for hibernate
39) webservice-- wsdl-
40) junit-mocking of any dao
41) code review tool
42) continous integration ?
43) findbug,pmd,checkstyle- sonar.

44) how hasmap works internally.
45) what is synchronization?
45) how will you implement singleton class?
46) difference between factory and abstractFactory?
47) difference between arraylist and linked list?
48) difference between arraylist and hashmap?
49) what are locks?
50) if you have two interfaces having same method in these, now you are implementing these two interfaces in your class. Will there be any issue with it?
51) what is hasing?
52) difference between hashmap and hashtable?
53) you have a very huge arraylist, which is having duplicate values. how will you get a collection of unique entities from this arraylist?
54) difference between Exception and Error? can we catch Exceptions and Errors in our java code?
55) how will you do the performance improvement in you project?
56) how customer layer communicates with the service layer.?
57) basic functioning of JMS.
58) what all design patterns have you implemented in your project?
59) what are joins?
60) you have an employee table, having ID, name, managerName, DeptId. Now you need to show the employee name and his manager from it.
61) you have employee table, and department table. employee having id, dept, salary and name. Dept is having dept id and name.
       now you need to show all the department where the average salary of the department > 10000.
62) You have a synchronized method in a Class ABC, say public synchronized void show(){}, now you have created an object of this ABC a1
        now, two threads t1 and t2 wants to access the two methods on this object "a1". is it possible to execute these two synchronized methods with the same object?
63) you have a class Parent and a class Child extends Parent. These two classes have a method public void show(){}.
       now you are doing Parent p  = new Child();
                                          p.show();
      which method is gonna call through this statement?
       what if both these two methods are static methods?
64)  you have millions of number, and you need to find the highest number from this. how will you do that, it should be performance efficient.
65)  what is the difference between Lock and synchronized.
66) what if you dont override hashcode method of your class and using this object as a key to store the values in a hashmap?
67)


**************************************************************************
ASked to someone
1.Describe current project with architecture
2.what is the difference between extend thread class and implementing unable interface.
3.what is the difference between ear, war, and jar.
4.what is realization, why it is used. what is transient variable.
5.can we put duplicate key in map and can we put multiple values in map?
6.Difference between jip and served. explain jip life cycle.
7.Difference between mvc1 and mvc2
8.explain struts1.1 flow.

**************************************************************************

1) Difference between LIST and SET, HashMap and HashSet, Vector and ArryList, ArrayList and LinkedList, which can be used in which scenario.
2) How HashMap works.
3) equals and hashcode
4) Colletion sorting - comparable and comparator.-what can be the defination of overriten methods. how it works.
5) new String("abc") - how many objects created. and what happens in memory.
6) String str[] = new String[3]{"a","b","c"} same if we have array of integer- what happens in memory
7) Immutable Object - how can we make class as immutable.
8) Serilization - what is serialVersionNo. if used in class and Serilizable is not implemented.
9) drawback of Serilizable interface
10) Externlizable and its two methods - what can we do with this two methods.
11) how can we share information between two threds.
12) Statics Synchronized method, Synchronized method, normal method.
     i) if two threads accessing these methods - what will happen in each case.
     ii) if we have two objects containing all above methods and two threads accessing two objects differently, what will happen.
13) difference between sleep and wait.
14) Tell me about String class.- Is String class is thread-safe.
15) enumeration and iterator and list-iterator. differences
16) fail-safe and fail-false.
17) HashMap, SynchronizedHashMap, concurrentHashMap
18) how can we find duplicates in arraylist - with Collecyions.frequency
19) how Jprofiler configured with application.
20) what about maven. in descriptive.

Wednesday 9 January 2013

Design Patterns- Factory


Factory Design Pattern:


Why?:

Factory Pattern, also known as Factory method pattern, is probably the most commonly used patterns in modern days.
Intent:
Creates objects without exposing the creation logic to the external world
Refers to a newly created object through an interface.

A factory is a Java class that encapsulates the object creation code. A factory creates and return a particular type of a object based on the data type or data provided to the factory method.

How?

The implementation is quite simple, e,g.,

  • If a client want a product, so instead of directly creating it by calling new, it asks for a factory object for a new product by providing information of what it need.
  • The factory instantiates a new concrete product and returns this newly created object to the client.
  • The client uses the object as abstract product without being knowing its concrete implementation.

Tuesday 8 January 2013

J2EE Design Patterns - Intercepting Filter

Different type of processing is required for the different type of request, received by the presentation tier request handler. Some requests are simply forwarded to the appropriate handler component, while other requests must be processed before actual request processing.
We require Preprocessing and post-processing of a client Web request and response.

When a request enters a Web application, it often must pass several checks, prior to the main processing stage -
- Authentication, Authorization
- data-encoding scheme.
- logging information about each request
- transformation of output for a specific client
- Uncompressing and converting encoding scheme of input.
- Does the client have a valid session?
- Does the request path violate any constraints?
- What encoding does the client use to send the data?
- Do we support the browser type of the client?

Some of these checks are tests, resulting in a yes or no answer that determines whether processing will continue or not.

With fulfillment of above requirement, we also need below demands be inline -
- Common processing, such as checking the data-encoding scheme or logging information about each request, completes per request.
- Centralization of common logic is desired.
- Services should be easy to add or remove unobtrusively without affecting existing components,
so that they can be used in a variety of combinations, such as Logging and authentication, Debugging and transformation of output for a specific client, Uncompressing and converting encoding scheme of input
- For an efficient system, these requests and responses must be pre-processed and post-processed in a proper way.
In addition to that this, processing must be independent from the rest of the system.

Solution -

Create pluggable filters to process common services in a standard manner without requiring changes to core request processing code.
The filters intercept incoming requests and outgoing responses, allowing preprocessing and post-processing.

Features -
- We are able to decorate our main processing, with a variety of common services, such as security, logging, debugging etc.
- These filters are components, that are independent of the main application code and they may be added or removed declaratively.
For example, a deployment configuration file may be modified to set up a chain of filters. The same configuration file might include a mapping of specific URLs to this filter chain. When a client requests a resource that matches this configured URL mapping, the filters in the chain are each processed in order before the requested target resource is invoked.
- Intercepting filters provide Declarative and Flexible Configuration with the help of web.xml file, where we can have Filter defination and filters are used in servlets, where we want them to act as filters.
- Numerous services are combined in varying permutations without a single recompile of the core code base.
- Intercepting filters improves reusability, Filters promote cleaner application partitioning and encourages reuse.
- The Intercepting Filter separates request/response processing from the rest of the system by creating filters.
- It provides authentication, authorization, transformation and conversion of requests and responses as needed.

Below Components are involved in this pattern -

FilterManager :
The FilterManager manages filter processing. It creates the FilterChain with the appropriate filters, in the correct order, and initiates processing.

FilterChain :
The FilterChain is an ordered collection of independent filters.

Filters :
These are the individual filters that are mapped to a target. The FilterChain coordinates their processing.

Target :
The Target is the resource requested by the client.

Design Patterns- Command

J2EE Design Patterns - Front Controller


The Front Controller provides a centralized entry point to access Application, that controls and manages Web request handling, by delegating request to appropriate Action OR Model files, who are responsible for rest of business processing at server-side.
The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request.
Front Controllers are responsible for routing incoming user requests in application.
With Centralizing point of access, Front Controler can manage below things at a time -
- Dispatching Request to appropriate Request handler OR Models OR Action files for Business processing. Thus Front Controller can validate the   incoming requests and route them accordingly. i.e Controlling page flow and navigation.
- Applying security services to incomming request, such as authentication and authorization.
- Accessing and managing model data.
- data validation.
- Handling business processing.
- Managing an appropriate views as per request.
- handling errors.
Advantages -
 - By centralizing controls, the controller helps reduce the amount of Java code.
 - reducing business logic in the view promotes, code reuse across requests.
 - Front Controllers can reduce code duplication in JSP pages, especially in cases where several resources require the same processing.
 - If the behavior of functions which are applied to Front Controller, needs to change, only the Front Controller and its helper classes need   to be changed. They constitute a relatively small portion of the application.
If not using Front Controller -
* view is required to provide its own system services often resulting in duplicate code.
* View navigation is left to the views. This may result in shared code for view content and view navigation.
* Distributed control is more difficult to maintain, since changes will often need to be made in numerous places.
The Front Controller suggests that we only have one Servlet (instead of having specific Servlet for each specific request) centralising the handling of all the requests and delegating the functions like validation, invoking business services etc to a command or a helper component.
Putting this use case in a simple words, we want all the request to go though a single servlet which does all the authentication and other generic operations and then based on what request was made by the user, this serlvet should transfer the request to appropriate Action item on server side.
As a web-application grows, number of controllers grow. Putting all the generic code inside these controllers in single controller, which actually performs those operations and then forwards the same request to appropriate controller is called Front Controller
In case of Struts1.xx this front controller is ActionServlet, all the request made to struts1.xx are passed though ActionServlet.
FrontController implementation examples as below -
* ActionServlet acts as FrontController in Struts 1.xx
 All Request are forwarded to ActionServlet, which in trun performs common functionality then forward request to appropriate Action (Sub-Controller)Class. this is done by using Struts-config.xml file.
* Dispatcher in Struts 2.xx


Example using HttpServlet :
------- Web.xml -------
<web-app>
  <servlet>
    <servlet-name>FrontControllerServlet</servlet-name>
    <servlet-class>com.test.FrontControllerServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FrontControllerServlet</servlet-name>
    <url-pattern>/*.do</url-pattern>
  </servlet-mapping>
</web-app>
--------------------------------------------------------------------------------------------------
public class FrontController extends HttpServlet {
    // parameters shared with login.jsp.  These must exactly match the
    // property names in the JSP.
    public static final String USERNAME_PARAM = "username";
    public static final String PASSWORD_PARAM = "password";
    public static final String USERBEAN_ATTR = "userbean";
    public static final String CONTROLLER_PREFIX = "/pages";
   
    /**
     * Handle get requests by forwarding to a common processor
     */
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        process(request, response);
    }
   
    /**
     * Handle post requests by forwarding to a common processor
     */
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {
        process(request, response);
    }
   
    /**
     * The common processor method.  Check if this user is logged in or not.
     * If they are not, forward to the login page, otherwise forward to the
     * requested URL.
     */
   protected void process(HttpServletRequest request,
                           HttpServletResponse response)
        throws ServletException, IOException
    {
        // the default next page
        String nextPage = request.getPathInfo();
       
        // find userbean from session
        HttpSession session = request.getSession(true);
        UserBean userBean = (UserBean) session.getAttribute(USERBEAN_ATTR);
       
        if (userBean == null || !userBean.isLoggedIn()) {
            // read request parameters
            String username = request.getParameter(USERNAME_PARAM);
            String password = request.getParameter(PASSWORD_PARAM);
           
            // if the userbean doesn't exists, create it
            if (userBean == null) {
                userBean = UserBeanFactory.newInstance();
                session.setAttribute(USERBEAN_ATTR, userBean);
            }
           
            // record the username and password values
            userBean.setUsername(username);
            userBean.setPassword(password);
           
            // attempt to login
            boolean result = userBean.doLogin();
           
            // if we failed, redirect to the login page
            if (!result) {
                nextPage = "/login.jsp";
            }
        }
       
        // transfer control to the desired view
        RequestDispatcher dispatcher =
            getServletContext().getRequestDispatcher(nextPage);
        dispatcher.forward(request, response); 
    }   
}

Friday 4 January 2013

Design Patterns- Strategy

OBJECTIVE:
Define a family of algorithms, encapsulate each one, and make them interchangeable at runtime. The Strategy pattern lets the algorithm vary independently from clients that use it.
Gang of Four book on Design Patterns states:
Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour at runtime.
The strategy pattern is a software design pattern, whereby an algorithm's behaviour can be selected at runtime.
For instance, a class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, and/or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. The validation strategies, encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.
In the strategy pattern, behaviour are defined as separate interfaces and specific classes that implement these interfaces. Specific classes encapsulate these interfaces. This allows better decoupling between the behaviour and the class that uses the behaviour. The behaviour can be changed without breaking the classes that use it, and the classes can switch between behaviour by changing the specific implementation used without requiring any significant code change behaviour can also be changed at run-time as well as at design-time. For instance, a car object’s brake behaviour can be changed from BrakeWithABS() to Brake() by changing the brakeBehavior member to:

* This pattern specifies set of classes, each representing a potential behaviour, so switching between those classes changes a application behaviour.
* Each one of those specifies classes, would usually encapsulates an algoritham. so switching between the classes, switch the algorithm, and thus change the behaviour of application.
* so using this pattern makes it easier to add OR remove specific behaviour without having to recode OR retest, all OR parts of application.
Advantages :
The Strategy pattern lets you build software as a loosely coupled collection of interchangeable parts.
That loose coupling makes your software much more extensible, maintainable, and reusable.
This gives greater flexibility in design and is in harmony with the Open/closed principle (OCP) that states that classes should be open for extension but closed for modification.

Where Would I Use This Pattern:
The Strategy pattern is to be used where you want to choose the algorithm to use at runtime. A good use of the Strategy pattern would be saving files in different formats, running various sorting algorithms, or file compression.
The Strategy pattern provides a way to define a family of algorithms, encapsulate each one as an object, and make them interchangeable.
Examples -- http://java.dzone.com/articles/design-patterns-strategy
Examples -- http://en.wikipedia.org/wiki/Strategy_pattern

Example with OUTPUT :

public interface GoAlgorithm {

public void go();
}

------------------------------------------------------------------------------------------
public class GoByDrivingAlgorithm implements GoAlgorithm {

public void go() {

System.out.println(" Now I am Driving ");
}

}

------------------------------------------------------------------------------------------
public class GoByFlyingAlgorithm implements GoAlgorithm {

public void go() {

System.out.println(" Now I am Flying ");
}

}

------------------------------------------------------------------------------------------
public class GoByFastFlyingAlgorithm implements GoAlgorithm {

public void go() {

System.out.println(" Now I am Flying Fast ");
}

}

------------------------------------------------------------------------------------------
public abstract class Vehicle {

private GoAlgorithm goAlgorithm;

public void setGoAlgorithm(GoAlgorithm newGoAlgorithm){
goAlgorithm = newGoAlgorithm;
}

public void go(){
goAlgorithm.go();
}
}

------------------------------------------------------------------------------------------
public class StreetRacer extends Vehicle {

public StreetRacer(){
setGoAlgorithm(new GoByDrivingAlgorithm());
}

}

------------------------------------------------------------------------------------------
public class FormulaOne extends Vehicle {

public FormulaOne(){
setGoAlgorithm(new GoByDrivingAlgorithm());
}
}

------------------------------------------------------------------------------------------
public class HeliCopter extends Vehicle {

public HeliCopter(){
setGoAlgorithm(new GoByFlyingAlgorithm());
}
}

------------------------------------------------------------------------------------------
public class Jet extends Vehicle {

public Jet(){
setGoAlgorithm(new GoByFastFlyingAlgorithm());
}
}

------------------------------------------------------------------------------------------
public class client {

public static void main(String args[]){

Vehicle vehicle = new Jet();

vehicle.go();

vehicle.setGoAlgorithm(new GoByFlyingAlgorithm());

vehicle.go();

vehicle.setGoAlgorithm(new GoByFastFlyingAlgorithm());

vehicle.go();
}
}

------------------------------------------------------------------------------------------
OUTPUT :

Now I am Flying Fast
Now I am Flying
Now I am Flying Fast 

Thursday 3 January 2013

Design Patterns- Observer

Observer Pattern is the fundamental pattern in java. To understand it in simple words, it allows one object(observer) to watch another object(subject). Observer pattern allows the subject and observer to form a publish-subscirbe relationship. Through Observer pattern, observers can register themselves to recieve events from subject. When the subject needs to inform its observer of an event, it simply sends the event to its observers.

For example:
Suppose in a loan application, interest rates are subject to change and depending upon this, several other values changes like EMI or the tenure of the loan :)
so here the subject is interest rate and observer are loan accounts which are register to the subject for the subscription of the changes in interest rates.
When the interest rate changes, it notifies/updates its observers about its changed value and intern each account is modified with its EMI value or Tenure.
diagram from wiki.

So here comes our Intent of the Observer Pattern:

Intent:

Define one to many dependency between objects so that one object change its state, can be notified and updated to other objects automatically. The motivation of doing so is to maintain the consistency of the related objects without making classes tightly coupled.

IN JAVA API:

Java makes our task very easy, in java.util package, we can find interfaces, classes and methods for implementing observer pattern.
Public Interface Observer:
Any class who implements this interface must be notified when subject or observable object change its status.
Update (Observable Ob, Object arg): This method is called when subject is changed.

Class Observable:
It’s a subject to whom observer wants to observe.

Some Important Method:
addObserver(Observer o):add Observers in the set of observers for this subject or observalbel object.

deleteObserver(Observer o): delete Observers in the set of observers .

hasChanged():check if object has changed.

clearChanged():this method will indicate that subject has no changes or all the observers has been notified when changes is made.

notifyObservers(): notify all the observers if object has changed .

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Observable.html

Wednesday 2 January 2013

Collection Framework

Design Patterns- Singleton


Singleton Design Pattern:


Why?:


The intent of a singleton class is to ensure a class has only one instance, and provide a global point of access to it.

How?

  • Make the class of the single instance object responsible for creation, initialization, access, and enforcement.
  • Declare the instance as a private static data member.
  • Provide a public static member function that encapsulates all initialization code, and provides access to the instance
There are various approaches to achieve singleton behavior:


Eager initialization:- where an instance of a class is created much before it is actually required, in other words the instance is created at the startup only irrespective of whether any class requires it or not.


public class EagerSingleton{
private static volatile EagerSingleton instance = new EagerSingleton();
//private constructor
private EagerSingleton(){
}

public synchronized static EagerSingleton getInstance(){
if(null == instance){
instance = new EagerSingleton();
}
return instance;
}
}

Lazy Initialization:
means delaying the creation of object untill its first requested.

public final static LazySingleton{
private static volatile LazySingleton instance = null;
//Private constructor
private LazySingleton(){}
private LazySingleton getInstance(){
if(instance==null){
synchronized (LazySingleton.class){
instance = new LazySingleton();
}
}
return instance;
}
}
//There is a problem with this implementation, I am keeping it open for the discussion.
//why do we use volatile with instance variable?

The above method has some drawbacks, suppose there are Two threads T1 & T2 starts simultaneously and  both comes to create instance and execute if(instance == null), at this point of time they both will get instance to be null, they sequentially go into the synchronized block and create the instance. so this way you will end up with 2 instances of a singleton class :)

This can be solved by double check locking technique, where we recheck the instance variable in synchronized block.

public final static LazySingleton{
private static volatile LazySingleton instance = null;
//Private constructor
private LazySingleton(){}
private LazySingleton getInstance(){
  if(instance==null){
      synchronized (LazySingleton.class){
         if(instance==null){
             instance = new LazySingleton();
        }
    }
}
return instance;
}
}


Static Block Initialization:
As you now  the static blocks are executed during the class loading and even before a constructor is called, so using this feature we can achieve singleton for our class.
Lets see how?



public class StaticBlockSingleton {
      private static final StaticBlockSingleton instance;
      static{
                        try{
                                    instance = new StaticBlockSingleton ();
                        }
                        Catch(Exception e){
                                    Sysout(“Unexpected result!!!”);
                        }
            }
            private StaticBlockSingleton(){};
  public static StaticBlockSingleton getInstance(){
                        return instance;
            }

Above code has one drawback. Suppose there are 5 static fields in class and application code needs to access only 2 or 3, for which instance creation is not required at all. So, if we use this static initialization. we will have one instance created though we require it or not.


Adding readReslove():
So fare we have covered like, how to implement our singleton class, various issues and their resolutions.
Now there is could be one more situation, where you need to frequently serialize your singleton class. So while deSerialization, it creates a new object of a class.. OOOPPPPPSSSS…
Now how to solve this issue?
Well its pretty simple, you just need to add readResolve method in your implementation to override it to return the existing instance of you class.

Something like:
protected Object readReslove(){
            return instance;
}

clone():
So far so good, but there could be one more violation in singleton pattern.
If your class is implementing clonable interface then there is a possibility that you end up creating multiple objects of your singleton class.
To avoid this situation, you just simply override the clone of Object in your implementation of singleton to return the same instance or simply throw an exception from there saying CloneNotSupported Exception.
Like:
protected Object clone() throws CloneNotSupportedException
{
            //you can return the existing instance
            return instance;
           
            //or, you can throw an exception from here
            throw new CloneNotSupportedException(“Cloning not allowed for singleton classes”);



Agile Development


Agile is software development methodology. It is very effective where Client frequently changes his equirement. Since it has more iteration so you can assure a solution that meets clients requirement.
More than one build deployment for a project. It involves more client interaction and testing effort.
There are two methods by which this methodology can be implemented:-
1- Scrum.
2- Extreme Programming.

Scrum: Each iteration would called a scrum which can be a 1- 2 Months. In Scrum Client prioritize his requirements what he want first. If developer did not meets all the requirement which was being fixed for a particular scrum than rest of the development part would be transferred to the next scrum (would be delivered in the next build), means developer can't increase time decided for a scrum. Its fixed.
Extreme Programming (XP): here iteration period would be less then in scrum , which is being 2-4 weeks.
Here developer prioritize what to do first on the basis of client requirement. This duration which was being fixed for a iteration, can be increase if the some development part is still pending. The build would deployed with having all the client needs. Thus iteration period is not fixed here it can be increase but iteration should meets all the client's requirement in this build.
More attention is required for testing in XP.

Apart from all the above answers, just add this important point.
There are many flavors of Agile Development:
1- Agile Manifesto
2- (XP) Extreme Programming
3- Scrum
4- Crystal
5- Context Driven Testing
6- Lean Development
7- (Rational) Unified Process

Agile methodology is a conceptual framework where software is developed in iterations. Each iterations has Requirement analysis, planning, design, coding, testing and documentation.
Characteristics:
- Many builds are delivered in the iteration process
- Accepts change of requirement at any stage
- Requires close communication between business,
Development and Testing people
- Reduced risk and time to develop
- Less documentation work compared to other methodologies
- Requires continuous testing

Test Driven Development
http://www.javacodegeeks.com/2012/05/test-driven-development-win-win.html

Saturday 22 September 2012

Java Serialization


What is Serialization in Java?
Java Serialization is the process of writing the states of an object into a byte stream which includes the object's data as well as information about the object's type and type of data stored in the object.

This process is JVM independent, that means an object which is serialized on one platform can be deserialized on an entirely different platform.

The main purpose of Java serialization is to write the states of the object in a stream of bytes that can be transported through a network and that object then can be rebuild again.

How to make a Java class Serializable?
A class must implement a marker interface Serializable in order to have a capabilities of serializing its objects. This interface just informs the JVM that this class can be serialized.
If you don't want any of the class's property not to be serialized, mark it as transient.

A sample program to create a serializable class:

import java.io.*;
import java.io.Serializable;

class Employee implements Serializable {
private static final long serialVersionUID = 1L;
public String empName;
public String address;
public transient int ssn; // this will not be serialized,it will be having
// default value when deserializing it from disk
public int age;

public Employee(String name, String addr, int number, int age){
this.empName=name;
this.address=addr;
this.ssn=number;
this.age= age;
}
}

public class SerializeDemo{
public static void main(String[] args){
Employee e1 = new Employee("Piyush", "Pune",1001, 32);
FileOutputStream fileOutput=null;
try{
fileOutput = new FileOutputStream("D:/STUDY/java/workspace/OUTPUTS/employee.ser");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOutput);
objectOut.writeObject(e1);
System.out.println("Employee object is serialized in employee.ser");
objectOut.close();
fileOutput.close();
}
catch(IOException fne){
fne.printStackTrace();
}
try{
FileInputStream fileInput = new FileInputStream("D:/STUDY/java/workspace/OUTPUTS/employee.ser");
ObjectInputStream objectInput = new ObjectInputStream(fileInput);
Employee e =(Employee) objectInput.readObject();
System.out.println("Employee is reConstructed from disk");
System.out.println(e.address);
System.out.println(e.empName);
System.out.println(e.ssn); // it may have default value depending on
// how its declared in serialized class.
System.out.println(e.age);
objectInput.close();
fileInput.close();
}
catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}



What is the difference between Serializable and Externalizable interface in Java?
Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.

What is serialVersionUID? What would happen if you don't define this?

Whenever you implements serializable interface in your class to serialize it, by default JVM inserts ( if you don’t define your own versionID) a unique ID which is called serialVersionUID. JVM uses this id to serialize and deserialize an object. JVM Creates this UID depending on the structure of your class, like the methods used in the class, objects in the class any interface implemented etc.
It is always better to define your own serialVersionUID in your calss.If you are using the default definition of serialVersionUID, and later on if you are going to alter your class, java will create a different UID as the structure of the class is changed and serialize objects with this new UID. Problem occurs when you try to deserialize an old object of this class, at that time the UIDs will not be matched and you will get “NotSerializableException”.

While serializing you want some of the members not to serialize? How do you achieve it?
mark those members as transient.

What will happen if one of the members in the class doesn't implement Serializable interface?
One of the easy question about Serialization process in Java. 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

from the above example, create a class person which doesnt extends serializable interface and also modify Employee class:

class Person{
public String name;

public Person(String name){
this.name= name;
}
}
class Employee implements Serializable {
       Person per;
       public Employee(String name, String addr, int number, int age, Person p){
this.empName=name;
this.address=addr;
this.ssn=number;
this.age= age;
this.per = p; //non serializable class's object
}
}

while serializing it will throw"NotSerializableException"


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

At the time of deserialization, the constructor of the parent class will be called, which will override the value of the instance variable of super class, that it has at the time of serialization.