String a = "test";
String b = "whatever";
String c= "test";
System.out.println(a == c); //true
I assume that this prints true because strings are immutable and therefore these strings are identical, so Java will point c
to a
's location in memory.
String a = "test";
String b = "whatever";
String c= new String("test");
System.out.println(a == c); //false
I assume that by invoking the new
operator, Java must allocate new memory, so it can't choose to point to a
.
My question is:
String d="a";
d="rbf";
d="ergfbrhfb";
d="erhfb3ewdbr";
d="rgfb";
//...
- What's going on with respect to the memory allocation of the intermediary assignments to
d
? - Does this answer change if subsequent assignments are of the same number of characters? (ie,
d="abc"; d="rfb";
) - Is new memory being allocated for each change to
d
? - If so, when does the memory allocated for each assignment become free again?