Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't String() constructor private?

Tags:

java

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";
like image 591
robbin Avatar asked Nov 16 '10 20:11

robbin


People also ask

Can the constructor be private?

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.

Why are constructors public?

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.

What is the correct reason for not declaring a constructor as private?

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 .

Why would a constructor be private?

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.


1 Answers

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.

like image 83
Michael Borgwardt Avatar answered Sep 18 '22 16:09

Michael Borgwardt