I figured out a a problem in my Code. First the code:
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
When you want to do a low level optimization, know how, you have to look inside Java code and inside byte-code either(compiled code)
for(String s : blablubb) {
s = "over";
}
is equals with:
for (int i = 0; i < blablubb.length; i++) {
String s = blablubb[i];
s = "over";
}
and that's why the output as how it is.
Your for(String s : blablubb)
loop is equivalent to the following code:
for(int i = 0; i < blablubb.length; i++ ) {
String s = blablubb[i];
s = "over";
}
Hopefully, from this you can see that all you are doing is reassigning a different value to s
without changing blablubb[i]
. This explains the output you see.
for(String s : StringArray)
{
}
is like
for(int i = 0; i < StringArray.length; i++)
{
String s = StringArray[i];
}
s = "over";
just changes the reference of s and not the String in the array.
blablubb[i] = "over";
changes the value stored at ith location in the array
The for-each loop don't modify the objects contained in the Collection of objects it's iterating over. It's passing the value not the reference.
This:
for (String s : blablubb) {
s = "over";
}
Is equal to this:
for (int i = 0; i < blablubb.length; i++) {
String s = blablubb[i];
s = "over";
}
This creates a temporary String with a copy of the value from array and you change only the copy. That's why blablubb[]
content stays untouched.
If you want to change values in the array, just use your second option:
for (int i = 0; i < blablubb.length; i++) {
blablubb[i] = "over";
}
And, by the way, you can print an array with just one line:
System.out.println(Arrays.toString(blablubb));