Issue
Why two different String
variables point to the same object if they are initialized by the same value, but they point to different object if the string is passed through an Intent
?
For example:
public class MainActivity extends Activity {
public static String textA;
protected void onCreate(Bundle savedInstanceState) {
MainActivity.textA = "abc";
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
intent.putExtra("extra", MainActivity.textA);
startActivity(intent);
}
}
public class MainActivity2 extends Activity {
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String textB = intent.getStringExtra("extra");
System.out.println(textB == MainActivity.textA);
String textC = "abc";
System.out.println(textC == MainActivity.textA);
}
}
The output is
false
true
My question is why textC
and MainActivity.textA
point to the same "abc"
but textB
points to a separate "abc"
?
Solution
I ran into this answer and learned a bit.
It seems like the JVM handles String
allocations differently.
Since it's probably the most widely allocated object, it requires immense optimization.
So the JVM tries to prevent String
allocations as much as it can.
In your code, you explicitly assign "abc"
to textA
and textC
. In this case, the JVM is smart enough to "know" it can use the same reference for both variables.
Unlike textA
and textC
, textB
gets assigned dynamically and the JVM does not have a guarantee that it can use the same "abc"
reference so it cannot apply the same optimization (even you cannot know it - someone can start MainActivity2
and pass different extra
value in the intent extras).
Answered By - Shlomi Katriel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.