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.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With