Serialization in Java


Serialization is a important topic in Java where we will use to Serialize the Object into a file or database or even in memory buffer and can transmitted across the network. Serialized Object can be de-serialized at any time and can get same state of original Object as same as cloning the Object. 

If we say in simple words Serialization is streaming Java object to a sequence of byte and restoring same objects from the stream. For example we need to save the state of Object at run-time we can use Serialization and store the Object state in a file. If same Object state need to be used in future then we can de-derialization and can make use of the Object.

Basically for implementing Serialization we need to implement java.io.Serializable interface in the class where the Objects get Serialized. In below example we have implemented in MySerializable class where this class Objects get Serialized. Serialization can't be used in various class where we use Threads, Socket etc.,

While we Serialize complete class variables will get Serialized. Suppose if we feel some variables should not be Serialized then we need to mark those variables as transient as like we have made in our below example. Those variables will not get serialized and will give null while when we de-serialize those variables. 

Below are the simple example for Serialization where we are serializing MySerializable class Object into a file and again de-serializing same Object back. Also we have used transient for "company" variable which won't get Serialized.



public class MySerializable implements Serializable {

 private static final long serialVersionUID = 1023;
 
 private int id;
 private String name;
 private String gender;
 transient private String company; // Variable will not to be Serialized
 
 public MySerializable(int id, String name, String gender, String company){
  this.id = id;
  this.name = name;
  this.gender = gender;
  this.company = company;
 }
 
 public int getId() {
  return id;
 }
 public String getName() {
  return name;
 }
 public String getGender() {
  return gender;
 }
 public String getCompany() {
  return company;
 }
 }




public class SerializationSample {

 public static void main(String args[])  {
  try{
   
   MySerializable serialB = new MySerializable(101, "Steve", "Male", "XYZ Inc.,");
   
   // Serializing the Object and storing in a file
   serialize("C:\\serial.out", serialB);
   System.out.println("Serialization completed...");
   
  }catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void serialize(String file, Object seriObj)
  throws IOException {
  FileOutputStream fos = new FileOutputStream(file);
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(seriObj);
 } 
}


OUTPUT:

Serialization completed...




public class DeSerializableSample {
 
 public static void main(String[] args) {
  try{
   
   // De-serializing the Object from the file
   MySerializable obj = (MySerializable) deSerialize("C:\\serial.out");
   
   System.out.println("ID      : "+obj.getId());
   System.out.println("NAME    : "+obj.getName());
   System.out.println("GENDER  : "+obj.getGender());
   System.out.println("COMPANY : "+obj.getCompany());
   
  }catch (Exception e) {
   e.printStackTrace();
  }
  
 }
 
 public static Object deSerialize(String seriObj)
  throws FileNotFoundException, IOException, ClassNotFoundException {
  FileInputStream fis = new FileInputStream(seriObj);
  ObjectInputStream ois = new ObjectInputStream(fis);
  return ois.readObject();
 }
}


OUTPUT:

ID      : 101
NAME    : Steve
GENDER  : Male
COMPANY : null






How to create executable jar file using eclipse

 

In most of the projects and applications we will use jar files. It can be 3rd party or even internal organization jar files. JAR files are nothing but Java ARchive which will be wrapped with the bundle of .class files, Java files, images, audio or video are any file formats. Its nothing but same as ZIP file which we used in our daily practice. 

By using any unzipping tools we can unwrap JAR files to get files inside. Since mainly its used for .class files and by using obfuscate developers can protect their code and implementation from other users.  

JAR files will be of 2 formats. 
1. Non executable JAR file
2. Executable JAR file

In this tutorial we will how to create executable jar using Eclipse and how to run in Windows. Important for creating executable jar file we need to have at-least single main() method in our project which will be executable. 


STEP - 1: Create new project which we need to implement our functionality  In this demo just we will add 2 numbers as like below. We have created Java Project called AddNumbers and we have class called Add2Numbers and we have implemented our code. Run and test the program once we have implemented. 


creating executable jar file using eclipse


STEP - 2: Right click on Project -> Export -> Java -> Runnable JAR file


creating executable jar file using eclipse


STEP - 3: Click Next and select Project and Class name under Launch configuration: <Add2Numbers - AddNumbers>

 Also enter the folder path and name to save the JAR file in Export destination: D:\\test\AddNubers.jar and click Finish. 

creating executable jar file using eclipse


STEP - 4: Next test your executable jar file from command prompt.


creating executable jar file using eclipse






Simple Web Service using SOAP


In one of our earlier tutorial we have seen Web Services in Java and we have discussed about SOAP Web Service and RESTful Web Services along with their differences. As further we will see a simple example for how to create Web Service server and client using SOAP. For this we will use eclipse J2EE IDE and Apache Tomcat as web server.

First we will create simple Server which will take 2 numbers as input and returns the addition of the program. Here by using Eclipse its very simple to create a service and to deploy and publish a service. Everything we can do it just by clicks rather than doing it lot manually. And also using IDE's will make life more easy than manually.

Server Program:

STEP - 1 : Create a Dynamic Web Project (File -> New -> Dynamic Web Project). Create your project by setting your Target run-time server to installed Apache Tomcat web server. In demo I have used Apache Tomcat 7.0 and you can decide your version according to your need. 

Simple Web Service using SOAP


STEP - 2 : Create a new class file under Java Resource by giving package and class name. Then implement the server side method to publish.  

Simple Web Service using SOAP


STEP - 3 : After finishing the server side method implementation, select New -> Others and type "web" in Wizards, where you can see Web Service under Web Services list. 

Simple Web Service using SOAP


STEP - 4 : Click next and select the class which you implemented the method to publish under Service implementation drop down box. As already we are ready with Develop service, so we have to
Assemble service
Deploy service
Install service
Start service 
Test service

to make Web Service server ready with publishing the service which we have implemented. So that just passing the WSDL (Web Services Description Language) to client they can understand the server implementation and can consume our service easily. Basically its XML which used to describe the functionality offered or published by a web service. For more details on WSDL you can refer to WSDL wiki.

Simple Web Service using SOAP


STEP - 5 : Our Web Service server created successfully and we are ready to test our service. In next screen you can see SOAP Binding and service created with WSDL. You can pass input parameter and can test the service as below 

Simple Web Service using SOAP


And also we can see SOAP request and response by switching from form to source in result tab as below. 

Simple Web Service using SOAP


STEP - 6 : Next you can check your WSDL file have created correctly or not in your web browser by passing. http://localhost:8080/MyServer/services/MyClass?wsdl

Simple Web Service using SOAP



We have done with server implementation by creating the service and publishing with the help of Eclipse of IDE. Next important that we are going to localhost as our web server so we should not stop the server which running. In real-time we will deploy our service in some web servers and we will access our service through internet. Where as for our demo we are localhost for both server and client. 

Next go-head and create the client and consume the service which we have published above. For that we need to create the client application given below. 


Client Program:

STEP - 7 :  Create a Dynamic Web Project (File -> New -> Dynamic Web Project).

Simple Web Service using SOAP


STEP - 8 : Next we need to create stub from WSDL file. For this server where we have published need to be running and as discussed above we haven't stopped the server which we have started while creating our server. 
For creating Web Service Client we need to select New -> Other and type "web" in the Wizards as given below and select the Web Service Client under Web Services tab.

Simple Web Service using SOAP


STEP - 9 : Click Next and pass the WSDL url in Service definition text box and set as Test client and click Finish which will read the WSDL file and generate the java stub code. 

Simple Web Service using SOAP


Once you finished we can see the Java stub created along with Service and Proxy classes. Next we can see the list of method(s) published by server. By selecting the method we can test directly from eclipse by giving inputs as below image.

Simple Web Service using SOAP


STEP - 10 : Next we need to write a client program to invoke the remote method using SOAP Web Services. Create new class called MyClient as below image.

Simple Web Service using SOAP


STEP - 11 : Just implement the client by using endpoint URL and service instance and test your Web Service using SOAP.

Simple Web Service using SOAP







Deep Copy in Java


Deep Copy in Java
In our earlier tutorial we have seen about Shallow copy and how we can implement and how its works in Java. Same way we will see about Deep copy in this tutorial.

Deep copy - by name itself we can identify as its copy complete Object in-depth while cloning any instance. In Shallow copy we have seen that Object which holds another Object will not be copied and only holds the address reference. Where as in Deep copy it copies those Objects also and creates the instance for those Objects. Apart from this difference Deep copy is same as Shallow copy like, explicitly we need to type cast to our class and Constructors will not be called in our cloning class, but Object which contains other Object class constructors will be called while cloning from clone() method instance creation. 


We will see same example which we have seen in Shallow copy and make changes only in our clone() method to implement Deep Copy.


public class Subject{
 
 String name;
 
 public Subject(){
  System.out.println("Inside Default Constructor");
 }
 
 public Subject(String name){
  System.out.println("\nInside Constructor");
  this.name = name;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 } 
}



public class Student implements Cloneable{

 String name;
 Subject sub;
 
 public Student(String name, String sub){
  this.name = name;
  this.sub = new Subject(sub);
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Subject getSub() {
  return sub;
 }
 public void setSub(Subject sub) {
  this.sub = sub;
 } 
 
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return new Student(name, sub.getName());
 }
}



public class DeepCopy {

 public static void main(String[] args) throws CloneNotSupportedException {
  
  Student stu = new Student("Raj", "Hindi");
  
  System.out.println("\nOriginal Student Name: "+stu.getName());
  System.out.println("Original Student Sub : "+stu.getSub().getName());
  
  // Cloning the original Object and Explicitly type casting 
  Student stu1 = (Student)stu.clone();
  
  System.out.println("\nClone Student Name: "+stu1.getName());
  System.out.println("Clone Student Sub : "+stu1.getSub().getName());
  
  stu1.setName("David");
  
  
  /*
   * In Deep copy cloned Object will hold complete copy of original Object
   */
  stu1.getSub().setName("Tamil");
  
  System.out.println("\nOriginal Student Name: "+stu.getName());
  System.out.println("Original Student Sub : "+stu.getSub().getName());
  
  System.out.println("\nClone Student Name: "+stu1.getName());
  System.out.println("Clone Student Sub : "+stu1.getSub().getName());
 }
}


OUTPUT:


Inside Constructor

Original Student Name: Raj
Original Student Sub : Hindi

Inside Constructor

Clone Student Name: Raj
Clone Student Sub : Hindi

Original Student Name: Raj
Original Student Sub : Hindi

Clone Student Name: David
Clone Student Sub : Tamil



In above output we can see Subject name ("Tamil") has changed only for the cloned Object, where as in Shallow copy it holds the address of Object. 
    




Difference between Object class equals() and String class equals()


String class equals()


In this tutorial we will see about what is the difference between Object class equals() and String class equals() method. Before discussing on difference on both methods lets see about both classes. We all knows that Object class is the base class for all the classes the Java. Totally 12 methods are there in Object class and each methods can be Overridden while we implement our
own class on necessary. 
Lets see on how equals() method implemented in both the classes.

Object Class:

equals() method in Object class used to compare whether some other Object is "equal to" this one. It compares only the Object level are same in both the sides. And also we need to note that it is necessary to override hashCode() method whenever equals() method is overridden, as to maintain the general contract for the hashCode method, which states that same objects must have equal hash codes. 
It will return only of both the Objects are same else it will return false.


String Class:

Basically equals() method in String class is overridden from Object class and used to compare whether some other Object is "equal to" this one, along with also Objects will be typecast to String and each character wise comparison will be made in equals() method. 
First it will check for both the Objects are same and in case if both the Objects are same it will return true else true if the given object represents a String equivalent to this string, false otherwise.

Lets see code of both the equals() method in Object class and String class.


equals() method in Object class:

public boolean equals(Object obj) {
 return (this == obj);
}


equals() method in String class:

public boolean equals(Object anObject) {
 if (this == anObject) {
  return true;
 }
 if (anObject instanceof String) {
  String anotherString = (String) anObject;
  int n = count;
  if (n == anotherString.count) {
   char v1[] = value;
   char v2[] = anotherString.value;
   int i = offset;
   int j = anotherString.offset;
   while (n-- != 0) {
    if (v1[i++] != v2[j++])
     return false;
   }
   return true;
  }
 }
 return false;
}



As we discussed above whenever equals() method overridden then we need to override hashCode() method also to maintain the general contract for the hashCode method. In that case String class also need to Override hashCode() method, lets see the hashCode() method which present in the String class.

hashCode() method in String class:


public int hashCode() {
 int h = hash;
 if (h == 0) {
  int off = offset;
  char val[] = value;
  int len = count;
  for (int i = 0; i < len; i++) {
   h = 31 * h + val[off++];
  }
  hash = h;
 }
 return h;
}











Shallow copy in Java


Shallow copy in Java


In one of our earlier tutorial we have seen about Java clone. In this tutorial we will see about Shallow Copy with simple example code. Also we will about What is Shallow Copy and how its works. Before we knowing about Shallow Copy or Shallow Clone we need to know about what is clone and how its working in Java upon Objects.

As already we have seen in our previous tutorial Clone is nothing but the process of copying one Object to produce the exact copy, but not guaranteed for all Objects can be cloned. Suppose if the Object is not supported for cloning then we can't make another copy, in that case we will get CloneNotSupportedException Exception. If the class is Fully singleton class and as per rule we can't make another copy of the class, hence it will be a best example for clone not allowed. Cloning can be divided into two types as 

  • Shallow Copy 
  • Deep Copy

In this tutorial we will see about only Shallow copy with simple example code and how its working. Shallow copy is nothing but default clone implementation where it create new instance and copy all the field of object to the new instance and returns the Object type.  Object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, it holds just the address reference of the other Objects rather copying complete instance is called Shallow copy. 

Explicitly we need to type cast to our class as given in below example. Basically if a class need to support cloning then we need to implement Cloneable interface and need to Override clone method also. 

Now all we know that clone will be Shallow or Deep copy to create a new copy of the class object. Here interviewer will interrupt and put a question like when we clone object whether Class constructor will be called or not? Suddenly our ears will open widely and start thinking. Answer will be NO, while cloning any class object constructor will not be called. 

Lets see simple example for Shallow copy and how its works.


public class Subject{
 
 String name;
 
 public Subject(){
  System.out.println("Inside Default Constructor");
 }
 
 public Subject(String name){
  System.out.println("Inside Constructor");
  this.name = name;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 } 
}



public class Student implements Cloneable{

 String name;
 Subject sub;
 
 public Student(String name, String sub){
  this.name = name;
  this.sub = new Subject(sub);
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Subject getSub() {
  return sub;
 }
 public void setSub(Subject sub) {
  this.sub = sub;
 } 
 
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return super.clone();
 }
}



public class ShallowCopy {

 public static void main(String[] args) throws CloneNotSupportedException {
  
  Student stu = new Student("Raj", "Hindi");
  
  System.out.println("\nOriginal Student Name: "+stu.getName());
  System.out.println("Original Student Sub : "+stu.getSub().getName());
  
  // Cloning the original Object and Explicitly type casting 
  Student stu1 = (Student)stu.clone();
  
  System.out.println("\nClone Student Name: "+stu1.getName());
  System.out.println("Clone Student Sub : "+stu1.getSub().getName());
  
  stu1.setName("David");
  
  
  /*
   * In shallow Object contains other Objects which will have only
   * the address reference. Hence by below line Language will change 
   * in both the Objects (Original as well as in Cloned)
   */
  stu1.getSub().setName("Tamil");
  
  System.out.println("\nOriginal Student Name: "+stu.getName());
  System.out.println("Original Student Sub : "+stu.getSub().getName());
  
  System.out.println("\nClone Student Name: "+stu1.getName());
  System.out.println("Clone Student Sub : "+stu1.getSub().getName());
 }
}


OUTPUT:


Inside Constructor

Original Student Name: Raj
Original Student Sub : Hindi

Clone Student Name: Raj
Clone Student Sub : Hindi

Original Student Name: Raj
Original Student Sub : Tamil

Clone Student Name: David
Clone Student Sub : Tamil



In above output we can see Subject ("Tamil") has changed for both the Objects, original as well as Cloned Object as we have changed Subject Name only for cloned Object in our code. 
Its the example for Shallow copy where Object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, it holds just the address reference of the other Objects rather copying complete instance into cloned instance. 






What is Class.forName and how its working


In this tutorial we will see about what is Class.forName and few questions which each Java Programmer needs to know in it. 

  • What is Class.forName?
  • In which package "Class" present?
  • What is the return type of Class.forName and how its working?
  • What are all Exceptions/ Error thrown by Class.forName method?

What is Class.forName?



"Class" is a Java class with various methods defined in JDK. forName is a static method in "Class" class with 2 different parameterized (Method Overloading) as given below.

public static Class<?> forName(String className)
public static Class<?> forName(String name, boolean initialize, ClassLoader loader)

Class.forName is used to create the instance or object dynamically at run-time. 


In which package "Class" present?

"Class" class present in java.lang package. 


What is the return type of Class.forName and how its working?

Returns the Class instance associated with the class or interface with the given class name String. 
For example, if we need to create the instance dynamically for com.javadiscover.MyClass then following code will return the runtime Class descriptor 

MyClass obj = (MyClass) Class.forName("com.javadiscover.MyClass")


What are all Exceptions/ Error thrown by Class.forName method?

There are 3 types of Exception and Error will be thrown by forName method. They are

LinkageError - if the linkage fails
ExceptionInInitializerError - if the initialization provoked by this method fails
ClassNotFoundException - if the class cannot be located