foreach – Understanding for each loop in Java-ThrowExceptions

Exception or error:

The code below doesn’t do what I expect. Every string is null after this code executes.

String[] currentState = new String[answer.length()];
for(String x : currentState)
{
    x = "_";
}

The code below does what I expect. Every string in currentState is now “_”

String[] currentState = new String[answer.length()];
for (int i = 0; i < currentState.length; i++) {
    currentState[i] = "_";
}

Can someone explain why the first case doesn’t work?

How to solve:

By design the for each variable ‘x’ (in this case) is not meant to be assigned to. I’m surprised that it even compiles fine.

String[] currentState = new String[answer.length()]; 
for (String x : currentState) { 
    x = "_"; // x is not a reference to some element of currentState 
}

The following code maybe shows what you’re in effect are doing. Note that this is not how enumerations work but it exemplifies why you can’t assign ‘x’. It’s a copy of the element at location ‘i’. (Edit: note that the element is a reference type, as such it’s a copy of that reference, assignment to that copy does not update the same memory location i.e. the element at location ‘i’)

String[] currentState = new String[answer.length()]; 
for (int i = 0; i < answer.length(); i++) { 
    String x = currentState[i];
    x = "_";
}

Answer:

Original code:

String currentState = new String[answer.length()];

for(String x : currentState) 
{ 
    x = "_"; 
}

Rewritten code:

String currentState = new String[answer.length()];

for(int i = 0; i < currentState.length; i++) 
{ 
    String x;

    x = currentState[i];
    x = "_"; 
}

How I would write the code:

String currentState = new String[answer.length()];

for(final String x : currentState) 
{ 
    x = "_";   // compiler error
}

Rewritten code with the error:

String currentState = new String[answer.length()];

for(int i = 0; i < currentState.length; i++) 
{ 
    final String x;

    x = currentState[i];
    x = "_";   // compiler error
}

Making the variables final highlights when you do things like this (it is a common beginner mistake). Try to make all of your variables final (instance, class, arguments, exceptions in catch. etc…) – only make them non-final if you really have to change them. You should find that 90%-95% of your variables are final (beginners will wind up with 20%-50% when they start doing this).

Answer:

Because x is a reference (or a variable of reference-type). All the first piece of code does is re-point the reference at a new value. For example

String y = "Jim";
String x = y;
y = "Bob";
System.out.println(x); //prints Jim
System.out.println(y); //prints Bob

The fact that you are re-assigning the reference y to “Bob” does not affect what the reference x was assigned to.

Answer:

You can convert your array to a List and then iterate like this:

String[] currentState = new String[answer.length()];
List<String> list = Arrays.asList(currentState);
for(String string : list) {
   x = "_";     
}

Answer:

Object x[]={1,”ram”,30000f,35,”account”};
for(Object i:x)
System.out.println(i);
for each is used for sequential access

Answer:

The for each loop meant for this:

List suits = ...;
List ranks = ...;
List sortedDeck = new ArrayList();
for (Suit suit : suits){
    for (Rank rank : ranks)
        sortedDeck.add(new Card(suit, rank));
}

so consider above you can do this:

String[] currentState = new String[answer.length()];
List<String> buffList = new ArrayList<>();
for (String x : currentState){
        x = "_";
        buffList.add(x);
        // buffList.add(x = "_" ); will be work too
}
currentState = buffList.toArray(currentState);

Leave a Reply

Your email address will not be published. Required fields are marked *