• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String Method Chaining and Immutability

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Reference: OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide, Chapter 3


Remember that String is immutable. What do you think the result of this code is



On line 5, we set a to point to "abc" and never pointed a to anything else.Since we are dealing with an immutable object, none of the code on lines 6 or 7 changes a.
b is a little trickier. Line 6 has b pointing to "ABC", which is straightforward. On Line 7, we have method chaining. First, "ABC".replace("B", "2") is called. This returns "A2C". Next, "A2C".replace('C', '3') is called. This returns "A23". Finally, b changes to point to this returned String. When line 9 executes, b is "A23".



My question is how b, made to point to object "ABC" on line 6 is changing to point to the returned String "A23"  on line 7, when b is a String and hence immutable?

 
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
b is not a String.
b is a reference to a String, and it is that String that is immutable.
You can change what b refers to without any issue, which is what is happening on line 7.
b was referring to a String object with the contents "ABC", but changed to reference the value returned by the second replace call ("A23").
 
Krish Krishnan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the response.
My confusion was from these statements: "Since we are dealing with an immutable object, none of the code on lines 6 or 7 changes a." and "Finally, b changes to point to this returned String.". Similarly, (if a can not change as it is immutable), shouldn't b also be immutable and unchanging?
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Krish Krishnan wrote:Similarly, (if a can not change as it is immutable), shouldn't b also be immutable and unchanging?



When you ask that, are you asking about b the variable, or about the String object that the variable may have referred to at some time in that code?
 
Krish Krishnan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am not sure how to explain - my doubt is why variables a and b are behaving differently being both are immutable? a not changing but b changing!
 
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Krish Krishnan wrote:My confusion was from these statements: "Since we are dealing with an immutable object, none of the code on lines 6 or 7 changes a." ...


That line is a bit confusing.  It should probably be worded like this:

"Since we are dealing with an immutable object, none of the code on lines 6 or 7 changes the String that a points to."
 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Krish Krishnan wrote:I am not sure how to explain - my doubt is why variables a and b are behaving differently being both are immutable? a not changing but b changing!


Remember what Dave Tolls said.  a is a reference to a String.  That's the same as saying a points to a String.  The String that a points to does not change.  Neither does the String that b points to, but it points to a different String than a.
 
Paul Clapham
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dave and Knute have covered it pretty well, but just to reiterate: variables are not immutable (unless you declare them final). Objects may or may not be immutable, depending on the design of their class, and String objects are always immutable.
 
Krish Krishnan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
While it's perfectly understood that a & b are reference variables and not objects themselves, and a and b may be made to point to some objects such as "abc" etc. including null. Here the code snippet has some object methods such as a.toUppercase(),  b.replace("B", "2") and replace('C', '3') - the last 2 are chained, that return the results "ABC", "A2C", and "A23" respectively. As I understand, these 3 returned String objects don't change or replace the original Strings (maintaining their immutable status) and generating 3 new objects in the String pool. Along with returning the new results (and generating the new objects), the results' references are saved in the variable b (but not in a), as obvious in the code b=a.toUppercase() etc. Hence the explanation that b is changing and a not changing.
I hope my understanding is correct?
 
Paul Clapham
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Krish Krishnan wrote:Hence the explanation that b is changing and a not changing. I hope my understanding is correct?



It seems to be correct. But still, talking about variable names as a substitute for talking about objects (which those variables might sometimes refer to) can lead to confusion. It's better to not do that.
 
Rancher
Posts: 144
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, it would be helpful if all those trolling around "Are you mean the String object or the reference?" would just stop that crap - that isn't helpful at all in any way - and already caused more confusion to OP ...

Back to topic:

@Krish Krishnan
To explain what happens here I have you have to understand how methods (oh, yea, side-note: to all called it "variable" - it's called reference - end of story - same like it's called method instead of function - jeez o.0) without side-effects work.
On the 2nd line you have "a" - wich points to the String "abc" - and call the method "toUppercase()" on it. This method, instead of modifying the String a references (as they're immutable), it returns a new String with the new modified content. To even have any effect you have to store this new String anywhere. If line 2 would only look like a.toUppercase() actually nothin really would happen as the new String is just thrown away (so it's likely to get optimized out).
Back to the basics: To even call a method you either need a class (when it's a static method) or an object (when it's an instances method). So, why does method chaining work? By the previous method returning some object the next method can be called on. So, let's unroll the chain:

So, I guess you understand what happens here: You first have the original b, reference to "ABC", then you first call the first replce on it wich returns a new String now contain "A2C" - wich you store back into b so you override it. Next, you take that new overridden String "A2C" and call the second replace on it resulting finally in "A23" wich then gets stored back in b overriding the intermediate "A2C" with the final "A23".
What makes method chaining different? Nothin at all! It exactly the same - just in a compressed way. Instead of storing each intermediate step seperately you "chain them together" - hence its name "method chaining".

Another example:
"C".concat("o").concat("d").concat("e").concat("r").concat("a").concat("n").concat("c").concat("h") is the very same as "C"+"o"+"d"+"e"+"r"+"a"+"n"+"c"+"h" - it's a chained concatenation of String to form the final result "Coderanch" - but instead of rely upon the special meaning of the "+" operator the concatenate Strings you use the concat() method. The above example could also be written as:

Or like this:

If you may familiar with the term "loop unrolling" - it's kinda like it's opposite: You shrink down multiple lines of code into one.
 
Dave Tolls
Rancher
Posts: 4801
50
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Kristina Hansen wrote:Well, it would be helpful if all those trolling around "Are you mean the String object or the reference?" would just stop that crap - that isn't helpful at all in any way - and already caused more confusion to OP ...



Well, considering Krish seeems to have grasped the point with their last post, I think we did a reasonable job explaining things to them.
 
Marshal
Posts: 79178
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dave T is right. Remember, it does nobody any good to go on about “trolling” and “crap”.
 
Rancher
Posts: 285
14
Eclipse IDE C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i think his confusion is because of this line here:


this command says to make the value of "a" uppercase, and then assign it to "b".
but afterwards when you print the value of "a" it's still in lowercase, even though we said for "a" to be made upper.

and i'm pretty sure the reason for this behavior is because java is pass by value???
so immutability of strings isn't what protects the value of "a" from changing.
 
Campbell Ritchie
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

S Fox wrote:. . . we said for "a" to be made upper.

No, it is to create an upper‑case version of the String pointed to by a. That String object itself doesn't change; you are creating a second String object.

. . . java is pass by value???

That isn't relevant because you aren't passing any information to a method.

so immutability of strings isn't what protects the value of "a" from changing.

No, it is that you don't say a = anythingDifferentFromFirstValue; anywhere.
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Krish Krishnan wrote:... and generating 3 new objects in the String pool.

This is a nitpick but new strings are not generated in the String pool. Only compile-time String constants are put in the String pool. Any new String objects have to be explicitly intern()-ed if you want them in the String pool, otherwise, they'll be on the heap with all other new objects created.
 
Krish Krishnan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks much for the many thoughtful responses received for my inquiry - very helpful in making the concept much more clear and learned few new things as bonus!
 
"To do good, you actually have to do something." -- Yvon Chouinard
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic