I'd like to know, in detail, how the Enhanced For Loop works in Java (assuming i do get how the basic usage of this loop is and how it works in general).
Given the following code:
String[] a = {"dog", "cat", "turtle"};
for (String s : a) {
out.println("String: " + s);
s = in.readLine("New String? ");
}
It doesn't actually modify the original list 'a'. Why not? How memory Management works? Isn't 's' a reference to the same memory cell of 'a[i]'?
I read on the oracle documentation that enhanced for loops can't be used to remove elements from the original array, it makes sense. Is it the same for modifying values?
Thanks in advance
And so to get the effect you want you need to replace the element with a new object, which isn't possible using an enhanced for loop. Strings are constant; their values cannot be changed after they are created.
Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values.
Using the for each loop − Since JDK 1.5, Java introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
Isn't 's' a reference to the same memory cell of 'a[i]'?
Originally, yes. But then in.readLine
produces a reference to a new String object, which you then use to overwrite s
. But only s
is overwritten, not the underlying string, nor the reference in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With