I know that String
objects are immutable, and I can create String
object in heap (String s1 = new String("text1"
) and in string pool (String s2 = "text2"
). So what's the point of having an opportunity to create a String
out of string pool? Why Java implicitly doesn't create all String
object in the string pool? Maybe to prevent the processor from iteration through string pool if chances that some rare string would be there?
Asked
Active
Viewed 51 times
2

Denys_newbie
- 1,140
- 5
- 15
-
3Mostly `new String("text1")` is part of a demonstration or written by someone who doesn't know what they're doing. – khelwood Jan 25 '21 at 23:30
-
1Also, you don't really want every dynamically generated and short-lived String to become internalised. So things like Reader or StringBuilder should be able to create "normal" regular-heap, uncached String instances. – Thilo Jan 26 '21 at 00:22
1 Answers
3
If you look at it from the perspective of the new
operator it makes sense.
new
always allocates a new object. That goes for all classes across the board, no exception. It doesn't have any special case behavior for the String
class, nor any other class. It is completely class agnostic.
I don't see any need for an optimization to be added, either. Writing new String("literal")
is usually a mistake. Why bother speeding up a mistake?

John Kugelman
- 349,597
- 67
- 533
- 578