Java for loop by value or by reference -
i figured out a problem in code. first code:
public class main { /** * @param args */ public static void main(string[] args) { string[] blablubb = { "a", "b", "c" }; for(string s : blablubb) { s = "over"; } printarray(blablubb); (int = 0; < blablubb.length; i++) { blablubb[i] = "over"; } printarray(blablubb); } public static void printarray(string[] arr) { for( string s : arr ) { system.out.println(s); } } }
the output is:
a b c on over on
i assumed first loop overwrite string in array. output on in case. seems creates copy of value instead creating reference. never perceived this. doing wrong? there option create reference instead?
//edit: seems knows except me. i'm c background , doesn't pay enough attention term reference different c. happily took me 10 minutes figure out (this time).
this:
for (string s : blablubb) { s = "over"; }
is equal this:
for (int = 0; < blablubb.length; i++) { string s = blablubb[i]; s = "over"; }
this creates temporary string copy of value array , change copy. that's why blablubb[]
content stays untouched.
if want change values in array, use second option:
for (int = 0; < blablubb.length; i++) { blablubb[i] = "over"; }
and, way, can print array 1 line:
system.out.println(arrays.tostring(blablubb));
Comments
Post a Comment