Why does the foreach statement not change the element value?

前端 未结 6 1059

How come the following prints boss and not bass?

String boss = \"boss\";
char[] array = boss.toCharArray();

for(char c : array)
{
 if (c== \'o\')
     c =          


        
6条回答
  •  别那么骄傲
    2020-11-22 01:17

    This is because c = 'a' is assigning a to the local variable c which is not referencing the actual value present at that index of the array itself. It is just containing a copy of the value present at the specified index of array. So the change is actually made in the local variable not in the actual location where array[i] is referencing.. If you want to change value you should use the following indeed:

    int i = 0;
    for(char c : array)
    {
     if (c== 'o')
         array[i] = 'a'; 
      i++;
    }
    

提交回复
热议问题