
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extend the Size of an Array in Java
An array has a fixed number of values and its size is defined when it is created. Therefore, the size of the array cannot be changed later. To solve this problem, an ArrayList should be used as it implements a resizable array using the List interface.
A program that demonstrates ArrayList in Java is given as follows −
Example
import java.util.*; public class Demo { public static void main(String args[]) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Apple"); aList.add("Melon"); aList.add("Orange"); aList.add("Mango"); aList.add("Grapes"); System.out.println("ArrayList elements are:"); for(String i:aList) { System.out.println(i); } } }
Output
ArrayList elements are: Apple Melon Orange Mango Grapes
Now let us understand the above program.
First the ArrayList is created. Then elements are added to it using add(). Finally, the ArrayList elements are displayed using for loop. A code snippet which demonstrates this is as follows −
ArrayList<String> aList = new ArrayList<String>(); aList.add("Apple"); aList.add("Melon"); aList.add("Orange"); aList.add("Mango"); aList.add("Grapes"); System.out.println("ArrayList elements are:"); for(String i:aList) { System.out.println(i); }
Advertisements