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




Web Services in Java


In this tutorial we will see about Web Services in Java.


What are Web Services?


Web services are client and server applications that communicate over the World Wide Web's (WWW) HyperText Transfer Protocol (HTTP). As described by the World Wide Web Consortium (W3C), web services provide a standard means of interoperating between software applications running on a variety of platforms and frameworks. Web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions, thanks to the use of XML. Web services can be combined in a loosely coupled way to achieve complex operations. Programs providing simple services can interact with each other to deliver sophisticated added-value services. By Oracle Docs.


Before Web Services?

Before Web Services introduced we were using RMI (Remote Method Invocation), CORBA etc., to communicate third part services and methods. With the release of JDK version 1.1, Java has its own, built-in native ORB, called RMI (Remote Method Invocation). Where CORBA is an integration technology, not a programming technology which used in Java to communicate between other languages like C, C++, Ada, COBOL etc., Instead of digging to RMI or other client/ server we will focus only on Web Services in this tutorial. 


Types of Web Services?

There are 2 tyes of Web Services,
1. SOAP based (Simple Object Access Protocol) Web Services 
2. RESTful Web Services 


SOAP Web Services (JAX-WS)

SOAP web services use XML messages that follow the Simple Object Access Protocol (SOAP) standard, an XML language defining a message architecture and message formats. Such systems often contain a machine-readable description of the operations offered by the service, written in the Web Services Description Language (WSDL), an XML language for defining interfaces syntactically. Basically Client and Server communication will be in XML standard formats which gives flexibility to use any platform (Java, .NET, etc.,) and to use any OS (Windows, Unix, etc.,). Generally Server can be in any language and client can be any language where communication will be in common XML formats and standards.


RESTful Web Services (JAX-RS)


JAX-RS provides the functionality for Representational State Transfer (RESTful) web services in Java. REST is well suited for basic, ad hoc integration scenarios. RESTful web services, often better integrated with HTTP than SOAP-based services are, do not require XML messages or WSDL service–API definitions as like SOAP. By Oracle Docs.


Difference between SOAP and RESTful

  • SOAP is a Object oriented and REST is a resource oriented.
  • In place of security SOAP supports SSL and WS-Security and REST supports only SSL.
  • As performance wise SOAP will be better than REST
  • SOAP doesn't support caching and REST supports.
  • SOAP is heavy in message size with WS specific markup. where as REST is lightweight and no extra XML markups added. 
  • SOAP supports text and binary encoding and REST supports only text encoding.
  • SOAP uses WSDL to describe the services which we have exposed and in REST there is no formal definition.
  • Complexity of SOAP uses frameworks to develop and on other side REST is very simple in development without any frameworks. 
  • Protocols supported in SOAP are HTTP, SMTP, JMS and REST supports only HTTP.


According to project needs development team need to decide whether they need to go with SOAP or REST. 






Update or Edit XML File using DOM Parser


In our earlier tutorial we have seen how to read XML file using DOM and SAX Parser. In this tutorial we will see how to edit or update XMl file using DOM parser. We have used below sample XML to update using DOM parser.

SAMPLE XML:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<organization>
 <employee mode="permanent">
  <name>John</name>
  <empid>1234</empid>
  <designation>SE</designation>
  <technology>Java</technology>
 </employee>
 <employee mode="contract">
  <name>David</name>
  <empid>4545</empid>
  <designation>Manager</designation>
  <technology>.NET</technology>
 </employee>
</organization>


XML AFTER UPDATE: 

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<organization>
 <employee mode="permanent">
  <name>John</name> 
  <empid>1234</empid> 
  <designation>SE</designation> 
  <age>35</age> 
 </employee>
 <employee mode="permanent">
  <name>David</name> 
  <empid>4545</empid> 
  <designation>Senior Manager</designation> 
  <age>35</age> 
 </employee>
 <employee mode="permanent">
  <name>Steve</name> 
  <empid>5635</empid> 
  <designation>Lab Engineer</designation> 
  <age>38</age> 
 </employee>
</organization>


If we seen above XML we have modified such as
  • Deleting <technology> node from the XML
  • Updating attribute value from "contract" to "permanent" for 2nd employee
  • Updating <designation> node value from "Manager" to "Senior Manager"
  • Adding new <employee> element


Below example java code will be used to modify the XML as per given above. 


import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class EditXML {
 
 public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException {
  editMyXML("D:\\document.xml");
 }
 
 public static void editMyXML(String file) throws ParserConfigurationException, SAXException, IOException, TransformerException{
  
  DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = builderFac.newDocumentBuilder();
     Document doc = builder.parse(new File(file));

     System.out.println ("ROOT: " + doc.getDocumentElement().getNodeName());
        NodeList list = doc.getElementsByTagName("employee");
        System.out.println("No. Of Employees: " + list.getLength());
                
        for(int i= 0; i<list.getLength(); i++){
            Node node = list.item(i);
            if(node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element)node;
                String mode, name, empid, designation, technology;
                                
                mode = element.getAttribute("mode");
                
                NodeList nListName = element.getElementsByTagName("name");
                Element nElementName = (Element)nListName.item(0);
                NodeList tListName = nElementName.getChildNodes();
                name =((Node)tListName.item(0)).getNodeValue().trim();
                
                NodeList nListEmpId = element.getElementsByTagName("empid");
                Element nElementEmpId = (Element)nListEmpId.item(0);
                NodeList tListEmpId = nElementEmpId.getChildNodes();
                empid = ((Node)tListEmpId.item(0)).getNodeValue().trim();
                
                NodeList nListDesi = element.getElementsByTagName("designation");
                Element nElementDesi = (Element)nListDesi.item(0);
                NodeList tListDesi = nElementDesi.getChildNodes();
                designation = ((Node)tListDesi.item(0)).getNodeValue().trim();
                
                NodeList nListTech = element.getElementsByTagName("technology");
                Element nElementTech = (Element)nListTech.item(0);
                NodeList tListTech = nElementTech.getChildNodes();
                technology =((Node)tListTech.item(0)).getNodeValue().trim();
                
                // Updating only for 4545 (David) Employee
                if(empid.equals("4545")){
                 
                 // Updating MODE from "contract" to "Permanent"
                 node.getAttributes().getNamedItem("mode").setTextContent("permanent");
                 
                 // Updating Designation from "Manager" to "Senior Manager"
                 ((Node)tListDesi.item(0)).setTextContent("Senior Manager");
                }
                
                // Adding new Node called "age"
                Element nElementAge = doc.createElement("age");
                nElementAge.appendChild(doc.createTextNode("35"));
                element.appendChild(nElementAge);
                
                // Deleting "technology" Node
                element.removeChild(nElementTech);
            }
        }
        
        //Adding new employee
        addNewEmployee(doc, "permanent", "Steve", "5635", "Lab Engineer", "38");
        
        
        // Writing update XML file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();
  DOMSource source = new DOMSource(doc);
  StreamResult result = new StreamResult(new File("D:\\document.xml"));
  transformer.transform(source, result);
 }
 
 public static void addNewEmployee(Document doc, String mode, String name, String empId, String designation, String age){
  
  Element root = doc.getDocumentElement();
        
        Element element = doc.createElement("employee");
        root.appendChild(element);
        
  Attr attr = doc.createAttribute("mode");
  attr.setValue("permanent");
  element.setAttributeNode(attr);
  
  Element nElementName = doc.createElement("name");
        nElementName.appendChild(doc.createTextNode("Steve"));
        element.appendChild(nElementName);
        
        Element nElementEmpId = doc.createElement("empid");
        nElementEmpId.appendChild(doc.createTextNode("5635"));
        element.appendChild(nElementEmpId);
        
        Element nElementDesi = doc.createElement("designation");
        nElementDesi.appendChild(doc.createTextNode("Lab Engineer"));
        element.appendChild(nElementDesi);
  
  Element nElementAge = doc.createElement("age");
        nElementAge.appendChild(doc.createTextNode("38"));
        element.appendChild(nElementAge);
  } 
}