What will be the output of the program?
public class Test {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();
list.add("2");
list.add("3");
list.add("4");
list.add("5");
System.out.println("size :"+list.size());
for(int i=0;i<list.size();i++) {
list.remove(i);
}
System.out.println("size after:"+list.size());
}
}
Answer Posted / sreekanth madamanchi
Step 1: The array size: 4
array is list[0]=2, list[1]=3, list[2]=4, list[3]=5;
i=0;i<4;i++
it removes the 0th element, means it removes 2.
now the array is list[0]=3, list[1]=4, list[2]=5
Step 2: Now the size of the array is 3
now i=1 (bcz i++)
i<3;i++
it removes the 1st element, means it removes 4 (Bcz i=1).
now the array is list[0]=3, list[1]=5
Step 3: Now the size of the array is 2
now i=2
the condition is fail in for loop (bcz i=2. means 2<2)
So it won't go inside the loop
So the size after:2
The final Output is
size :4
Size after:2
| Is This Answer Correct ? | 13 Yes | 0 No |
Post New Answer View All Answers
What is meant by class loader? How many types are there? When will we use them?
What is difference between static and abstract class?
Define an applet in java?
What is an immutable class?
What is the difference between variable & constant?
What is __ init __ functions?
What do you mean by append?
Give us the name of the list layoutmanagers in java?
Why strings in java are called as immutable?
What is an example of a conditional statement?
Is it possible to compare various strings with the help of == operator? What are the risks involved?
Can we have this () and super () together?
What is a loop java?
Why do we override tostring method in java?
What are the types of collections in java?