2

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?

rafaelc
  • 57,686
  • 15
  • 58
  • 82
Abhilash
  • 803
  • 1
  • 9
  • 32
  • Possible duplicate of [Why is String immutable in Java?](http://stackoverflow.com/questions/22397861/why-is-string-immutable-in-java) – rafaelc Sep 12 '16 at 17:59
  • 1
    Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – RamenChef Sep 13 '16 at 00:21

3 Answers3

2
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.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
-1

It will return a string object . The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation. Reference

lakshman sai
  • 481
  • 6
  • 14
-2
String str=new String("very");    

here str in the reference for the string object with value "very". and new String("very") is the referenced object created in java. while "very" is the value which will be replaced by "Good" without creating any new object but in the same memory unit.