Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why String class is not Cloneable?

Tags:

java

string

clone

Why String class is not implementing Cloneable interface?

For example: (We write this type of code sometimes.)

String s1 = new String("Hello");

String s2 = new String("Hello");

Here s1!=s2;

So instead of doing this , if we could have done:

String s1 = new String("Hello");

String s2 = s1.clone();

This could be easy.

like image 896
Raj Avatar asked Mar 18 '14 18:03

Raj


1 Answers

The String class represents an immutable string. There would be no purpose to cloning a String. If you feel that you need to clone it, then you can just reuse the same reference and achieve the same effect.

Even if you could clone s1 as s2, then s1 != s2 would still be true. They'd still be references to distinct objects.

like image 164
rgettman Avatar answered Oct 01 '22 09:10

rgettman