I did search on this but the keywords must be too generic to narrow down the relevant bits. Why are both ways of declaring a string valid in android and is there any difference?
-
1They are the same. I would recommend checking out this: docs.oracle.com/javase/tutorial/java/javaOO/… are basically instantiating a new instance of the String object.Robert– Robert2012-01-04 15:54:54 +00:00Commented Jan 4, 2012 at 15:54
-
1Strings are immutable, so I suspect that there is no difference. You could examine the bytecode generated by each to see if there is any difference.Mitch– Mitch2012-01-04 15:55:11 +00:00Commented Jan 4, 2012 at 15:55
-
Probably should be closed as copy of String vs new String()Sulthan– Sulthan2012-01-04 16:05:26 +00:00Commented Jan 4, 2012 at 16:05
-
Thanks for the links, and apologies for duplicating the question. I spent a good 10 minutes trying to find a similar Q before posting but there were way too many results to scroll through and many were c++ and ios related. This is what I wanted: "You very rarely would ever want to use the new String(anotherString) constructor. From the API..."wufoo– wufoo2012-01-04 16:12:26 +00:00Commented Jan 4, 2012 at 16:12
4 Answers
Using the new keyword you create a new string object, where using foo = "bar" will be optimized, to point to the same string object which is used in a different place in your app.
For instacne:
String foo = "bar";
String foo2 = "bar";
the compiler will optimize the above code to be the same exact object [foo == foo2, in conradiction to foo.equals(foo2)].
EDIT: after some search, @Sulthan was right. It is not compiler depended issue, it is in the specs:
A string literal always refers to the same instance (§4.3.1) of class String.
4 Comments
String.intern(). All literal strings and string-valued constant expressions are internedThis is java syntax and not only specific to Android. Here is a discussion on this. String vs new String()
Comments
This is not only about Android, it's about Java.
When you write "xxxx" it is a literal string. It's a String instance. Note, that all literal strings with the same value are the same instance. See method String.intern() for details.
Example:
String s1 = "abc";
String s2 = "abc";
in this example, s1 == s2 is true.
new String("xxx") is a copy constructor. You take one string (the literal) and you create a new instance from it. Since all strings are immutable, this is usually something you don't want to do.
Example:
String s1 = "abc";
String s2 = new String("abc");
s1.equals(s2) is true
s1 == s2 is false