Java ArrayList - 2

If you are new to java ArrayList please check my previous post on java array list Java Array List - 1

Today we will learn how to take user input and save data to an Array List , also how to print element of Array List using for loop.

Take user input :

At first run the code on your computer and see if you can find out how is it working
We imported java.util.ArrayList; and  java.util.Scanner; one for Array List and another for user input.
Then inside Main method in line - 6 we declared our Array List and after taking every user input we are adding the string to our array list in line 14.

Print Array List elements using for loop :

To print/get an element of Array List we have to use arr_List_name.get(index). Let's see the whole code :
for (int i = 0; i < arrList.size(); i++) {
    String s = arrList.get(i);
    System.out.println(s);
}
Add this for loop after line 17 of our previous code , and run the code. It will print all the elements.
If you are wondering how is it working let me explain 😛

we are iterating from index 0 to last index of the array list . to do this we used "arrList.size()" which will return the length of the array list.
Then we store the i'th element of array to our string s using "arrList.get(i)".
And then we print the string.
so at first iteration we get and print the 0'th index element then 1st index element and so on..

Print Array List elements using for each loop:

We can do the same task in another way using for each loop , which takes less code 😎
for (String s : arrList) {
     System.out.println(s);
}

Run this code and see the magic for yourself 😁 
if you are enthusiastic and want to learn more about for each loop 
check this out - Java for each loop

Comments

Popular Posts