
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
What are Variable Length Dynamic Arrays in Java
In Java, Arrays are of fixed size. The size of the array will be decided at the time of creation. But if you still want to create Arrays of variable length you can do that using collections like array list.
Example
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class AddingItemsDynamically { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array :: "); int size = sc.nextInt(); String myArray[] = new String[size]; System.out.println("Enter elements of the array (Strings) :: "); for(int i=0; i<size; i++) { myArray[i] = sc.next(); } System.out.println(Arrays.toString(myArray)); ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray)); System.out.println("Enter the element that is to be added:"); String element = sc.next(); myList.add(element); myArray = myList.toArray(myArray); System.out.println(Arrays.toString(myArray)); } }
Output
Enter the size of the array :: 3 Enter elements of the array (Strings) :: Ram Rahim Robert [Ram, Rahim, Robert] Enter the element that is to be added: Mahavir [Ram, Rahim, Robert, Mahavir]
Advertisements