java - String.equals with for each and for loop -


this question has answer here:

string[] rgb = new string[3];  rgb[0] = integer.tohexstring(color.getred()); rgb[1] = integer.tohexstring(color.getgreen()); rgb[2] = integer.tohexstring(color.getblue());  for(string el : rgb) {     if(el.equals("0"))     {         el = "00";     } }  for(int = 0; i<3; i++) {     if(rgb[i].equals("0"))     {         rgb[i] = "00";     } } 

in above code evaluate each index based on weather or not each = zero. yet runs false in foreach loop , true when appropriate in loop. can explain happening behind scenes make happen?

i not running them sequentially both there demo purposes.

in for-each loop, string el not reference array rgb. holds value of given index in array. therefore, in case, have use normal for loop modify contents of array; otherwise contents of el overwritten each iteration of loop.

a visual explanation:

string[] = new string[]{"hi", "hello"};     <------- contains 2 indexes. for(string str : i){     str = str + "!"; } 

first iteration:

  • str set i[0], has value of "hi"
  • str set str + "!", changing str "hi!"
  • end of braces; str discarded

second iteration:

  • str set i[1], has value of "hello"
  • str set str + "!", changing str "hello!"
  • for loop ends; str discarded

in no case values of i ever changed, because values of str separate references strings.

see this post concept of immutability(wikipedia).


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -