Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between return (string expr) and return New String(string expr)?

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.

like image 241
jackthehipster Avatar asked Dec 08 '13 09:12

jackthehipster


3 Answers

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
like image 55
Zaheer Ahmed Avatar answered Nov 11 '22 23:11

Zaheer Ahmed


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.

like image 30
christopher Avatar answered Nov 11 '22 22:11

christopher


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.

like image 2
stinepike Avatar answered Nov 11 '22 22:11

stinepike