13

I was looking into the String API and suddenly I came across one String empty Constructor i.e. we can construct an empty String object using String s = new String()

I wonder is there any use of it?

Anand
  • 20,708
  • 48
  • 131
  • 198
  • 2
    Interesting question. The Javadocs for `String()` state "Note that use of this constructor is unnecessary since Strings are immutable. " – Steve Kuo Sep 14 '12 at 18:38
  • 1
    I think if yoy use not initialized s object java give you null pointer exeption.. and such s contains empty string – Aliaksei Bulhak Sep 14 '12 at 18:38
  • 1
    just for init ` Initializes a newly created String object so that it represents an empty character sequence.` – huseyin tugrul buyukisik Sep 14 '12 at 18:38
  • 1
    This is a good question, on topic, and should not be deleted. The existence of that constructor indeed seems odd, and one might wonder whether it was a mistake by the library designers, perhaps retained only for backwards compatibility, or whether it had a subtle use case. – Raedwald Oct 30 '17 at 09:46

6 Answers6

11

Ofcourse.....

String s = new String();

will create a Non-literal String object on the heap, which will be garbage collected.

where as

String s = "" ;

will create a String Literal. This will not be garbage collected ever, if it is reachable through the default loader.

See this link below to a question which I asked. This may not be directly related to your question, but it will certainly help you grasp the concept firmly.

Is String Literal Pool a collection of references to the String Object, Or a collection of Objects

Community
  • 1
  • 1
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
4

It creates the empty string, which appears to have some limited use.

If you'll be building up a String by concatenating, and aren't using e.g. StringBuiler, your code can begin as one of the following.

String result = new String();
String result = "";
String result = "first part of string";

// ...
result += "append to the result";

The first two aren't equivalent, and you should prefer to initialize with "" since this can take advantage of string interning.

pb2q
  • 58,613
  • 19
  • 146
  • 147
  • No point to call `new String()` if you can use the literal "". These two aren't equivalent, because the constructor creates a new instance, but the "" literal uses the instance interned in a runtime pool. – Natix Sep 14 '12 at 18:53
  • @Natix edited, my answer did _suggest_ the two were equivalent. – pb2q Sep 14 '12 at 18:56
3

Small example... String can be garbage collected

System.out.println(1 + new String() + 2);

instead of

System.out.println(1 + "" + 2);
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
0

According to the documentation, this constructor creates an empty sequence.

public String()

Initializes a newly created String object so that it represents an empty character sequence. Note that use of this constructor is unnecessary since Strings are immutable.

If you want an empty sequence, it makes sense.

But normally, it wouldn't be necessary to use the empty constructor before you make changes to it, since you are not changing the String. In fact, when you change using the operator += for example, you are creating another immutable String, and not changing one.

Check this question about this subject: How do String objects work (like immutable objects)?

Community
  • 1
  • 1
gdfbarbosa
  • 825
  • 3
  • 10
  • 21
0

Some background first

Because Strings in Java are immutable, they are also "interned" - that means that all the string literals in the loaded classes are kept in a pool, so there is usually only one instance of each unique string literal in memory at one time. It is an application of the flyweight pattern, similar pools are also kept for Integer and other primitive wrapper objects (but only for a limited number of small values).

Because of this mechanism, identity comparison of string literals (even from different classes) is usually possible (although you should always use equals method when comparing strings for safety and consistency):

System.out.println("hello" == "hello"); // true

Now, if you use the default string constructor, you get an instance of an empty string, but it is a new instance, as stated in JavaDoc:

Initializes a newly created String object so that it represents an empty character sequence. Note that use of this constructor is unnecessary since Strings are immutable.

Such new instance is different from the interned empty string, resulting in:

System.out.println(new String() == ""); // false

But as I said, only string literals are automatically interned - that means strings created manually by StringBuilders, from char arrays etc. are not interned. You can use the String.intern() method to put such a string into the pool manually.

Now for some real scenario

Well all this is nice indeed, but I still haven't answered why this constructor exists. Well, Java strings are just smart wrappers over char arrays and some distinct string objects can share their internal arrays.

If I create a very long string (by reading from a stream for example), then this instance isn't interned (as said above), so it will be garbage collected after the variable that referenced it gets out of scope. But if do this:

String longString = readVeryLongString();
String shortString = longString.subString(0, 10);

... then the new shortString will not copy first 10 characters from the longString and put them into its own new char array. No, it will reference the original array, using only first 10 chars from it.

Now, if the shortString variable has longer life (for example is put into some static context), then the underlying char array will not be garbage collected (even if the original longString variable already got out of scope). This is one of the ways how to create a memory leak in Java.

Now, the default string constructor comes to the rescue! If I change the code above to this:

String longString = readVeryLongString();
String shortString = new String(longString.subString(0, 10));

... then the shortString will be a new string instance that made a new internal char array by copying only the 10 required chars from the original string returned by the subString method.


A nice article illustrating this subject:

http://illya-keeplearning.blogspot.cz/2009/03/java-string-internals.html

Natix
  • 14,017
  • 7
  • 54
  • 69
  • 1
    This is a good explanation of what `new String(existingString)` is useful for, but the question was actually about `new String()` with no arguments. :-/ – ruakh Sep 14 '12 at 20:16
  • Yeah, you're right, I got carried away a bit. :) I'll try to update the answer... – Natix Sep 14 '12 at 20:34
-1

to create an empty string,call default constructor as String s new String();

will create an instance of String with no characters in it.

Neeraj singh
  • 257
  • 1
  • 8
  • 18