I wrote a code for string reversing using Stack and StringBuilder classes. And I have noticed that 'foreach' loop in this code generates java.util.ConcurrentModificationException, but usual 'for' loop instead does not. So why?
public static String reverse(String str)
{
    Stack<Character> stack = new Stack<>();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++)
        stack.push(str.toCharArray()[i]);
    }
    for (Character c: stack) // generates an exception
    {
        sb.append(stack.pop());
    }
    return sb.toString();
}
I expected a reversed string, but ConcurrentModificationException has occured.
 
     
     
     
    