In: Computer Science
Assume you call the method below with an array list that contains (2,3,4,5,1)
public static void m3(ArrayList list1)
{
if (list1.size() ==1)
System.out.println(list1.get(0));
else
if (list1.size()%2==0)
System.out.println(list1.remove(0));
else
System.out.println(list1.remove(list1.size()-1));
}
What will be the output?
Assume you call the method below with an array list that contains (2,3,4,5,1)
public static void m3(ArrayList list1)
{
if (list1.size() ==1)
System.out.println(list1.get(0));
else
if (list1.size()%2==0)
System.out.println(list1.remove(0));
else
System.out.println(list1.remove(list1.size()-1));
}
What will be the output?
Answer- 1 will be printed.
Explanation
(i) in this program we have a method m3 that take ArrayList as a argument .
(ii) in the first if statement we check the size of our ArrayList that
is 5 initially so if size will be equals to 1 then condition is true but now our case condition is false.
If(5==1)
So condition is false.
(iii) now condition is false so else block will be executed , and in the else block have a another if statement and we checked a condition that is if size of list is modulo by 2 is equals to 0 then our condition will be true but here out condition it is failed. because modulus is 1.
If(5%2==0)-> it becomes
If(1==0) so condition is false
(iv) so now else block will be executed- in this else block we have a print statement and inside print statement we called remove method through object list1. and inside remove method we called list1.size() method that return size of list.so size of list is 5 and now we minus the size of list by 1
so (5-1=4).
list.(remove(4));
remove method remove the value of 4th index so in our case the value of 4th index is 1 so 1 will be our output.
Note:
Remove method is used to remove the element present at the specified position in the list.