For – Know the difference

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?
[crayon lang=”java” mark=”10,16″ title=”Main.java”]
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); } }} [/crayon] 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: [crayon] a b c over over over [/crayon] I never perceived this. In other "words" you could read this as: [crayon lang="java"] for (int i = 0; i < blablubb.length; i++) { String s = blablubb[i]; s = "over"; } [/crayon] Hopefully you've known this and didn't run into confusion by assuming another behaviour.

If you have found a spelling error, please, notify us by selecting that text and pressing Ctrl+Enter.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Spelling error report

The following text will be sent to our editors: