Abhilash28Abhi Abhilash28Abhi - 1 month ago 5x
Java Question

String object created or not by java code

For the following code :

String object will be created in heap area (not inside String pooled area):

String str = new String("very");

Now if I modify str to refer "good" like:

str = "good";

Will it modify the object "very" created in heap and change its value to "good" or will it create a new object of "good" in pool?

String str = new String("very");

str is a reference. Meaning it "points" to a string object.

When you do

str = "good"

you just make str point to a different object. You are not trying to change the contents of the object to which str points to.

If you did something like str.Method() this would be an attempt to do something on the object to which str points, but as string is immutable still you would get a new string object out of that.

But by simply doing

str = ...

You make reference point elsewhere, this would be common with all reference types.