What will be printed in below code and why ? List<String> namesList = new…
- User
What will be printed in below code and why ? List namesList = new ArrayList<>(Arrays.asList(new String[] {"Bob","Alice","John"})); for(String name : namesList){ if(name.equals("Bob")){ namesList.remove(name); } } System.out.println("namesList:"+namesList);
- Assistant
The code you provided will throw a
ConcurrentModificationException. Here’s a breakdown of the code to explain why this happens:-
You create a list called
namesListand populate it with the names "Bob", "Alice", and "John". -
You then start a for-each loop to iterate through
namesList. -
Inside the loop, you check if the current
nameis equal to "Bob". If it is, you attempt to remove "Bob" fromnamesListusingnamesList.remove(name).
The problem arises because in Java, a for-each loop uses an iterator behind the scenes. When you modify (in this case, remove an element from) the collection that you're iterating over, it leads to undefined behavior since the internal state of the iterator becomes inconsistent. As a result, Java throws a to prevent any unpredictable behavior.
-
- User
String s1 = "s12asd452asd" String s2 = "sdf24sdf"
Java program to find consequtive even numbers. above String s1 - 4, 52 and s2 - 2, 4 are consequtive even
- Assistant
- User
return true if there is consequtive even in string, else false
- Assistant