Showing posts with label element. Show all posts
Showing posts with label element. Show all posts

Remove element from array

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


public class RemoveElementFromAnArray
{
public static void main(String[]args)
{
//Now we want to remove last element,"crocodile"
String[]animal={"lion","tiger","elephant","crocodile"};

//Step 1:Create a temp array with sizeArrayAnimal-1
String[]temp=new String[animal.length-1];

//Step 2:Copy element from "lion" to "elephant" into array temp
System.arraycopy(animal,0,temp,0,(animal.length-1));

//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
*************************************************

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
******************************************************

RELAXING NATURE VIDEO