Why JAVA foreach doesn't change element value? -
how come following prints boss , 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 not print out bass?it prints boss.
you're changing iteration variable c
. doesn't change contents of array. iteration variable copy of array element. if want modify array, need explicitly:
for (int = 0; < array.length; i++) { if (array[i] == 'o') { array[i] = 'a'; } }
your original code equivalent (as per section 14.14.2 of jls) to:
for (int = 0; < array.length; i++) { char c = array[i]; if (c == 'o') { c = 'a'; } }
changing value of local variable never change else - just changes local variable. assignment:
char c = array[i];
copies value in array local variable. doesn't associate local variable array element perpetually.
Comments
Post a Comment