Write a Java program to Insert an element at the end of the LinkedList collection


The code demonstrates how to use the addLast method of LinkedList in Java to add an element at the end of the list. In the Element_End class, a LinkedList object named fru is created with a type parameter specified as String, indicating that it can only hold items of type String. Several fruit names, including "Papaya", "Mulberry", "Apple", "Banana", "Cherry", and "Watermelon", are added to the fru list using the add method.

The System.out.println statement is used to print the fruit names in the fru list. The addLast method is then called on the fru list with the argument "Mango", which is the fruit being added to the end of the list. The addLast method appends the specified element to the end of the list.

Finally, another System.out.println statement is used to print the fruit names in the fru list after the new fruit "Mango" has been added at the end of the list using the addLast method.

Source Code

import java.util.LinkedList;
public class Element_End
{
	public static void main(String[] args)
	{
		LinkedList <String> fru = new LinkedList <String>();
		fru.add("Papaya");
		fru.add("Mulberry");
		fru.add("Apple");
		fru.add("Banana");
		fru.add("Cherry");
		fru.add("Watermelon");
 
		System.out.println("Fruit Names : " + fru);
		fru.addLast("Mango");
		System.out.println("Fruit Names : " + fru);
	}
}

Output

Fruit Names : [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon]
Fruit Names : [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon, Mango]

Example Programs