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


Please Help Members By Posting Answers For Below Questions

What is concurrent hashmap and its features?

513


Define an enumeration?

607


What is the importance of static variable?

580


How many types of design patterns are there?

524


What is the difference between @before and @beforeclass annotation?

526






Can size_t be negative?

604


what do you mean by classloader in java?

564


Hi all, I am dng a mini project on FileSplitter application which splits the GBs of logfile into Smaller chunks(mbs) depending on the split size." How to handle GBs file? I am getting OutOfMemoryException, when I input such GB sized file. Thx

1596


Is singleton a bad practice?

569


Tell us something about set interface.

553


what is the constructor and how many types of constructors are used in java?

531


Which method returns the length of a string?

561


What is ++ a in java?

561


How do you create a bulleted list?

555


What is string :: npos?

571