I saw following member in java.lang.String
:
private final char value[];
My question is:
Will following statement make a copy of the literal string into char[]
metioned above, while another copy of literal string also exists in the constant pool.
String b1 = new String("abc");
If so, didn't the constant pool meaning less? Or we should prevent use new() to create String with literal?
@Update:
So, according to the answers, why String
class need a char value[]
variable inside it, why not just refer to a single copy inside constant pool?
If create a string with new String("...")
, won't the literal be put into constant pool if not exists in pool yet?
According to my imagine, the only benefit to use the new String()
is that, it might be quicker than query a constant pool; or the constant pool has size limit, it will remove old constant value when size not enough? But I am not sure is this the way it works.
Conclusion
So, according to answers the new String()
should only be used by constant pool maintainer itself, we programmers don't.