Basically there are three way to convert an primitive value to string so that if we have requirement to use that primitive as a string then we can you this concept and way of conversion but now the point is out of these three way which one is the best and take less time and doesn't have any performance issue.

The three ways of converting primitive into string are :

1. Using Empty string
2. Using valueOf() with String class
3. Using toString() with Wrapper class.

Using Empty String

With the use of an empty string we are creating an new string in the constant string pool and if that string literal is already present in the pool then it will create the object in the heap which points to the pool literal object and return the heap memory address to its original object. For ex-

public class prog {

    public static void main(String[] args) {

 String s=""+10;
 String x1="java10";
 String x2="java"+10;
 System.out.println(x1.equals(x2)); // true
 System.out.println(x1==x2);    // false
 System.out.println(x1.hashCode()==x2.hashCode());//true

    }

}

In the above example ( x2== x1 ) will give false that means s2 and s1 both are different object and which proves that x1 literal get stored in string pool first and then while storing s2 literal it will first check the pool, if present then it will create an new object in the heap memory if we are using new operator that means internally  String is created with the use of ' new ' operator. 

Using valueOf() with String class

Another option for making a primitive value to string value is the use of valueOf( int i ) defined static in the String class, which return string value and take integer value from its integer type parameter. Here i have used only int type but valueOf() can be used with any primitive type. For ex- 

public class prog {

    public static void main(String[] args) {

 int x=10;
 String s1=String.valueOf(x);
 System.out.println(s1); 
 
     }

}

using valueOf() which it self used Integer.toString( int, int ) internally to convert it into string type value.

Using toString() with Wrapper class

Every wrapper class is having overridden toString() method with parameter as any primitive type. So we have one more option to make a primitive data as string type by using toString( int i ) . Here also i have used int type but toString() is available with any primitive type as argument. For ex-

public class prog {

    public static void main(String[] args) {

 int x=10;
 String s1=Integer.toString(x);
 System.out.println(s1); 
 
     }

}

toString() method internally uses character array concept to create an String. So this is the most efficient way of converting into string value.

So it is recommended to use any of the either valueOf() or toString().

Note: It is not recommended to convert with the use of empty string . 
String is a reference data type and hence string literals are treated as object and get stored in the string constant pool. We must have to define any string within double-quote otherwise it will give compilation error. String can be represented in two form either with using ' new ' operator or without using new operator.

Two way of string representation in java :
1. Without using new operator
2. With using  new operator.

Without using new operator

String can be represented without using new operator that means we are directly assigning string value to its reference. If we are defining like this then first it will search for the string literal whether it is present in the String pool or not. If it is present then simply it returns the reference of the existing object to the current reference. For ex-

public class A {

 public static void main(String[] args) {

    String s = "java";
           String s1= "java";
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 }
}


In the above program with the first statement i.s String s="java", it will search in the string pool whether that string literal is present or not. If it is present in the pool then it will return the reference to the reference variable 's' which also starts pointing to that object.



With the second statement again it will start searching in the string pool , if present then return the reference variable and if not then create the object in the pool and then return the reference. 

Important points regarding Creating string without new operator

1. First search in the string pool whether string literal is present or not.
2. If present in the pool then return the reference.
3. If not present in the pool then crate and object and return the reference of that object.

With using new operator 

With the help of new operator it is definitely going to create an object. First it will search in the string pool that whether that string literal is present or not , if not present then it will create an object in the pool itself and if present then it will create an object in the heap memory and that memory will hold the reference of the already present literal in the pool. So with the above statement its confirm that with the use of new operator it is going to create an object but in heap or in pool it all depends upon the string literal's presence in the pool.
For ex- 

public class A {

 public static void main(String[] args) {

    String s = new String("java");
           String s1= new String("java");
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 } 
}

In the above for the first statement it will search in the pool whether string literal " java " is present in the pool or not , if not then create the object in the pool itself and if present in the heap memory and return the reference of the already stored object to the reference variable " s ". 

For the second its the string literal " java " is surely present in the pool so JVM will create object in the object in the heap memory and return the reference to that object and that object reference value is returned to the " s1 " reference variable.

Example with and without new operator 

public class A {

 public static void main(String[] args) {

           String s="java";  //without new operator 
           String s1="java";
    String s2 = new String("java"); // with new operator
           String s3= new String("java"); // with new operator
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 } 
}

From the above example:

String s = "java" ---> Create object in the String pool ( if not present )
String s="java"---> Return the reference of the object present in the pool .
String s1= new String("java") --> Create the String object in the heap.
String s2=new String("java")--> Create the String object in the heap.

Diagram showing how memory is assigned in the heap and string pool.



In the above diagram we can see that s2 and s3 contain the reference of the object created in the heap memory and which itself contains the reference of the string pool object.


But in case of without using new operator, always reference value is returned and it is not going to create any object in the heap memory. This is the major difference between the string object with and without using new operator. 
It is the manually implemented coding for doing cloning. This concept has came to overcome the limitation found with shallow cloning which fails to clone the data member. Through deep cloning we can be able to cover up the problem with the shallow cloning. Now with the help of deep cloning we can able to clone the object members as well but to achieve this we don't have any predefined method, so we need to write our own code. Deep Cloning is just a term to indicate that we are also cloning the object members.

To achieve deep cloning we need to override the clone method and need to create an object of the object member so that we have other object  and need to copy return that object to the clone object.

See the example below then you will be more clear about the above statement written.

Example showing Deep Cloning

class E{
    int y=40;
    String s1="tutorial";
    public E(int y2, String s12) {
 this.y=y2;
 this.s1=s12;
   }
   public E(){}
 }

public class deepCloning implements Cloneable{

    int x= 20;
    String s="java";
    E e;
  
   deepCloning(int x2, String s2, E e1){ //To initialize the property 
 this.x=x2;
 this.s=s2;
 this.e=e1; 
   }
   public deepCloning() {
 e=new E();
   }
   protected Object clone(){   //overridden clone() method 
 deepCloning d2=null;
 E e1= new E(this.e.y,this.e.s1);
 d2=new deepCloning(this.x,this.s,e1);
 return d2;
   }

public static void main(String[] args) {

        deepCloning d = new deepCloning();
 deepCloning d1=null;
 try{
  d1=(deepCloning)d.clone();// Cloning statement 
 }catch(Exception e){
  e.printStackTrace();
 }
 System.out.println(d);
 System.out.println(d1);
 d1.e.y=30;
 System.out.println(d1.e.y);
 System.out.println(d.e.y);

 }  
}

In the above code we can see that clone method is overridden to our class in which we try to create and separate object for the class E and also create and object of the current object to return the class E object so that the clone object will have that reference value for its Object member. 

And all the constructor used in the respective class to initialize the property otherwise there may have chance to throw NullPointerExcpetion
It is a default cloning in java implemented by the Java vendor simply by using one predefined method in the Object class i.e clone().  Using shallow cloning we can only be able to clone the member of the class but fails to clone object members of the class. To clone the object member we need to write our own code which is also called as Deep Cloning.

To achieve shallow Cloning we need to implement Cloneable interface and need to call the clone() method with the object of the class whose object is to be cloned but it returns the Object class object so need to type-cast to its respective class type.

Example showing shallow cloning :

public class deepCloning implements Cloneable {

    int x= 20;
    String s="java";
 
  public static void main(String[] args) {
     deepCloning d = new deepCloning();
     deepCloning d1=null;
      try{
 d1=(deepCloning)d.clone(); // Cloning statement 
      }catch(Exception e){
 e.printStackTrace();
       }
 System.out.println(d);    // Original Object
 System.out.println(d1);   // Cloned Object
        System.out.println(d.x);  // 20 as output
 System.out.println(d1.x); // 20 as output
 d1.x=30;                  // Value changed to 30 by 
                                     cloned object
 System.out.println(d.x);  // 20 as output
 System.out.println(d1.x);//30 as output(not affecting d) 

 }
}

In the above code
d   = Original Object
d1 = Cloned Object
If we try to change the object d will not reflect on object d1 and vice-versa.

What if we are not implemeting the Cloneable interface ?
If we are not implementing Cloneable then it will Runtime error saying CloneNotSupportedException. So its mandatory to implement Cloneable Interface which is marker interface to indicate JVM that the object of that implementing class is to be cloned.

Example showing how shallow Cloning fails to clone Object member

class F{

     int x=30;
     String s="java";
}

   public class deepCloning implements Cloneable{

 int x=40;
 String s1="tutorial";
 F f;

 deepCloning(){
     f = new F();
 }
   public static void main(String[] args) {
 
 deepCloning sc = new deepCloning();
 deepCloning sc1=null;
 try{
      sc1=(deepCloning)sc.clone();//Cloning statement 
 }catch(Exception e){
      e.printStackTrace();
 }
 System.out.println(sc.f.x);  // 30 as output
 System.out.println(sc1.f.x); // 30 as output
 sc.f.x=60;                 // changing the x value of f
 System.out.println(sc.f.x); // 60 as output
 System.out.println(sc1.f.x);// 60 as output
 }

}

In the above code even if i tried to change the value of  instance variable x of class F through deepCloning class object, the value get changed but by accessing with the cloned object it result the changed value which indicated that cloned object's object member f is also pointing to the same object. To avoid this type of problem we have the concept of deep cloning. We can see the last two line of the above program that result of both line even if in the previous line i modified the value of x to 60. 


Diagrammatic representation of the above program

Diagram of Shallow Cloning

                                       ( Above diagram showing the shallow cloning )

What is the problem with the shallow Cloning ?

While Cloning it fails to clone the object member. As we can see in the above example while cloning it simple copies the reference value of the ' f ' to the cloned object which also point the object which was pointing by the original object;s object member. 
Cloning is a concept used to create a new object of the existing object. It means creating another object in the memory same as the existing one by copying the content of it.

For cloning a object java vendor has provided a method i.e clone() method in the Object class which is used to clone the object.

Clone() method is defined as protected in the Object and return the Object class object. Signature of the clone() is :-

protected Object clone() throws CloneNotSupportedException

This method throws one exception i.e java.lnag.CloneNotSupportedException, that means we need to handle this exception while using clone() in our program or we need to define the same exception with the throw keyword in the sub-class. 

We need to implement Cloneable interface to that class whose object we want to clone because by implementing JVM will got to know that this class is to be cloned.Syntax for Cloneable interface :

public interface java.lang.Cloneable{}

Cloneable interface is a marker interface that means without any method or member defined or we can say that empty interface. 

There are two types of cloning possible in java

1. Shallow Cloning ( default Cloning )
2. Deep Cloning ( Manual Cloning ) 

Shallow Cloning 

It is the Default implementation of the clone() method in the Object class. If we are using clone() method then it do shallow cloning. It is used to clone the data members of the existing class but fails to clone any of the member object. To overcome this limitation of the Shallow cloning there is a concept given by the java vendor is deep cloning. 

Deep Cloning 

It is manual implementation which has to be done by user itself. As not predefined method is available so we need to write our own code to do deep cloning and it is used to fulfill the limitations of the shallow cloning as it fails to clone the object member.   

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic