2
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 i = 0; i<3; i++)
{
    if(rgb[i].equals("0"))
    {
        rgb[i] = "00";
    }
}

In the above code I evaluate each index based on weather or not each is = to zero. yet it always runs false in the foreach loop and true when appropriate in the for loop. can someone explain what is happening behind the scenes to make this happen?

i am not running them sequentially they are both there for demo purposes.

Shar1er80
  • 9,001
  • 2
  • 20
  • 29
gnarlyninja
  • 177
  • 1
  • 10
  • It doesn't 'run false' in the foreach loop - when you ask questions, make sure you check the assertions you're making, often doing that will let you answer the question yourself. – pvg Jul 13 '15 at 23:39
  • @Shahzeb color is a variable that holds the type java.awt.Color – gnarlyninja Jul 13 '15 at 23:58
  • @pvg right, its always good to take a step back and question your assumptions, thanks for the reminder! – gnarlyninja Jul 14 '15 at 00:24

1 Answers1

8

In your for-each loop, the String el is not actually a reference to the array rgb. It just holds the value of a given index in the array. Therefore, in this case, you have to use a normal for loop to modify the contents of the array; otherwise the contents of el are just overwritten each iteration of the loop.

A visual explanation:

String[] i = new String[]{"Hi", "Hello"};     <------- Contains two indexes.
for(String str : i){
    str = str + "!";
}

First iteration:

  • str is set to i[0], which has a value of "Hi"
  • str is set to str + "!", changing str to "Hi!"
  • end of braces; str is discarded

Second iteration:

  • str is set to i[1], which has a value of "Hello"
  • str is set to str + "!", changing str to "Hello!"
  • for loop ends; str is discarded

In no case are the values of i ever changed, because the values of str are separate references to Strings.

See this SO post about the concept of immutability(Wikipedia).

Community
  • 1
  • 1
jfdoming
  • 975
  • 10
  • 25