Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enhanced For Loop - Editing Original Array Values

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

like image 843
jnardiello Avatar asked Jan 03 '13 10:01

jnardiello


People also ask

Can enhanced for loops change values?

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.

Can you use enhanced for loop on array?

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.

Does enhanced for loops traverse the complete array sequentially?

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.


1 Answers

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.

like image 185
Oliver Charlesworth Avatar answered Sep 18 '22 20:09

Oliver Charlesworth