- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add items to an array in java dynamically?
Since the size of an array is fixed you cannot add elements to it dynamically. But, if you still want to do it then,
- Convert the array to ArrayList object.
- Add the required element to the array list.
- Convert the Array list to array.
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]
- Related Articles
- How to Add Commas Between a List of Items Dynamically in JavaScript?
- How to add items/elements to an existing jagged array in C#?
- How to declare Java array with array size dynamically?
- How to add a button dynamically in android?
- How do I add an element to an array list in Java?
- How to add elements to the midpoint of an array in Java?
- How to dynamically create radio buttons using an array in JavaScript?
- How to add items in a JComboBox on runtime in Java
- How to add table rows Dynamically in Android Layout?
- How to Dynamically Add Views into View in Android?
- How to dynamically remove items from ListView on a click?
- How to add HTML elements dynamically using JavaScript?
- Add property to common items in array and array of objects - JavaScript?
- How to add a TextView to a LinearLayout dynamically in Android?
- How to get items from an object array in MongoDB?

Advertisements