views:

742

answers:

11

We normally create objects using the new keyword, like:

Object obj = new Object();

Strings are objects, yet we do not use new to create them:

String str = "Hello World";

Why is this? Can I make a String with new?

+7  A: 

It's a shortcut. It wasn't originally like that, but Java changed it.

This FAQ talks about it briefly. The Java Specification guide talks about it also. But I can't find it online.

Malfist
A: 

Feel free to create a new String with

String s = new String("I'm a new String");

The usual notation s = "new String"; is more or less a convenient shortcut - which should be used for performance reasons except for those pretty rare cases, where you really need Strings that qualify for the equation

(string1.equals(string2)) && !(string1 == string2)

EDIT

In response to the comment: this was not intended to be an advise but just an only a direct response to the questioners thesis, that we do not use the 'new' keyword for Strings, which simply isn't true. Hope this edit (including the above) clarifies this a bit. BTW - there's a couple of good and much better answers to the above question on SO.

Andreas_D
-1 - Bad advice. You should NOT "feel free" to use `new String(...)` UNLESS your application REQUIRES you to create a String with a distinct identity.
Stephen C
I know that. Edited the post for clarification.
Andreas_D
+6  A: 

String is subject to a couple of optimisations (for want of a better phrase). Note that String also has operator overloading (for the + operator) - unlike other objects. So it's very much a special case.

Brian Agnew
The + is actually an operator which is translated into a StringBuilder.append(..) call.
Willi
+2  A: 

Syntactic sugar. The

String s = new String("ABC");

syntax is still available.

Seva Alekseyev
This is not quite right. s=new String("ABC") will not give you the same results as s="ABC". See danben's comment.
Steve B.
Also, somewhat ironically, it will first create a String instance representing "ABC" inline - and then pass that as an argument to the constructor call which will create an return a String of identical value.
Andrzej Doyle
The valid use case for this constructor is `String small = new String(huge.substring(int, int));`, which allows you to recycle the big underlying `char[]` from the original `huge` String.
Pascal Thivent
+32  A: 

In addition to what was already said, String literals [ie, Strings like "abcd" but not like new String("abcd")] in Java are interned - this means that every time you refer to "abcd", you get a reference to a single String instance, rather than a new one each time. So you will have

String a = "abcd";
String b = "abcd";

a == b; //True

but if you had

String a = new String("abcd")
String b = new String("abcd")

then its possible to have

a == b; // False

(and in case anyone needs reminding, always use .equals() to compare Strings; == tests for object equality)

Interning String literals is good because they are often used more than once. For example, consider the (contrived) code:

for (int i = 0; i < 10; i++) {
  System.out.println("Next iteration");
}

If we didn't have interning of Strings, "Next iteration" would need to be instantiated 10 times, whereas now it will only be instantiated once.

danben
You have a missing closing bracket in your first sentence. Please fix it! It hurts my eyes so much =S
Dave
By using String a = new String("abcd"), does it means two string with similar content are present in memory.
changed
Right - the compiler will not necessarily check to see if such a String has already been interned (though you could certainly write one that did).
danben
Dave, taken care of.
danben
yes, this optimization is possible because strings are immutable and therefore can be shared without problems. the shared "asdf" handling is an implementation of the 'Flyweight' design pattern.
manuel aldana
No one said that it isn't possible, only that it isn't guaranteed. Was that your downvote?
danben
A: 

You can still use new String("string"), but it would be harder to create new strings without string literals ... you would have to use character arrays or bytes :-) String literals have one additional property: all same string literals from any class point to same string instance (they are interned).

Peter Štibraný
+5  A: 

Strings are "special" objects in Java. The Java designers wisely decided that Strings are used so often that they needed their own syntax as well as a caching strategy. When you declare a string by saying:

String myString = "something";

myString is a reference to String object with a value of "something". If you later declare:

String myOtherString = "something";

Java is smart enough to work out that myString and myOtherString are the same and will store them in a global String table as the same object. It relies on the fact that you can't modify Strings to do this. This lowers the amount of memory required and can make comparisons faster.

If, instead, you write

String myOtherString = new String("something");

Java will create a brand new object for you, distinct from the myString object.

jamie mccrindle
Hey ... it doesn't require "infinite wisdom" to recognize the need for some kind of syntactic support for string literals. Just about every other serious programming language design supports some kind of string literal.
Stephen C
Hyperbole has been reduced to stun, Captain :)
jamie mccrindle
A: 

Class String is a special class. Lot of things you can do with Strings which you cannot with others. E.g. string1 + string2 and also string1 += string2.

fastcodejava
To better qualify your statement. The special stuff is all provided by the compiler.
mP
+1  A: 

In Java, Strings are a special case, with many rules that apply only to Strings. The double quotes causes the compiler to create a String object. Since String objects are immutable, this allows the compiler to intern multiple strings, and build a larger string pool. Two identical String constants will always have the same object reference. If you don't want this to be the case, then you can use new String(""), and that will create a String object at runtime. The intern() method used to be common, to cause dynamically created strings to be checked against the string lookup table. Once a string in interned, the object reference will point to the canonical String instance.

    String a = "foo";
    String b = "foo";
    System.out.println(a == b); // true
    String c = new String(a);
    System.out.println(a == c); // false
    c = c.intern();
    System.out.println(a == c); // true

When the classloader loads a class, all String constants are added to the String pool.

brianegge
A: 

There's almost no need to new a string as the literal (the characters in quotes) is already a String object created when the host class is loaded. It is perfectly legal to invoke methods on a literal and don, the main distinction is the convenience provided by literals. It would be a major pain and waste of tine if we had to create an array of chars and fill it char by char and them doing a new String(char array).

mP
A: 

Javac does all the fun stuff under the hood when it sees a string constant. Fortunately :)

Thorbjørn Ravn Andersen