what is the use of clone() in real time scenario?

Answers were Sorted based on User's Feedback



what is the use of clone() in real time scenario?..

Answer / aravindareddy

Clone() method is used to create and return copy of the
object,The Cloneable interface defines a method called Clone
(), which can be used to clone an object in your java
program.The reason for making a copy of an object is if
you’re going to modify that object and you don’t want to
modify the caller’s object. If you decide that you want to
make a local copy, you simply use the clone() method to
perform the operation.

Is This Answer Correct ?    28 Yes 7 No

what is the use of clone() in real time scenario?..

Answer / aravinda reddy

Further to above a small update, clone will peform shallow
copy.Please execute below example and check the output.

public class CloneExamples {

public static void main(String[] args) {
ArrayList al = new ArrayList();

for(int i = 0; i < 10; i++ )
al.add(new Int(i));

System.out.println("al: " + al);

ArrayList al1 = (ArrayList)al.clone();

// Increment all al1's elements:
for(Iterator e = al1.iterator(); e.hasNext
(); )
((Int)e.next()).increment();

// See if it changed al's elements:
System.out.println("al: " + al);
System.out.println("al1: " + al1);
}
}

class Int {

private int i;

public Int(int ii) { i = ii; }

public void increment() { i++; }

public String toString() {
return Integer.toString(i);
}
}

o/p:
al: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
al: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
al1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

the old ArrayList and the cloned ArrayList are aliased to
the same objects

Is This Answer Correct ?    6 Yes 8 No

Post New Answer

More Core Java Interview Questions

What is java full form?

0 Answers  


What happens when you assigned a 'double' value to a 'String'?

8 Answers  


what is the need to set path in java? how many ways to set path in java? Explain breif?

5 Answers  


How can you debug the Java code?

6 Answers   BirlaSoft,


Is empty string in java?

0 Answers  






Can variables be used in java without initialization?

0 Answers  


Which is the class in java?

0 Answers  


what type of questions asked for barclays technologies pune please send urgent

0 Answers  


Explain 5 features introduced in jdk 1.7?

0 Answers  


is it mandatory to deaclare all variables public static fianl in interfaces?if i declare like in the below program, public interface A { public static final int I=0; int j=0; } in interface A,what is the difference between I,j?

2 Answers  


what are three ways in which a thread can enter the waiting state? : Java thread

0 Answers  


Can a class extend abstract class or interface? why

4 Answers   Wipro,


Categories