Java @ Desk: Core Java
Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Tuesday, November 25, 2014

How can we create a deep copy of an object in Java

10:15 AM 0
How can we create a deep copy of an object in Java?

Copying objects in Java

There are two ways of creating copies of objects (and arrays) in Java:
1. Shallow Copy
2. Deep Copy

What is "Deep Copy"?

A deep copy copies all fields, and makes copies of inner objects as well (unlike creating a copy of the memory address of the inner object). A deep copy occurs when an object, along with all the objects to which it refers, is copied as a whole. After a deep copy, if we change the property of the inner object in the copied object, it will not affect the respective property of the inner object in the original object.

How can we create a deep copy of an object?

We can achieve deep copy in 3 ways.
1. Serialize and de-serialize
2. Clone the Object correctly
3. Copy Constructor

If the object which we need to deep copy is simple, we can go for either the copy constructor approach or we can implement the clone correctly. But in most cases we will need to deep copy various objects of various complexities. The object graph may be much more complex which results in increased complexity of both the copy constructor and the clone methods. In this case we can go for the serialization approach. By using serialization, we can create deep copies of any object s that adhere to a set of rules by just one function.

Rules for deep copy using serialization to work correctly
1. All classes in the object graph should be serializable
2. Serialization should not be overridden such that new instances are not created, e.g. for singletons.

How to implement serialization?
We need to use a common utility class and provide a static method that will serialize and de-serialize the object, thus creating a deep copy of that object, and then return the copy. Serialization and deserialization of the object ensures that all the classes in the object graph are recreated in a new heap location.

Sample code illustrating deep copy through serialization/deserialization:

/**
 * Util Class
 *
 */
class CommonUtil{
 
 /**
  * Method to provide deep copy
  * @param obj - Object to be deep copied
  * @return Deep copied Object
  * @throws IOException
  * @throws ClassNotFoundException
  */
 public static <T extends Object> T getCopy(T obj) throws IOException, ClassNotFoundException{
  
  ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
  ObjectOutputStream objectOutStream = new ObjectOutputStream                                 (byteOutStream);
  objectOutStream.writeObject(obj);
  objectOutStream.flush();
  objectOutStream.close();
  byteOutStream.close();
  byte[] byteData = byteOutStream.toByteArray();

  ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
  T copy = (T) new ObjectInputStream(bais).readObject();
  
  return copy;
 }
}




What is "Shallow Copy"?


When we clone an object, only the values of that object get copied. The newly created object has an exact copy of the values in the original object. If any of the fields of the original object store references to other objects, then, just the reference addresses are copied (i.e., only the memory address is copied). So, manipulating the property of the inner object in a copied object after a shallow copy will result in the modification of the respective property of the inner object in the original object as well, as both points to the same address in the heap.

Sample code (with output) illustrating shallow copy:

class School implements Serializable, Cloneable {
 
 private String name;
 private Address address;
 
 public void setAddress(Address address){
  this.address = address;
 }
 
 public Address getAddress(){
  return address;
 }
 
 public void setName(String name){
  this.name = name;
 }
 
 public String getName(){
  return name;
 }
 
 @Override
 public String toString(){
  StringBuilder builder = new StringBuilder();
  builder.append("School Name: ");
  builder.append(name);
  builder.append(", ");
  builder.append("Address: ");
  builder.append(address.getAddress());
  return builder.toString();
 }
 
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return super.clone();
 }
 
}


class Address implements Serializable, Cloneable{
 
 private String address;
 
 public Address(){
  
 }
 
 public Address(String name){
  this.address = name;
 }
 
 public String getAddress(){
  return address;
 }
 
 public void setAddress(String address){
  this.address = address;
 }
 
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return super.clone();
 }
}

//Code to run application

School s1 = new School();
s1.setName("General School");
s1.setAddress(new Address("School 1 Address"));

School s2 = (School) s1.clone();// Deep copy by improper clone implementation
s2.getAddress().setAddress("School 2 Address");
  
System.out.println(s1);
System.out.println(s2);

Output:
School Name: General School, Address: School 2 Address
School Name: General School, Address: School 2 Address


Note here, that the change made to the value of "address" in the cloned object (s2) changed the value of "address" in the original object (s1) as well, as they both point to same object in the heap.



How Deep Copy can be implemented effectively in the above example:

1. Override clone Correctly
In the above case if we override the clone method in the School correctly we can create a deep copy.

@Override
protected Object clone() throws CloneNotSupportedException {
  
School clone = new School();
clone.setName(name);
clone.setAddress((Address)address.clone());
return clone;
}

2. Copy Constructor
We can provide a copy constructor in the School that will return a deep copy of the school. In school class provide the copy constructor

/**
 * Copy Constructor to get the copy
 * @return Copy of the school
 */
public static School getSchoolCopy(School school){
 School copy = new School();
 copy.setName(school.getName());
 copy.setAddress(new Address(school.getAddress().getAddress()));
 return copy;
}

And use copy constructor to provide the copy of the object

School s2 = School.getSchoolCopy(s1);

3. Serialize and de-serialize
Use the CommonUtil class (already explained above) to get the copy:

School s1 = CommonUtil.getCopy(s1); to get the clone of the object


The output of all three deep copy methods is:

School Name: General School, Address: School 1 Address
School Name: General School, Address: School 2 Address

Note here, that the change made to the value of "address" in the cloned object (s2) does not change the value of "address" in the original object (s1).

You can also use some third party libraries to create deep copies. Dozer and Kryo are two great libraries that serve this purpose. There is also Apache Commons that provides SerializationUtils.

NOTE:

1) Whenever we copy a Collection of objects we should always go for deep copy.
2) Copy method in the Collections class creates a shallow copy, and hence, modifying the objects in the copied collection will modify the object in the actual collection.

This post is written by Jerin Joseph. He is a freelance writer, loves to explore latest features in Java technology.

Wednesday, December 4, 2013

Reflection call getter methods of Pojo java

7:07 AM 2
Reflection call getter methods of Pojo

Consider a scenario where a POJO consists of 100's of fields with getters and setters. And you want to display values of all the fields.
To achieve this, writing System.out.println for each getter would be a very tedioius job as shown below

Consider a Person class with Name, Address, etc. fields. So to print each value as shown below you need to write Sysout for each field
System.out.println("Name - " + object.getName());
System.out.println("Address - " + object.getAddress());

Saturday, November 23, 2013

Google libphonenumber to validate phone number of all regions across the world

9:46 PM 0
Google libphonenumber to validate phone number of all regions across the world
Google has provided a jar libphonenumber.jar using which any number across the world from any country can be validated.

You can download the jar from this location - https://code.google.com/p/libphonenumber/
User interface for testing purpose - http://libphonenumber.appspot.com/
Specify any phone number and you will recieve all the details of the phone number

Friday, October 4, 2013

Java multipy, add, subtract, divide two numbers without using operators

2:32 AM 1
Java multipy, add, subtract, divide two numbers without using operators In Java, following operators are used to perform mathematical operations:
1) + - Addition
2) - - Subtraction
3) * - Multiplication
4) / - Division

Thursday, September 26, 2013

Print all permutations of String in java

4:51 AM 0














import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class StringPermutations {
    static Set permutationSet;

    static Set permutationResult = new HashSet();

    public static Set permutation(String string) {
        permutationSet = new HashSet();

        int length = string.length();
        for (int i = length - 1; i >= 0; i--) {
            shuffle(string.charAt(i));
        }
        return permutationSet;
    }

    private static void shuffle(char c) {
        if (permutationSet.size() == 0) {
            permutationSet.add(String.valueOf(c));
        } else {
            Iterator it = permutationSet.iterator();
            for (int i = 0; i < permutationSet.size(); i++) {

                String temp;
                for (; it.hasNext();) {
                    temp = it.next();
                    for (int k = 0; k < temp.length() + 1; k += 1) {
                        StringBuilder sb = new StringBuilder(temp);

                        sb.insert(k, c);

                        permutationResult.add(sb.toString());
                    }
                }
            }
            permutationSet = permutationResult;
            permutationResult = new HashSet();
        }
    }

    public static void main(String[] args) {
        Set result = permutation("abc");

        Iterator it = result.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

Monday, August 5, 2013

Difference between length and length() in java

4:26 AM 2
length() - This is a method in java. It is a static method of String class. It returns the length of a string object i.e. number of characters stored in an object.
length - This is a instance variable of array of array in java. It returns the length of an array i.e. number of elements stored in an array.

Wednesday, July 24, 2013

Serialize static variable in java

3:22 AM 0
Can we serialize static variable in java?
No. Since static members are associated with the class and they do not belong to the individual objects, they are not serialized. Static field values will be reinitialized to whatever value they are set to when the class is loaded.
Consider a below class with a static field with initial value as 10.

Person.java
 package com.serialization;  
 import java.io.Serializable;
 public class Person implements Serializable {  
   private static final long serialVersionUID = -8935100740005343248L;
   static int staticField = 10; 
   private String firstName;  
   private String lastName;  
   public Person(String firstName, String lastName) {  
     super();  
     this.firstName = firstName;  
     this.lastName = lastName;  
   }  

Serialization java example

2:55 AM 0
To implement a very basic example of Serialization in java, lets create Person.java that implements Serializable interface.
Person.java
 package com.serialization;  
 import java.io.Serializable;
 public class Person implements Serializable {  
   private String firstName;  
   private String lastName;  
   public Person(String firstName, String lastName) {  
     super();  
     this.firstName = firstName;  
     this.lastName = lastName;  
   }  

Tuesday, July 23, 2013

Serialization in java

5:43 AM 0
Serialization in java

What is serialization?
Serialization is a process to translate an object in a state/format that can be transferred over a network, stored in a file and the transmitted state/format can be used to get back the original object.
An object is converted to bytes and stored in a file. This process is called serialization.
Conversion of bytes into a original object is called de-serialization.

How to serialize an object in java?

Friday, July 5, 2013

Java beep sound example

11:56 PM 0
There are different ways to generate a beep sound in java. The general basic way to generate is to use java.awt.Toolkit class which has a default method to generate the beep sound. The other implementation is also shown below on how to generate beep sound in java.
 package test;  
 import java.awt.Toolkit;  
 import javax.sound.sampled.AudioFormat;  
 import javax.sound.sampled.AudioSystem;  
 import javax.sound.sampled.LineUnavailableException;  
 import javax.sound.sampled.SourceDataLine;  
 public class Beep {  
      public static float SAMPLE_RATE = 8000f;  
      public static void tone(int hz, int msecs) throws LineUnavailableException {  
           tone(hz, msecs, 1.0);  
      }  
      public static void tone(int hz, int msecs, double vol)  
                throws LineUnavailableException {  
           byte[] buf = new byte[1];  
           AudioFormat af = new AudioFormat(SAMPLE_RATE, // sampleRate  
                     8, // sampleSizeInBits  
                     1, // channels  
                     true, // signed  
                     false); // bigEndian  
           SourceDataLine sdl = AudioSystem.getSourceDataLine(af);  
           sdl.open(af);  
           sdl.start();  

Saturday, June 29, 2013

Access private field/member java using reflection

6:34 AM 0
We all know, in java we cannot access private members of a class outside that class. Private members are accessible only within the class.
In order to access private field/method or member outside the class, we need to use reflection in java.
Through reflection, private members are accessible outside the class also.

Before Reflection
After Reflection

Thursday, June 27, 2013

Different ways to create an/a object in java

5:35 AM 0
In java, an object of a class can be created in various ways. This is the most important as well as most common question asked in java interviews. There are 4 difference ways to create a/an object in java as described below:

1) Using new keyword
2) Using Class.forName()
3) Using clone()
4) Using object deserialization
Detailed explanation on different ways to create a object in java:

Consider a class as shown below:

Friday, June 21, 2013

Facade design pattern in java

1:58 AM 2
Facade is design pattern in java that helps to re design a poorly structured API into a well defined API. It provides a simpler interface to the client, but internally it interacts with complex components and get a job done for the client. It hides a complexity behind exposing a simpler interface to the client.

Consider a scenario, of an Employee Hiring consultancy that collects all the information of an employee going to join in some company. The information includes personal details, last employment details, last drawn salay, expected salary, desired location.
Now, lets say, there are different complex interfaces, one that returns employee personal information, one give employee past experience details and so on.
So, in this case, if a client need a complete list of information of one particular employe, there needs to give a call to lots of other interface.

Thursday, June 20, 2013

Proxy design pattern in java

5:37 AM 0
Proxy, as the name suggest, does the work what the real one should do. Proxy is some thing that performs the task what the real java object must perform to do.Typically, one instance of the complex object and multiple proxy objects are created, all of which contain a reference to the single original complex object. Any operations performed on the proxies are forwarded to the original object. Once all instances of the proxy are out of scope, the complex object's memory may be deallocated.

Why to use proxy?
There can be many instances, where real object wants the task to be performed by the proxy object. In this case, proxy first checks if the real instance object is available or not. It not create the new instance but if the object is already available, do not create the new instance, proxy instance will be used to perform the operation.

Friday, June 14, 2013

Decorator design pattern in java

4:50 AM 0
As the name suggest, it decorates some basic behaviour of an object. It is used to extend the behaviour of certain object. In implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance.

Use decorator pattern, to add responsibility to objects without affecting other objects.

Thursday, June 13, 2013

Adapter design pattern in java

5:07 AM 0
The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using an Adapter.

There is a SalaryCalculator.java class file which takes employeeId and annualPackage fields as input and returns the monthly inhand for that employee.

Tuesday, June 11, 2013

Prototype design pattern in java

4:39 AM 0
Prototype pattern is used where the application needs many instances of an same object with minimal changes. Hence the Cloneable interface is used in this where the clone of the object is returned.

Question arises why clone, why not new object creation if many instances are required?

In general, cloning or creating an object using new operator are same. But there are cases where new object creation would be heavy in cases where a constructor for an object does some heavy provessing. Say for example, creating a database connection. In this case, cloning would be much much cheaper.

Monday, June 10, 2013

Builder design pattern in java

6:40 AM 0
This design pattern breaks the complex object creation into simpler processes. The construction process remains the same to create different representations. Director controls the construction of the object and only the director knows what type of object to create.

This pattern helps the object creation in a step by step manner. It breaks the module into smaller pieces and the smaller pieces in integration gives the complex object.

Tuesday, June 4, 2013

Explain ways to run a java class

1:43 AM 0




1) Create a public static void main(String args[]) {……} in your class and run this java class to run the code inside the main block


2) The second way is to create a static block inside a class static {……} and run the java file. The code inside the static block will get executed.


public class RunJavaMain {

    public static void main(String args[]) {
        System.out.println("Main method is called");
    }
}
public class RunJavaStatic {

    static {
        System.out.println("This file is executed using main method");
        System.exit(0);
    }
}
The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:
Exception in thread "main" java.lang.NoSuchMethodError: main

As of Java 7, it stop working. It compiles fine but while execution it gives the error message

Friday, May 31, 2013

Sort ArrayList using Comparable in Java

10:29 PM 0













 package test;  
 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 public class PersonComparable implements Comparable<PersonComparable> {  
      private int age;  
      private String firstName;  
      private String secondName;  
      public int getAge() {  
           return age;  
      }  
      public void setAge(int age) {  
           this.age = age;  
      }  
      public String getFirstName() {  
           return firstName;  
      }  
      public void setFirstName(String firstName) {  
           this.firstName = firstName;  
      }