7

i want to know where to use string object(in which scenario in my java code). ok i understood the diff btwn string literal and string object, but i want to know that since java has given us the power to make string object, there must be some reason, at some point string object creation would be useful. so i want to know in which scenario can we prefer string object in place of string literal.

kaka
  • 7,425
  • 4
  • 19
  • 23
  • 6
    A string literal is a string object. – krock Jul 29 '10 at 06:03
  • At some point, that's more or less the same as asking why you should use `int` variables instead of numeric constants. – pascal Jul 29 '10 at 06:21
  • 1
    And that's not that trivial a question (`int` vs. constants). Leads to magic numbers vs. "not a global parameter, just need it this once..." etc. – Konrad Garus Jul 29 '10 at 06:25
  • Yeah, I think I remember seeing a language, or a compiler supposedly implementing a global dictionary of numeric constants. After something like `const int a = 1; *(int*)&a = 2;`, 1 becoming 2 **everywhere**... – pascal Jul 29 '10 at 06:37
  • Can you be more specific? It looks like most answers concentrate on `String s = new String("xx")`. Is it what you were talking about? – pascal Jul 29 '10 at 07:22

6 Answers6

6

In most situations, you should use String literals to avoid creating unnecessary objects. This is actually Item 5: Avoid creating unnecessary objects of Effective Java:

Item 5: Avoid creating unnecessary objects

It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed. Reuse can be both faster and more stylish. An object can always be reused if it is immutable (Item 15). As an extreme example of what not to do, consider this statement:

String s = new String("stringette"); // DON'T DO THIS!

The statement creates a new String instance each time it is executed, and none of those object creations is necessary. The argument to the String constructor ("stringette") is itself a String instance, functionally identical to all of the objects created by the constructor. If this usage occurs in a loop or in a frequently invoked method, millions of String instances can be created needlessly. The improved version is simply the following:

String s = "stringette";

This version uses a single String instance, rather than creating a new one each time it is executed. Furthermore, it is guaranteed that the object will be reused by any other code running in the same virtual machine that happens to con- tain the same string literal [JLS, 3.10.5]

There is however one situation where you want to use the new String(String) constructor: when you want to force a substring to copy to a new underlying character array like in:

String tiny = new String(huge.substring(0, 10));

This will allow the big underlying char[] from the original huge String to be recycled by the GC.

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • Could you explain why String `tiny = new String(huge.substring(0, 10));` is eligible for GC? On the other hand why `tiny = huge.substring(0, 10);` not eligible? – Sujee Jul 29 '10 at 07:14
  • 3
    @Sujee With `tiny = huge.substring(0, 10)`, `tiny` would use the **same** `char[]` than `huge`. With `String tiny = new String(huge.substring(0, 10))`, `tiny` would use a new (smaller) `char[]`, allowing the big one to be recycled. Check the sources for the details. – Pascal Thivent Jul 29 '10 at 07:24
  • There is a subtlety to using `new String(String)`; see http://stackoverflow.com/a/390854/8946. – Lawrence Dol Jan 11 '13 at 00:52
4

Don't use a new String object if you know what the string is. For example:

String str = new String("foo"); // don't do this

You are thus creating an unnecessary object - once you have a String object created from the literal, and then you create another one, taking the first one as constructor argument.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
2

Contrary to your question, there is a DISADVANTAGE of using a String object compared to String literal.

When you declare a String literal, String s = "foo", the compiler will check for an existing "foo" object on the heap and assign 's' to already existing "foo".

However, if you create a String object, String s = new String("foo"), an entirely new object will be created on the heap (even if there is already an existing "foo"). Strings being immutable this is totally unnecessary.

Here is good reference: http://www.javaranch.com/journal/200409/ScjpTipLine-StringsLiterally.html

Mihir Mathuria
  • 6,479
  • 1
  • 22
  • 15
2
String a = "ABC";
String b = new String("ABC");
String c = "ABC";

a == b // false
a == c // true

a.equals(b) // true
a.equals(c) // true

The point is that a & c point to the same "ABC" object (JVM magic). Using "new String" creates a new object each time. IMO, using string object is a disadvantage, not an advantage. However, as another poster said, string object is useful for converting byte[], char[], StringBuffer - if you need to do that.

xagyg
  • 9,562
  • 2
  • 32
  • 29
2

String literals are converted to String objects, and as others pointed out, creating explicit String objects is unnecessary and inperformant, as it defeats String pooling.

However, there is one situation where you want to create new Strings explicitly: If you use just a small part of a very long String. String.substring() prevents the original String from getting GC'd, so you can save memory when you write

String s = new String(veryLongString.substring(1,3));

instead of

String s = veryLongString.substring(1,3);
Landei
  • 54,104
  • 13
  • 100
  • 195
0

literal strings are objects created in a String Pool and if they have the same value, they are referencing to the same object.

System.out.println("abc"=="abc"); // the output is true

Meanwhile, string object are real objects in memory and if they have the same value, there's no guarantee that they are referencing to the same object.

String a = new String("abc");
String b = new String("abc");
System.out.println(a==b); // the output is false
Truong Ha
  • 10,468
  • 11
  • 40
  • 45