Is using a String() constructor as against string literal beneficial in any scenario? Using string literals enable reuse of existing objects, so why do we need the public constructor? Is there any real world use? For eg., both the literals point to the same object.
String name1 = "name";//new String("name") creates a new object.
String name2 = "name";
Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.
You make a constructor public if you want the class to be instantiated from any where. You make a constructor protected if you want the class to be inherited and its inherited classes be instantiated.
Putting private constructor is pretty much useless for this reason. @Will: Not if you use reflection. Declaring constructors private is intended to prevent instantiation (barring reflection), but preventing subclassing is a side effect, not the intent. The appropriate tool for this is declaring the class final .
Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.
One example where the constructor has a useful purpose: Strings created by String.substring()
share the underlying char[]
of the String
they're created by. So if you have a String
of length 10.000.000 (taking up 20MB of memory) and take its first 5 characters as substring then discard the original String
, that substring will still keep the 20MB object from being eligible for garbage collection. Using the String constructor on it will avoid that, as it makes a copy of only the part of the underlying char array that's actually used by the String
instance.
Of course, if you create and use a lot of substrings of the same String
, especially if they overlap, then you'd very much want them to share the underlying char[]
, and using the constructor would be counterproductive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With