How to Extend an Array After Initialisation in Java?
Last Updated :
05 Aug, 2021
In java, the arrays are immutable i.e if the array is once assigned or instantiated the memory allocated for the array can’t be decreased or increased. But there is one form of a solution in which we can extend the array.
Extending an array after initialization: As we can’t modify the array size after the declaration of the array, we can only extend it by initializing a new array and copying the values of the old array to the new array, and then we can assign new values to the array according to the size of the array declared.
Below are the examples to show extending the array after initialization.
Example 1:
Java
import java.lang.*;
class ExtendingArray {
public static void main(String[] args)
{
String[] words = new String[] { "G" , "E" , "E" };
String[] extendWords = new String[ 5 ];
extendWords[ 3 ] = "K" ;
extendWords[ 4 ] = "S" ;
System.arraycopy(words, 0 , extendWords, 0 ,
words.length);
for (String str : extendWords) {
System.out.print(str);
}
}
}
|
Example 2:
Java
import java.lang.*;
class ExtendingArray {
public static void extendedArray()
{
int [] num = new int [] { 1 , 2 , 3 , 4 , 5 , 6 };
int [] extendnum = new int [ 10 ];
extendnum[ 6 ] = 7 ;
extendnum[ 7 ] = 8 ;
extendnum[ 8 ] = 9 ;
extendnum[ 9 ] = 10 ;
System.arraycopy(num, 0 , extendnum, 0 , num.length);
for ( int str : extendnum)
System.out.println(str);
}
public static void main(String[] args)
{
ExtendingArray exarr = new ExtendingArray();
exarr.extendedArray();
}
}
|
Output
1
2
3
4
5
6
7
8
9
10
Share your thoughts in the comments
Please Login to comment...