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

class, java, object, string, types

Solution

`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

Problem

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.

Original source

Related problems