Reputation: 699
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
Upvotes: 5
Views: 3904
Reputation: 43738
s
is a local variable that points to the String
instance. It is not associated with a[i]
, they just happen to have the same value initially.
Upvotes: 5
Reputation: 2931
For every iteration String s initially references to corresponding String object in String a[]. But it is then referenced to another String object that is returned by in.readLine().
Upvotes: 1
Reputation: 4228
Think in s
like an address to an object. The thing here is that s
is pointing out to a certain value of the array when using the for loop. When you reassing s
inside the loop is just happen that s
points out to another value but the original value of the array is not modified as you are only changing the address s
is pointing to.
String[] a = {"dog", "cat", "turtle"};
for (String s : a) {
//s --> "dog"
out.println("String: " + s);
s = in.readLine("New String? ");
//s --> the new string the user inputs
}
Upvotes: 1
Reputation: 272537
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.
Upvotes: 11
Reputation: 533530
You can only write
for (int i = 0; i < a.length; i++) {
out.println("String: " + a[i]);
a[i] = in.readLine("New String? ");
}
You can't use for-each loops to modify the original collection or array.
Upvotes: 3