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?

4
  • 2
    Interesting question. The Javadocs for String() state "Note that use of this constructor is unnecessary since Strings are immutable. " Commented Sep 14, 2012 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 Commented Sep 14, 2012 at 18:38
  • 1
    just for init ` Initializes a newly created String object so that it represents an empty character sequence.` Commented Sep 14, 2012 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. Commented Oct 30, 2017 at 9:46

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

5 Comments

a string literal can be GC-ed. tho some common ones are probably strongly referenced throughout the jvm life.
I've heard that interned string can be GC'ed starting in Java 7.
I'm having a really hard time thinking of a scenario where it actually matters if an instance of an empty string can be garbage collected or not.
"" goes in String Constant (Literal) pool, while new String () goes on heap.
"This will not be garbage collected ever" - highly incorrect.
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.

2 Comments

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 edited, my answer did suggest the two were equivalent.
3

Small example... String can be garbage collected

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

instead of

System.out.println(1 + "" + 2);

Comments

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)?

Comments

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

2 Comments

This is a good explanation of what new String(existingString) is useful for, but the question was actually about new String() with no arguments. :-/
Yeah, you're right, I got carried away a bit. :) I'll try to update the answer...
-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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.