class A {
public void someMethod() {
String var = "Abhi";
var = "Abhishek";
}
}
Will the var variable store Abhi and Abhishek in different memory location or Abhishek overwrites Abhi ??
If i use this expression String var= new String();, then what?
Given this method:
In this example there are 3 relevant things:
var. This variable is stored on the stack (because it’s a local variable) and can hold the reference to some object.Stringobject with the contentAbhi: it’s the first thing thatvarreferences right after its declaration.Stringobject with the contentAbhishek:varis modified to reference this object in the second line wherevaris mentioned.So in respect to memory: the two
Stringobjects are stored in distinct spaces, unrelated to each other.varhowever, only ever occupies the same place (during a single invocation offoo, that is). So the reference toAbhiis overwritten with a reference toAbhishek.If you add the line
var= new String();at the end of that method, then that line would do two things:Stringobject representing the emptyStringandStringobject to the variablevar.Note that there is almost never a reason to use that
Stringconstructor, because""has (almost) the exact same effect.