How come the following prints boss and not bass?
String boss = "boss";
char[] array = boss.toCharArray();
for(char c : array)
{
if (c== 'o')
c = 'a';
}
System.out.println(new String(array)); //How come this does NOT print out bass?It prints boss.
This is because
c = 'a'
is assigninga
to the local variablec
which is not referencing the actual value present at that index of thearray
itself. It is just containing a copy of the value present at the specified index ofarray
. So the change is actually made in the local variable not in the actual location wherearray[i]
is referencing.. If you want to change value you should use the following indeed:You're assigning 'a' to the local variable c, but not to the array element. To make it print bass, you'd need
Changes applied in 'for each' loop are made just inside her body (that's because values are copied, not referentions). To work on referentions use 'for' loop.
In my perspective the author actually asks for a reasons of so build function. I can't find any good reason of such move. Is it becouse for-each loop is meant to be an universal or in least editting directly so obtained variable would need some special treatment in various methods?
This loop is waged by additional fields and instructions. It seems to be good just for a simple, rapid and short-living quotes. I would use it in a perspective of a very short time to write - challanges, debugging, pressure at work.
With lambda - this makes a group of a tricky methods. But that's a legacy of high level programming and quick life unfortunately, IMO.
You variable
c
gets changed, but not the array contents. To change the array, don't usec
, manipulate the array directly.You're changing the iteration variable
c
. That doesn't change the contents of the array. The iteration variable is just a copy of the array element. If you want to modify the array, you need to do so explicitly:Your original code is equivalent (as per section 14.14.2 of the JLS) to:
Changing the value of a local variable will never change anything else - it just changes the local variable. The assignment:
copies the value in the array into a local variable. It doesn't associate the local variable with the array element perpetually.