wufoo
wufoo

Reputation: 14621

String foo = "bar" vs. String foo = new String ("bar") in Android?

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?

Upvotes: 3

Views: 3985

Answers (4)

Steffen Heil
Steffen Heil

Reputation: 4356

String x = new String( "x" )

effectively creates 2 Strings. One for the literal (which is a expression with no variable name) and one that you keep as x then. It is the same as:

String x;
{
  String a = "x";
  x = new String( a );
}

Upvotes: 0

amit
amit

Reputation: 178521

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.

Upvotes: 4

Sulthan
Sulthan

Reputation: 130200

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

Upvotes: 0

kosa
kosa

Reputation: 66677

This is java syntax and not only specific to Android. Here is a discussion on this. String vs new String()

Upvotes: 3

Related Questions