Pages

Add element in array

Note : Source code below will show you how to add new element in a created array. It will add "monkey" word in an array that contains "lion","tiger","elephant","crocodile" word.

******************************************************
COMPLETE SOURCE CODE FOR : AddElementInArray.java
******************************************************


public class AddElementInArray
{
public static void main(String[]args)
{
//Create array with it's component
String[]animal={"lion","tiger","elephant","crocodile"};

//Add an element - "Monkey"
String a="monkey";

//Step 1:Create temp array (size=(arrayThatWeWantToAddElement)+1)
String[]temp=new String[(animal.length)+1];
System.arraycopy(animal,0,temp,0,animal.length);
temp[temp.length-1]=a;

//Make animal array point to temp array
animal=temp;

//Print all element in animal
int temp2=0;
while(temp2!=animal.length)
{
System.out.println(animal[temp2]);
temp2=temp2+1;
}
}
}


******************************************************
JUST COMPILE AND EXECUTE IT
******************************************************
Related Posts Plugin for WordPress, Blogger...