AdSense

AdSense3

Thursday 27 November 2014

Java Transient Keyword

Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.

Let's take an example, I have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but I don't want to serialize one value, e.g. age then we can declare the age data member as transient.

Example of Java Transient Keyword

In this example, we have created the two classes Student and PersistExample. The age data member of the Student class is declared as transient, its value will not be serialized.
If you deserialize the object, you will get the default value for transient variable.
Let's create a class with transient variable.
  1. import java.io.Serializable;  
  2. public class Student implements Serializable{  
  3.  int id;  
  4.  String name;  
  5.  transient int age;//Now it will not be serialized  
  6.  public Student(int id, String name,int age) {  
  7.   this.id = id;  
  8.   this.name = name;  
  9.   this.age=age;  
  10.  }  
  11. }  
Now write the code to serialize the object.
  1. import java.io.*;  
  2. class PersistExample{  
  3.  public static void main(String args[])throws Exception{  
  4.   Student s1 =new Student(211,"ravi",22);//creating object  
  5.   //writing object into file  
  6.   FileOutputStream f=new FileOutputStream("f.txt");  
  7.   ObjectOutputStream out=new ObjectOutputStream(f);  
  8.   out.writeObject(s1);  
  9.   out.flush();  
  10.   
  11.   out.close();  
  12.   f.close();  
  13.   System.out.println("success");  
  14.  }  
  15. }  
Output:
success
Now write the code for deserialization.
  1. import java.io.*;  
  2. class DePersist{  
  3.  public static void main(String args[])throws Exception{  
  4.   ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
  5.   Student s=(Student)in.readObject();  
  6.   System.out.println(s.id+" "+s.name+" "+s.age);  
  7.   in.close();  
  8.  }  
  9. }  
211 ravi 0
As you can see, printing age of the student returns 0 because value of age was not serialized.

Wednesday 26 November 2014

Serialization in Java

Serialization in java is a mechanism of writing the state of an object into a byte stream.
It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.
The reverse operation of serialization is called deserialization.
The String class and all the wrapper classes implements java.io.Serializable interface by default.

Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as marshaling).

java.io.Serializable interface

Serializable is a marker interface (has no body). It is just used to "mark" java classes which
support a certain capability.
It must be implemented by the class whose object you want to persist. Let's see the example
given below:
  1. import java.io.Serializable;  
  2. public class Student implements Serializable{  
  3.  int id;  
  4.  String name;  
  5.  public Student(int id, String name) {  
  6.   this.id = id;  
  7.   this.name = name;  
  8.  }  
  9. }  

ObjectOutputStream class

The ObjectOutputStream class is used to write primitive data types and Java objects to an
 OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.

Constructor

1) public ObjectOutputStream(OutputStream out) throws IOException {}creates an ObjectOutputStream that writes to the specified OutputStream.

Important Methods

MethodDescription
1) public final void writeObject(Object obj) throws IOException {}writes the specified object to the ObjectOutputStream.
2) public void flush() throws IOException {}flushes the current output stream.
3) public void close() throws IOException {}closes the current output stream.

Example of Java Serialization

In this example, we are going to serialize the object of Student class. The writeObject() method
of ObjectOutputStream class provides the functionality to serialize the object. We are saving the
state of the object in the file named f.txt.
  1. import java.io.*;  
  2. class Persist{  
  3.  public static void main(String args[])throws Exception{  
  4.   Student s1 =new Student(211,"ravi");  
  5.   
  6.   FileOutputStream fout=new FileOutputStream("f.txt");  
  7.   ObjectOutputStream out=new ObjectOutputStream(fout);  
  8.   
  9.   out.writeObject(s1);  
  10.   out.flush();  
  11.   System.out.println("success");  
  12.  }  
  13. }  
success

Deserialization in java

Deserialization is the process of reconstructing the object from the serialized state.It is the
reverse operation of serialization.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor

1) public ObjectInputStream(InputStream in) throws IOException {}creates an ObjectInputStream that reads from the specified InputStream.

Important Methods

MethodDescription
1) public final Object readObject() throws IOException, ClassNotFoundException{}reads an object from the input stream.
2) public void close() throws IOException {}closes ObjectInputStream.

Example of Java Deserialization

  1. import java.io.*;  
  2. class Depersist{  
  3.  public static void main(String args[])throws Exception{  
  4.     
  5.   ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
  6.   Student s=(Student)in.readObject();  
  7.   System.out.println(s.id+" "+s.name);  
  8.   
  9.   in.close();  
  10.  }  
  11. }  
211 ravi

Java Serialization with Inheritance (IS-A Relationship)

If a class implements serializable then all its sub classes will also be serializable.
Let's see the example given below:
  1. import java.io.Serializable;  
  2. class Person implements Serializable{  
  3.  int id;  
  4.  String name;  
  5.  Person(int id, String name) {  
  6.   this.id = id;  
  7.   this.name = name;  
  8.  }  
  9. }  
  1. class Student extends Person{  
  2.  String course;  
  3.  int fee;  
  4.  public Student(int id, String name, String course, int fee) {  
  5.   super(id,name);  
  6.   this.course=course;  
  7.   this.fee=fee;  
  8.  }  
  9. }  
Now you can serialize the Student class object that extends the Person class which is Serializable.
Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.

Java Serialization with Aggregation (HAS-A Relationship)

If a class has a reference of another class, all the references must be Serializable otherwise
serialization process will not be performed. In such case, NotSerializableException is thrown at
runtime.
  1. class Address{  
  2.  String addressLine,city,state;  
  3.  public Address(String addressLine, String city, String state) {  
  4.   this.addressLine=addressLine;  
  5.   this.city=city;  
  6.   this.state=state;  
  7.  }  
  8. }  
  1. import java.io.Serializable;  
  2. public class Student implements Serializable{  
  3.  int id;  
  4.  String name;  
  5.  Address address;//HAS-A  
  6.  public Student(int id, String name) {  
  7.   this.id = id;  
  8.   this.name = name;  
  9.  }  
  10. }  
Since Address is not Serializable, you can not serialize the instance of Student class.

Note: All the objects within an object must be Serializable.


Java Serialization with static data member

If there is any static data member in a class, it will not be serialized because static is the part
of class not object.
  1. class Employee implements Serializable{  
  2.  int id;  
  3.  String name;  
  4.  static String company="SSS IT Pvt Ltd";//it won't be serialized  
  5.  public Student(int id, String name) {  
  6.   this.id = id;  
  7.   this.name = name;  
  8.  }  
  9. }  

Java Serialization with array or collection

Rule: In case of array or collection, all the objects of array or collection must be serializable.
If any object is not serialiizable, serialization will be failed.

Externalizable in java

The Externalizable interface provides the facility of writing the state of an object into a byte
 stream in compress format. It is not a marker interface.
The Externalizable interface provides two methods:
  • public void writeExternal(ObjectOutput out) throws IOException
  • public void readExternal(ObjectInput in) throws IOException

Java Transient Keyword

If you don't want to serialize any data member of a class, you can mark it as transient.

Tuesday 25 November 2014

Java DatagramSocket and DatagramPacket

Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.


Java DatagramSocket class

Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.

Commonly used Constructors of DatagramSocket class

  • DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available Port Number on the localhost machine.
  • DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the given Port Number.
  • DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.

Java DatagramPacket class

Java DatagramPacket is a message that can be sent or received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class

  • DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to receive the packets.
  • DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet. This constructor is used to send the packets.

Example of Sending DatagramPacket by DatagramSocket

  1. //DSender.java  
  2. import java.net.*;  
  3. public class DSender{  
  4.   public static void main(String[] args) throws Exception {  
  5.     DatagramSocket ds = new DatagramSocket();  
  6.     String str = "Welcome java";  
  7.     InetAddress ip = InetAddress.getByName("127.0.0.1");  
  8.      
  9.     DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);  
  10.     ds.send(dp);  
  11.     ds.close();  
  12.   }  
  13. }  

Example of Receiving DatagramPacket by DatagramSocket

  1. //DReceiver.java  
  2. import java.net.*;  
  3. public class DReceiver{  
  4.   public static void main(String[] args) throws Exception {  
  5.     DatagramSocket ds = new DatagramSocket(3000);  
  6.     byte[] buf = new byte[1024];  
  7.     DatagramPacket dp = new DatagramPacket(buf, 1024);  
  8.     ds.receive(dp);  
  9.     String str = new String(dp.getData(), 0, dp.getLength());  
  10.     System.out.println(str);  
  11.     ds.close();  
  12.   }  
  13. }