I would like to write some words about the difference of the for loop behaviour. At first you should read the code and notice 2 different for usages. Both should do the same. Do they?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class Main { /** * @param args */ public static void main(String[] args) { String[] blablubb = { "a", "b", "c" }; // 1) for(String s : blablubb) { s = "over"; } printArray(blablubb); // 2) for (int i = 0; i < blablubb.length; i++) { blablubb[i] = "over"; } printArray(blablubb); } public static void printArray(String[] arr) { for( String s : arr ) { System.out.println(s); } } } |
I assumed the first loop would also overwrite the string in the array – as the second one does. But it does not! – It copies the reference value to a locale variable. So guess what the output actually is:
1 2 3 4 5 6 | a b c over over over |
I never perceived this. In other “words” you could read this as:
1 2 3 4 | for (int i = 0; i < blablubb.length; i++) { String s = blablubb[i]; s = "over"; } |
Hopefully you’ve known this and didn’t run into confusion by assuming another behaviour.