6

Is there a difference between these two methods?

public String toString() {
    return this.from.toString() + this.to.toString();
}

public String toString() {
    return new String(this.from.toString() + this.to.toString());
}

(assuming, of course, that the from.toString() and to.toString() methods are returning Strings).

Basically I'm confused about String handling in Java, because sometimes strings are treated like a primitive type even though they are class instances.

jackthehipster
  • 978
  • 8
  • 26
  • i think both return String objects bcz "String" is an object in Java, 2ndly u r unnecessary using a wrapper object"new String()" that's all ... Both Return immutable "String" Objects – internals-in Dec 08 '13 at 09:26
  • 1
    possible duplicate of [Difference between string object and string literal](http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal) – MarsAtomic Dec 08 '13 at 09:29
  • Jack, in the future, please conduct both Google and Stack Overflow searches before asking questions. Often, you will find that questions have already been answered in great detail. Your question has been answered multiple times on SO. – MarsAtomic Dec 08 '13 at 09:35
  • 1
    See also [What is the purpose of the expression “new String(…)” in Java?](http://stackoverflow.com/questions/390703/what-is-the-purpose-of-the-expression-new-string-in-java). – Jeppe Stig Nielsen Dec 08 '13 at 09:38
  • @mars Of course, I didn't intend to ask a duplicate question, I just couldn't think of what I need to search for... I looked for "implicit object creation" and found nothing. Now that you've said "literal string", I see my error :) Although my question isn't quite about literal strings but string expressions... but that has probably been asked and answered somewhere as well. – jackthehipster Dec 08 '13 at 09:42
  • possible duplicate of [What is the difference between "text" and new String("text") in Java?](http://stackoverflow.com/questions/3052442/what-is-the-difference-between-text-and-new-stringtext-in-java) – Alvin Wong Dec 08 '13 at 09:44
  • These suggestions for duplicate are wrong. – Maroun Dec 08 '13 at 09:52
  • @jeppe thanks for this interesting link. So the question wasn't *that* stupid after all :) – jackthehipster Dec 08 '13 at 09:53
  • @mars: I changed the title of my question to better match the *actual* question, because it wasn't really about literals as the original title suggested... hope this will not be a confusion to anyone. – jackthehipster Dec 08 '13 at 09:55
  • Thanks for all the answers! – jackthehipster Dec 08 '13 at 09:59

4 Answers4

5

There is no difference in real.

as both of your function has return type String, creating a new String() is just a overhead. it like wrapping a string to again to a string and create a new string in pool which in real has no advantage.

But one major difference in primitive type and String object is that class String always create new string.

String str = "my string";

if "my string" already exists in String pool. then it will use the same string instead of creating new.

This is the reason why when,

String str1= "my string";
String str2 ="my string";

str1==str2? --> will return true

The result of above will be true, because same String object from pool is used.

but when you do,

String str = new String("new string");

Always, a new String object is created, irrespective of a same one already exists in pool or not.

so comparing:

String str1 = new String("new string");
String str2 = new String("new string");

str1==str2 --> will return false
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • 1
    `new String(String)` doesn't *wrap* the original String. It creates a brand new (useless) *copy* of the original String. – JB Nizet Dec 08 '13 at 09:38
  • I *assume* (but don't know) that internally Java will create some sort of object for the first method as well, wouldn't it? So that basically the same happens in both instances, only in the first case it happens implicitly and in the second explicitly? EDIT: no, of course the second time the JVM would need to create the implicit object as well and then create two objects in total... ok, got it. – jackthehipster Dec 08 '13 at 09:44
  • 1
    No. `this.from.toString() + this.to.toString()` is already a String object, containing an array of (let's say) 2000 chars. `new String(this.from.toString() + this.to.toString())` creates another String object, containing another array of 2000 chars which is a copy of the array of 2000 chars contained in the String `this.from.toString() + this.to.toString()`. There is no point in making this additional copy: it uses more memory, it forces the GC to work more, it takes CPU time to make the copy, and the returned String has the same value anyway. – JB Nizet Dec 08 '13 at 09:50
3

There is a difference, if at some point you previously defined a String "ABC". Java interns strings, so when you don't explicitly state that you want a new object, it will return an object that has the same value. So for example.

String abc = "abc";

// Some code.

return new String("abc"); // This will be a new object.

Whereas if you do this:

String abc = "abc";

// Some code.

return "abc"; // This will be the above object.

This is because it's pointless for the JVM to waste memory with objects of the same value, so it stores them in memory and waits for you to need / use them again!

Which one do you go for?

More often than not the String interning process won't hamper you too much, so you're usually okay going for the former.

christopher
  • 26,815
  • 5
  • 55
  • 89
  • 1
    No, it's not. Using new String(String) is useless, since String is immutable. The state of a String NEVER changes. Moreover, interning has nothing to do with the OP's question. – JB Nizet Dec 08 '13 at 09:34
  • I read the beginning, which was correct, but I failed to see the extra jazz about String states, which, when I read it a second time was "Wha? What's he on about?" The edited answer is correct. While the OP is not directly asking about interning, he asked about differences, and interning is the major portion. – MarsAtomic Dec 08 '13 at 09:37
  • Mostly agreed, but this made me wonder: "More often than not the String interning process won't hamper you too much". Can you give a practical example of when String interning *does* "hamper you too much"? – Jonik Dec 08 '13 at 09:46
  • I took a "never say never" approach to the question. – christopher Dec 09 '13 at 10:04
2

The second one has an extra overhead.. In the second method you are initializing the string one more time that the first one ... something like

String s = "something";

return s; 

vs

return new(s);

apart from that both will do the exact same task.

stinepike
  • 54,068
  • 14
  • 92
  • 112
1

return new String(this.from.toString() + this.to.toString());

Above statement will create 2 objects.

1st object is referring to concatenated value of this.from.toString() + this.to.toString(). This doesn't have reference. 2nd object is created because of new operator.

return this.from.toString() + this.to.toString();

This will create 1 object on heap memory area.

Vikas V
  • 3,176
  • 2
  • 37
  • 60