Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Showing posts with label Interview Questions. Show all posts
Showing posts with label Interview Questions. Show all posts

Sunday, September 27, 2015

Lambda Expressions in Java 8

Lambda Expressions:
  • Lambda expression is an anonymous function without any declarations. 
  • Lambda Expression are useful to write shorthand code and hence saves the effort of writing lengthy code. 
  • It promotes developer productivity, better readable and reliable code.
  • Lambda expressions can be converted to functional interfaces.
  • Lambda expressions can access effectively final variables from the enclosing scope..
Syntax of Lambda expression:
(arguments) -> {body}

Example of Lambda expression:
public class LambdaExpressions
{
  public static void main(String[] args)
  {        
    // Old way
    Runnable runnable = new Runnable() {
        public void run() {
            System.out.println("With out using Lambda Expressions .... ");
        }
    };
    
    Thread thread = new Thread(runnable);    
    thread.start();
    
    // Using Lambda Expressions
    Runnable runnable2 = () -> { System.out.println("With using Lambda Expressions .... ");};
    
    Thread thread2 = new Thread(runnable2);    
    thread2.start();    
  }
}
Output:
With out using Lambda Expressions .... 
With using Lambda Expressions .... 
Lambda expression arguments can contain zero or more arguments.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");

new Thread(() -> { System.out.println("Empty arguments.");}) {      // empty arguments          
}.run();;
        
names.forEach(name -> System.out.println(name));            // one argument with out specifying data type 
names.forEach((name) -> System.out.println(name));          // one argument with out specifying data type
names.forEach((String name) -> System.out.println(name));   // one argument with specifying data type
Note: We can omit the datatype of the parameters in a lambda expression. And also we can omit the parentheses if there is only one parameter.

Lambda expression body can contain any number of statements or with out statement also.
If body contains more than one statement then curly braces is mandatory otherwise it is optional.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");
        
names.forEach(((name) -> System.out.println(name))); // with out braces
        
names.forEach((name) -> {                            // with braces 
    System.out.println(name);
    System.out.println("Hello Mr. "+name);          
});

Friday, September 11, 2015

Write a Java program to get unique characters from String

In this post, we are going to see how to get unique characters from string.
There are several ways to get unique characters from string. In this post, i have implemented two ways.
1. using boolean array.
2. using map.
1. Using Boolean array: In this technique, first we need to convert string into char array. After that we need to iterate all characters. While iterating we need to check that character is already added to array or not. If it is not added then we need to add that character to boolean array and append that character to stringbuilder. If it is already added that character to boolean array, skipping that character to add boolean array.
Code: 
public static String getUniqueCharsUsingBooleanArray(String input) {
        if (input == null || input.length() == 0)
            return input;

        boolean uniqueChars[] = new boolean[256];
        StringBuilder sb = new StringBuilder();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (!uniqueChars[ch]) {
                uniqueChars[ch] = true;
                sb.append(ch);
            }
        }
        return sb.toString();
}
2. Using Map: In this technique, first we need to convert string into char array. After that we need to iterate each character. While iterating we need to check that character is already added or not. If it is not added, adding that character to map and making count is 1. If it is already added then increment that character with count +1. Once all iteration is done then we need to iterate map and append to that character to stringbuilder. Finally convert this stringbuilder to string using toString() method.
Code:
public static String getUniqueCharsUsingMap(String input) {
        if (input == null || input.length() == 0)
            return input;

        Map<Character, Integer> map = new LinkedHashMap<>();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (map.get(ch) == null) {
                map.put(ch, 1);
            } else {
                map.put(ch, map.get(ch) + 1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character uniqueChar : map.keySet()) {
            sb.append(uniqueChar);
        }
        return sb.toString();
}

Program:
package com.ranga;

import java.util.LinkedHashMap;
import java.util.Map;

public class UniqueCharecters {

    public static void main(String[] args) {
        String input = "my name is ranga reddy";
        System.out.println("Unique Characters using way1: " + getUniqueCharsUsingMap(input));
        System.out.println("Unique Characters using way2: " + getUniqueCharsUsingBooleanArray(input));
    }

    public static String getUniqueCharsUsingBooleanArray(String input) {
        if (input == null || input.length() == 0)
            return input;

        boolean uniqueChars[] = new boolean[256];
        StringBuilder sb = new StringBuilder();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (!uniqueChars[ch]) {
                uniqueChars[ch] = true;
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    public static String getUniqueCharsUsingMap(String input) {
        if (input == null || input.length() == 0)
            return input;

        Map<Character, Integer> map = new LinkedHashMap<>();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (map.get(ch) == null) {
                map.put(ch, 1);
            } else {
                map.put(ch, map.get(ch) + 1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character uniqueChar : map.keySet()) {
            sb.append(uniqueChar);
        }
        return sb.toString();
    }
}
Output:
Unique Characters using way1: my naeisrgd
Unique Characters using way2: my naeisrgd
Happy Learning ....!

Wednesday, September 2, 2015

Add Digits - Given a non-negative integer number, repeatedly add all its digits until the result has only one digit.

Given a non-negative integer number, repeatedly add all its digits until the result has only one digit. 
For example,


38 = 3 + 8 = 11 = 1 + 1 = 2
58 = 5 + 8 = 13 = 1 + 3 = 4
Solution:
There are several ways to implement. Easiest way is number % 9. For example 38 % 9 = 2

Program:
package com.ranga.puzzales;

/**
* Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
* For example,
*
* 38 = 3 + 8 = 11 = 1 + 1 = 2
* 58 = 5 + 8 = 13 = 1 + 3 = 4
*
* @author Ranga Reddy
* @version 1.0
*/

public class AddDigits {
public static void main(String[] args) {
int num = 38;
int digit = 0;

// way 1
System.out.println("Finding the Single Digit using Way1 ");
digit = getSingleDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

num = 58;
digit = getSingleDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

num = 8;
digit = getSingleDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

// Way 2
num = 38;
System.out.println("Finding the Single Digit using Way2 ");
digit = getOneDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

num = 58;
digit = getOneDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

System.out.println();

num = 8;
digit = getOneDigit(num);
System.out.format("Input : %d, Output: %d", num, digit);

}

/**
* Way 1
* Used to find out the single digit.
* @param num
* @return the single digit
*/

private static int getSingleDigit(int num) {
int sum = 0;
while(num > 9) {
sum = sum + (num % 10);
num = num / 10;
}
sum = sum + num;
if(sum > 9) {
sum = getSingleDigit(sum);
}
return sum;
}

/**
* Way 2
* Used to find out the single digit.
* @param num
* @return the single digit
*/

private static int getOneDigit(int num) {
if(num == 0) return 0;
if(num % 9 == 0) return 9;
return num % 9;
}
}
Output:
Finding the Single Digit using Way1 
Input : 38, Output: 2
Input : 58, Output: 4
Input : 8, Output: 8
Finding the Single Digit using Way2 
Input : 38, Output: 2
Input : 58, Output: 4
Input : 8, Output: 8

Sunday, August 23, 2015

Method References in Java8


Method References:
  • Method references refers to methods or constructors without invoking them.
  • We can use lambda expressions to create anonymous methods. 
  • Sometimes, however, a lambda expression does nothing but call an existing method. 
  • In those cases, it's often clearer to refer to the existing method by name.
  • Using Method references refer to the existing method by name, they are compact, easy-to-read lambda expressions for methods that already have a name.
  • In java, method references can be specified by using double colon (::) operator.
  • Method reference can be expressed using the lambda expression syntax (->) in order to make it simple :: operator can be used.
Syntax:
           <class_name or instance_name>::<method_name>
Example:
/**
 * @author Ranga Reddy
 * @version 1.0
 */
public class MethodReferenceExample {
    public static void main(String[] args) {
        
        // with out using method reference
        new Thread(
                () -> {System.out.println("Hello, Mr. Ranga"); }
        ) {
            
        }.run();;
        
        // with using method reference
        new Thread(MethodReferenceExample:: sayHello) {
            
        }.run();
        
    }
    
    public static void sayHello() {
        System.out.println("Hello, Mr. Ranga");
    }
}
Types of Method References:
There are four types of method references:

Method Reference Type
Syntax
Example
Reference to a static method
ClassName::staticMethodName
String::valueOf
Reference to a bound non-static method
ObjectName::instanceMethodName
s::toString
Reference to an instance method of an arbitrary object of a particular type
ClassName::instanceMethodName
Object::toString
Reference to a constructor
ClassName::new
String::new
Reference to a static method:
We can call static method references by using ContainingClass::staticMethodName
Example:
public class MethodReferenceExample {
    public static void main(String[] args) {        
        // Reference to a Static Method     
        new Thread(MethodReferenceExample::sayHello).start();
    }       
    public static void sayHello() {     
        System.out.println("Hello, Mr. Ranga");
    }
}
Reference to a bound non-static method:
We can call non-static method using ObjectName:: instanceMethodName
Example:

public class MethodReferenceExample {
    public static void main(String[] args) {
        // Reference to an Instance Method of a Particular Object
        String name = "My name is Ranga Reddy";
        printName(name::toString);      
    }
    
    private static void printName(Supplier<String> supplier) {
        System.out.println(supplier.get());
    }
}
Reference to an instance method of an arbitrary object of a particular type:
We can call non-static method using ClassName:: instanceMethodName

Example:
public class MethodReferenceExample {
    public static void main(String[] args) {
        // Reference to an Instance Method of an Arbitrary Object of a Particular Type
        String[] names = { "Ranga", "Reddy", "Vinod", "Raja", "Manu", "Teja", "Vasu" };     
        Arrays.sort(names, String::compareToIgnoreCase);
        System.out.println(Arrays.toString(names));     
    }
}
Reference to a bound non-static method:
We can call non-static method using ClassName:: new
Example:
@FunctionalInterface
interface EmployeeFactory {
    Employee getEmployee(long id, String name, Integer age);
}

class Employee {
    private long id;
    private String name;
    private int age;
        
    public Employee() {     
        this(1, "Ranga", 27);
    }
    
    public Employee(long id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
    }   
}

public class MethodReferenceExample {
    public static void main(String[] args) {                
        // Reference to constructor
        EmployeeFactory employeeFactory = Employee :: new;
        Employee employee = employeeFactory.getEmployee(1, "Ranga Reddy",27);
        System.out.println(employee);       
    }
}
When to use method references:
When a lambda expression is invoking already defined method, then we can replace it with reference to that method.
When we can't use method references:
We can't pass arguments to the method references. So that places we can't use method references.
References:
  1. https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
  2. http://java8.in/java-8-method-references/
  3. http://www.informit.com/articles/article.aspx?p=2191424

Monday, August 17, 2015

Java8 New Features

New Features of Java 8:

The following are the major features of Java 8:

Sunday, May 17, 2015

What are all the different ways to create an object in Java?

There are four ways to create a Object in Java. They are

1. Using new keyword - This is the most common way to create an object in java.
Example:
MyObject object = new MyObject();

2. Using Class.forName() - If we know the name of the class and if it has a public default constructor we can create an object in this way.
Example:
MyObject object = (MyObject) Class.forName("com.ranga.MyObject").newInstance();

3. Using clone() - The clone() can be used to create a copy of an existing object.
Example:
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();

4. Using object deserialization - Object deserialization is nothing but creating an object from its serialized form.
Example:
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

Write a SQL Program to Swap the values in a single update query.

Given a Student table, Swap all Male to Female value and vice versa with a single update query.

Id Name Sex Salary
----------------------------
1 Ranga Male 2500
2 Vasu Female 1500
3 Raja Male 5500
4 Amma Female 500

Program:
------------------------
UPDATE Gender SET sex = CASE sex WHEN 'Male' THEN 'Female' ELSE 'Male' END

Write a SQL Program to Select every Nth record.

CREATE TABLE student(id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(4 ,'Ranga', 27, 'Male'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male'),
(8 ,'Vasu', 50, 'Female'),
(9 ,'Ranga', 27, 'Male'),
(10 ,null, 27, 'Male');

Program:
-----------------------------------------------
SELECT * FROM (
SELECT @row := @row +1 AS Rownum, name as Name FROM (SELECT @row :=0) r, student
) students
WHERE rownum %3 = 1;

Output:
-----------------------------------------------
Rownum Name
1 Ranga
4 Ranga
7 Vinod
10 (null)

Write a SQL Program to get the Sum value of same column with different conditions.

CREATE TABLE student(id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male');

Query:
-----------------------------------
SELECT SUM(CASE WHEN s.gender = 'Male' THEN 1 ELSE 0 END) AS MaleCount,
SUM(CASE WHEN s.gender = 'Female' THEN 1 ELSE 0 END) AS FemaleCount
FROM
student s;

Output:
------------------------------
MaleCount FemaleCount
4 2

Write a SQL Program to Get the Next and Previous values based on Current value?

CREATE TABLE student (id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(4 ,'Ranga', 27, 'Male'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male'),
(8 ,'Vasu', 50, 'Female'),
(9 ,'Ranga', 27, 'Male');

Query:
-----------------------------------
SELECT name as Name,
(SELECT name FROM student s1
WHERE s1.id < s.id
ORDER BY id DESC LIMIT 1) as Previous_Name,
(SELECT name FROM student s2
WHERE s2.id > s.id
ORDER BY id ASC LIMIT 1) as Next_Name
FROM student s
WHERE id = 7;

Output:
------------------------------------------------------
Name Previous_Name Next_Name
Vinod Pavi Vasu

How to get the Duplicate and Unique Records by using SQL Query?

CREATE TABLE student (id int, name varchar(30), age int, gender char(6));

INSERT INTO student VALUES
(1 ,'Ranga', 27, 'Male'),
(2 ,'Reddy', 26, 'Male'),
(3 ,'Vasu', 50, 'Female'),
(4 ,'Ranga', 27, 'Male'),
(5 ,'Raja', 10, 'Male'),
(6 ,'Pavi', 52, 'Female'),
(7 ,'Vinod', 27, 'Male'),
(8 ,'Vasu', 50, 'Female'),
(9 ,'Ranga', 27, 'Male');

Getting the duplicate records:
---------------------------------------
SELECT DISTINCT name AS Name, COUNT(name) as Count FROM student GROUP BY name HAVING COUNT(name) > 1;

Output:
---------------------------------------
Name Count
Ranga 3
Vasu 2

Getting the Unique records:
---------------------------------------
SELECT DISTINCT name AS Name FROM student GROUP BY name;

Output:
---------------------------------------
Name
Pavi
Raja
Ranga
Reddy
Vasu
Vinod

How to delete the Child records while updating Parent Record.

If we use javax.persistence.CascadeType.All for deleting child records it will delete only collection of strings. Other than collection of strings in order to delete we need to use
org.hibernate.annotations.CascadeType.DELETE_ORPHAN to delete the child records.
For Example,
public class Employee {    
            @OneToMany(cascade = {CascadeType.ALL})
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
List<Department> departments;
}

What is the output of the following SQL Program. SELECT CASE WHEN null = null THEN 'I LOVE YOU RANGA' ELSE 'I HATE YOU RANGA' end as Message;

SELECT CASE WHEN null = null THEN 'I LOVE YOU RANGA' ELSE 'I HATE YOU RANGA' end as Message;
Output: 'I HATE YOU RANGA'
The reason for this is that the proper way to compare a value to null in SQL is with the is operator, not with =.
SELECT CASE WHEN null IS null THEN 'I LOVE YOU RANGA' ELSE 'I HATE YOU RANGA' end as Message;
Output: 'I LOVE YOU RANGA'

Write a SQL Program to generate the following output?

Input:
Employee:
Department:
Output:
Creating tables and inserting Data:
CREATE TABLE Employee (
e_id INT NOT NULL AUTO_INCREMENT,
e_name VARCHAR(100) NOT NULL,
age tinyint NOT NULL,
PRIMARY KEY (e_id)
);

CREATE TABLE Department (
d_id INT NOT NULL AUTO_INCREMENT,
d_name VARCHAR(100) NOT NULL,
e_id INT NOT NULL,
PRIMARY KEY (d_id),
FOREIGN KEY (e_id)
REFERENCES Employee(e_id)
ON DELETE CASCADE
);

INSERT INTO Employee VALUES (1,'Ranga', 27), (2, 'Raja', 50), (3, 'Vasu',45) ,
(4, 'Vinod', 27), (5, 'Manoj',27);

INSERT INTO Department VALUES (1,'HR', 2), (2, 'Finance', 4), (3, 'Software',1) ,
(4, 'Finance', 3), (5, 'Hardware',1), (6, 'Software', 5), (7, 'Finance', 1);
Query: 
SELECT group_concat(e.e_name) as Employee_Names, d.d_name as Department_Name FROM Employee e INNER JOIN Department d ON d.e_id = e.e_id GROUP BY d.d_name;
Happy Coding!!!

Tuesday, January 14, 2014

Externalization in Java


In my previous post ( Serialization), we saw about Serialization. While using Serialization we can get some limitations.

Limitations of Serialization:
  1. File size is very high because it contains meta information of the file.
  2. Customization due to transient which is not effective because we get “null” in place of transient attributes.
To overcome the limitations of Serialization, we can use the Externalization.

Externalization(java.io.Externalizable): 

Externalization is nothing but serialization but by implementing Externalizable interface to persist and restore the object. To make our object as externalize we need to implement with Externalizable interface.

Unlike Serializable interface, it is not a marker interface which contains two methods 

public void writeExternal(ObjectOutput out) throws IOException;
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

In Serialization process, JVM has full control for serializing object but in Externalization process application/developer gets control for persisting objects. In Externalization process, writeExternal() and readExternal() method provides complete control on format and content of Serialization process.

In writeExternal() method we are making attributes as externalized by using corresponding methods for different types of data.

writeInt()    --> for Integer
writeLong() --> for Long
writeDouble() --> for Double
writeUTF()    --> for String (UTF --> Universal Text Format)
writeObject() --> for Derived attributes other than String & Wrapper classes etc..

In the same way, readExternal() method also provides some methods. By using those methods we can get the externilized attributes.

readInt();
readLong();
readDouble();
readUTF();
readObject();

Employee.java

package com.ranga;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

/**
 * Created by ranga on 1/12/14.
 */

public class Employee implements Externalizable {
  private long serialVersionUID = 31462223600l;

  private long id;
  private String firstName;
  private String lastName;
  private int age;
  private String address;

  public Employee() {
    super();
  }

  public Employee(long id, String firstName, String lastName, int age, String address) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.address = address;
  }
  public Employee(int age) {
    this.age = age;
  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  @Override
  public void writeExternal(ObjectOutput out) throws IOException {
    out.writeLong(id);
    out.writeUTF(firstName);
    out.writeUTF(lastName);
    out.writeInt(age);
    out.writeUTF(address);
  }

  @Override
  public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    id = in.readLong();
    firstName = in.readUTF();
    lastName = in.readUTF();
    age = in.readInt();
    address = in.readUTF();
  }

  @Override
  public String toString() {
    return "Employee{" +
        "id=" + id +
        ", firstName='" + firstName + '\'' +
        ", lastName='" + lastName + '\'' +
        ", age=" + age +
        ", address='" + address + '\'' +
        '}';
  }

}

ExternalizationDemo.java

package com.ranga;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

/**
 * Created by ranga on 1/13/14.
 */

public class ExternalizationDemo {
  public static void main(String[] args) {
    Employee employee = new Employee();
    employee.setId(143);
    employee.setFirstName("Ranga");
    employee.setLastName("Reddy");
    employee.setAge(25);
    employee.setAddress("MPL, Chittoor, AP");

    FileOutputStream fileOutputStream = null;
    ObjectOutputStream objectOutputStream = null;

    try {
      fileOutputStream = new FileOutputStream( new File("employees.ser"));
      objectOutputStream = new ObjectOutputStream(fileOutputStream);
      objectOutputStream.writeObject(employee);
      System.out.println("Employee Object Externalization Done Successfully.");
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally {
      if(objectOutputStream != null) {
        try {
          objectOutputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
      if(fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

Output:
Employee Object Externalization Done Successfully.

DeExternalizationDemo.java

package com.ranga;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * Created by ranga on 1/13/14.
 */
public class DeExternalizationDemo {
  public static void main(String[] args) {
    FileInputStream fileInputStream = null;
    ObjectInputStream objectInputStream = null;

    try {
      fileInputStream = new FileInputStream(new File("employees.ser"));
      objectInputStream = new ObjectInputStream(fileInputStream);
      Employee employee = (Employee) objectInputStream.readObject();
      System.out.println("Employee Info: "+employee);
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally {
      if(objectInputStream != null) {
        try {
          objectInputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
      if(fileInputStream != null) {
        try {
          fileInputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

Output:
Employee Info: Employee{id=143, firstName='Ranga', lastName='Reddy', age=25, address='MPL, Chittoor, AP'}

Only those fields will be persisted as byte stream that will be saved by writeExternal and readExternal. Other field in the class will not be externalized. So by Externalizable interface java developer has complete control on java class persistence.

Externalizable provides complete control, it also presents challenges to serialize super type state and take care of default values in case of transient variable and static variables in Java. If used correctly Externalizable interface can improve performance of serialization process.

Advantages:

The main advantages of externalization over serialization are:
1)File size is highly reduced(nearly 1/3)
2) Customization is very easy and more effective.

Performance issue:
 
1. Further more if you are subclassing your externalizable class you will want to invoke your superclass’s implementation. So this causes overhead while you subclass your externalizable class.
2. methods in externalizable interface are public. So any malicious program can invoke which results into lossing the prior serialized state.


Difference between Serialization and Externalization:

1. With the classes which implement Serializable, the serialization of the object is taken care of automatically, while classes that implement Externalizable is responsible for serializing itself, without the help of default serialization procedures.
2. when we serialize an Externalizable object, a default constructor will be called automatically after that will the readExternal() method be called.