![]() You are calling that local variable s in your more recent examples. That point is not clearly made in the Java Tutorials. that means you can re-assign to the local variable (unless it is marked final), but that re-assignment is not reflected in the original array. If you look in the Java Language Specification, you find that the value in the array is copied into a local variable, and that local variable is used in the loop. Ove Lindström has already given you an answer for the second question. 2: Why am I not getting all my Strings catenated together?.1: Why can't I change the array elements in a for-each loop?.Why then changes made through it are not reflected. It worked as expected.ĭog dogArr = //prints original values i.e one two and three Has it got anything to do with String immutability or is it the expected behavior. I pasted the snippet where i tried with strings but result was similar to that in case of an array of primitives. It's discomforting to have such huge conceptual flaws in head. Since Strings are objects, shouldn't the first loop have changed the contents.Ĭan someone please clear this. Is it because it is an array of primitives and "copy of" value from the array is in "s". But still, somehow I am not able to give myself a solid explanation. I mean i know "s" here is a block scoped variable. So is it that we cannot modify anything using these advanced loops. A normal for loop would have required me to use "arr+=1" and yes, that would obviously have changed the contents. Consider the code.Īfter this the contents of the array did not change. I have yet again been humbled by how little I know. I have been using foreach loops for quite some time now. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
March 2023
Categories |