- How to Add Elements to an Array in Java
- Adding elements to a Java array
- Method 1: Adding Elements to array by creating a new Java array
- Method 2: Adding Elements to an array in Java by using ArrayList
- Conclusion
- About the author
- Farah Batool
- Java adding element to array
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Java Add To Array — How to add element to an array in Java?
- 2. Java add to array by recreating new array
- 3. Java add to array by using intermediate storage — ArrayList
- 4. Java add to array using HashSet
- 5. Conclusion
- Labels:
- SHARE:
- About Us
- Java 8 Tutorial
- Java Threads Tutorial
- Kotlin Conversions
- Kotlin Programs
- Java Conversions
- Java String API
- Spring Boot
- $show=Java%20Programs
- $show=Kotlin
How to Add Elements to an Array in Java
Array is a group of same data type elements and is considered a fixed-size data structure. In Java, you cannot directly add elements to an array because the location next to the last element of the array is available in memory or not is not known. However, there are some other ways for adding elements to an array.
This blog will explain how to add an element to an array in Java. So let’s get started!
Adding elements to a Java array
In Java, you can add elements to an array:
Now, let’s check out the stated method one by one.
Method 1: Adding Elements to array by creating a new Java array
To add elements to an array in Java, first create an array then copy the existing array elements in the newly created array. After doing so, you can add new elements to it.
Example
In this example, firstly, we will create an integer array named numArray[ ] with the following values:
In the next step, we will create a new integer type array named newNumArray[ ] with a greater size of the existing array:
The element 77 is stored in the variable named appendValue, which we want to add:
For printing the array numArray[ ], use the System.out.println() method:
Now, copy the elements of array numArray[ ] in a newly created array newNumArray[ ] by using a for loop:
Then, insert the value that is stored in appendValue variable in the newNumArray[ ]:
Lastly, print the newNumArray[] elements:
The given output indicates that 77 is successfully added in the newNumArray[ ]:
Now, let’s check out the other method for adding elements to an array in Java.
Method 2: Adding Elements to an array in Java by using ArrayList
You can also utilize Java ArrayList to add elements to an array. It is considered ideal as ArrayList is a re-sizable array.
Example
First of all, we will create an integer type array named numArray[ ] with the following values:
Print array by using the System.out.println() method:
Create an ArrayList named newNumArrayList and pass the array in it by using the aslist() method:
Add the required element in the created ArrayList with the help of the add() method:
Now, we will convert this ArrayList into an array by using the toArray() method:
Finally, print the array with the appended element:
Output
We have provided all of the necessary information related to adding elements to an array in Java.
Conclusion
In Java, elements can be added to an array by using Array List or creating a new array. The best and most efficient method is utilizing the ArrayList for the mentioned purpose. To do so, convert the existing array into an ArrayList, add required elements, and then convert it to a normal array. ArrayList also takes less memory space. This blog discussed the methods of adding elements to an array in Java.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.
Java adding element to array
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Java Add To Array — How to add element to an array in Java?
In java, once the array is created then it can not be resized. That means increasing or reducing the size in java is not possible.
2. Java add to array by recreating new array
Next, loop through the existing array and get each value. Now, add the value into the new array at the same index. At last, add new value to the last.
package com.javaprogramto.arrays.add; import java.util.Arrays; public class JavaArrayToAddExample < public static void main(String[] args) < int[] values = new int[5]; values[0] = 0; values[1] = 1; values[2] = 2; values[3] = 3; values[4] = 4; int[] newArray = new int[5 + 1]; for (int i = 0; i < values.length; i++) < newArray[i] = values[i]; >int newValue = 5; int newArraylength = newArray.length; newArray[newArraylength - 1] = newValue; System.out.println("existing array values " + Arrays.toString(values)); System.out.println("new array values " + Arrays.toString(newArray)); > >
existing array values [0, 1, 2, 3, 4] new array values [0, 1, 2, 3, 4, 5]
3. Java add to array by using intermediate storage — ArrayList
In this approach, We’ll use ArrayList as the temporary storage and convert arraylist back to array using toArray() method of List.
package com.javaprogramto.arrays.add; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class JavaArrayToAddExample2 < public static void main(String[] args) < Integer[] array = < 10, 20, 30, 40, 30, 40 >; System.out.println("Initial array values " + Arrays.toString(array)); List integers = new ArrayList<>(); for (int a : array) < integers.add(a); >int newValue = 50; integers.add(newValue); array = integers.toArray(array); System.out.println("Array after adding 50 value " + Arrays.toString(array)); > >
Initial array values [10, 20, 30, 40, 30, 40] Array after adding 50 value [10, 20, 30, 40, 30, 40, 50]
4. Java add to array using HashSet
But, you need to remember two things that if the array has duplicate values then the duplicate values are omitted from final array.
So this way is not recommended unless the above two are needed to remove the duplicate values and its order.
import java.util.Set; public class JavaArrayToAddExample3 < public static void main(String[] args) < Integer[] array = < 10, 20, 30, 40, 30, 40 >; System.out.println("Initial array values " + Arrays.toString(array)); Set integers = new HashSet<>(); for (int a : array) < integers.add(a); >int newValue = 50; integers.add(newValue); array = integers.toArray(array); System.out.println("Array after adding 50 value " + Arrays.toString(array)); > >
Initial array values [10, 20, 30, 40, 30, 40] Array after adding 50 value [50, 20, 40, 10, 30, null]
5. Conclusion
Labels:
SHARE:
About Us
Java 8 Tutorial
- Java 8 New Features
- Java 8 Examples Programs Before and After Lambda
- Java 8 Lambda Expressions (Complete Guide)
- Java 8 Lambda Expressions Rules and Examples
- Java 8 Accessing Variables from Lambda Expressions
- Java 8 Method References
- Java 8 Functional Interfaces
- Java 8 — Base64
- Java 8 Default and Static Methods In Interfaces
- Java 8 Optional
- Java 8 New Date Time API
- Java 8 — Nashorn JavaScript
Java Threads Tutorial
Kotlin Conversions
Kotlin Programs
Java Conversions
- Java 8 List To Map
- Java 8 String To Date
- Java 8 Array To List
- Java 8 List To Array
- Java 8 Any Primitive To String
- Java 8 Iterable To Stream
- Java 8 Stream To IntStream
- String To Lowercase
- InputStream To File
- Primitive Array To List
- Int To String Conversion
- String To ArrayList
Java String API
- charAt()
- chars() — Java 9
- codePointAt()
- codePointCount()
- codePoints() — Java 9
- compareTo()
- compareToIgnoreCase
- concat()
- contains()
- contentEquals()
- copyValueOf()
- describeConstable() — Java 12
- endsWith()
- equals()
- equalsIgnoreCase()
- format()
- getBytes()
- getChars()
- hashcode()
- indent() — Java 12
- indexOf()
- intern()
- isBlank() — java 11
- isEmpty()
- join()
- lastIndexOf()
- length()
- lines()
- matches()
- offsetByCodePoints()
- regionMatches()
- repeat()
- replaceFirst()
- replace()
- replaceAll()
- resolveConstantDesc()
- split()
- strip(), stripLeading(), stripTrailing()
- substring()
- toCharArray()
- toLowerCase()
- transform() — Java 12
- valueOf()
Spring Boot
$show=Java%20Programs
$show=Kotlin
accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
A quick guide on how to add an element to the array in java. Arrays are in fixed size in java but recreate the array with new value and with arraylist