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".
Krish Krishnan wrote:Similarly, (if a can not change as it is immutable), shouldn't b also be immutable and unchanging?
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." ...
All things are lawful, but not all things are profitable.
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!
All things are lawful, but not all things are profitable.
Krish Krishnan wrote:Hence the explanation that b is changing and a not changing. I hope my understanding is correct?
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 ...
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.S Fox wrote:. . . we said for "a" to be made upper.
That isn't relevant because you aren't passing any information to a method.. . . java is pass by value???
No, it is that you don't say a = anythingDifferentFromFirstValue; anywhere.so immutability of strings isn't what protects the value of "a" from changing.
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 wrote:... and generating 3 new objects in the String pool.
"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
|