New for loop not same as old !!!

public class Test {

public static void main(String[] args) {

String[] strArray = new String[2];

for (int i = 0; i < strArray.length; i++)

{

strArray = "111";

}

for (String str : strArray)

{

System.out.println(str);

}

}

}

This program gives following output

111

111

But with new for loop

public static void main(String[] args) {

String[] strArray = new String[2];

for (String str : strArray)

{

str = "111";

}

for (String str : strArray)

{

System.out.println(str);

}

}

It gives

null

null.

Can anybody tell me whether it is a bug in java or something that I don't understand?

[777 byte] By [chintan13a] at [2007-11-26 21:34:15]
# 1
http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html
masijade.a at 2007-7-10 3:15:35 > top of Java-index,Java Essentials,Java Programming...
# 2

it's not a bug. did you really think something that obviously broken would be released? when you're doing "for String str: strArray" the variable str is a reference to one of the strings in the array, not the string itself, hence when you assign it so another string, it's just referring to that string instead. the original object is not impacted at all

georgemca at 2007-7-10 3:15:35 > top of Java-index,Java Essentials,Java Programming...
# 3
for (String str : strArray){str = "111";}You set a temporary variable here and not the array elements.
BIJ001a at 2007-7-10 3:15:35 > top of Java-index,Java Essentials,Java Programming...
# 4
> http://java.sun.com/j2se/1.5.0/docs/guide/language/for> each.htmlit's not a misunderstanding of foreach loops, it's a misunderstanding of how references work :-)
georgemca at 2007-7-10 3:15:35 > top of Java-index,Java Essentials,Java Programming...
# 5

> >

> http://java.sun.com/j2se/1.5.0/docs/guide/language/for

>

> > each.html

>

> it's not a misunderstanding of foreach loops, it's a

> misunderstanding of how references work :-)

I see that now that I read closer. After the code got broken (the infamous i counter to italics) I didn't really bother to look to closely. ;-)

Edit: But then again, it still applies when you consider the following quote from that link:

Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it.

;-)

masijade.a at 2007-7-10 3:15:35 > top of Java-index,Java Essentials,Java Programming...