Write a Java program to Insert an item at the last of LinkedList using the offerLast() method


The code demonstrates how to use the offerLast method of LinkedList in Java to insert an item at the end of the list. In the Insert_ItemLast class, a LinkedList object named list is created without specifying a type parameter, allowing it to hold items of any type. Several items of different types, including 18, "JAVA", 54.78, 'J', and true, are added to the list using the add method.

The System.out.println statements are used to print the items in the list before and after inserting items at the last. The offerLast method is then used to insert 3.56 and "List" at the end of the list. The offerLast method returns true if the item was successfully added to the end of the list, and false otherwise.

After inserting the items at the last using offerLast, the updated list is printed using the System.out.println statement. Note that offerLast is equivalent to addLast and can be used interchangeably. They both insert an item at the end of the list.

Source Code

import java.util.LinkedList;
public class Insert_ItemLast
{
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.add(18);
		list.add("JAVA");
		list.add(54.78);
		list.add('J');
		list.add(true);
 
		System.out.println("LinkedList Items : " + list);	
 
		// Insert an element at the last of LinkedList
		list.offerLast(3.56); 
		list.offerLast("List"); 
 
		System.out.println("LinkedList Items : " + list);
	}
}

Output

LinkedList Items : [18, JAVA, 54.78, J, true]
LinkedList Items : [18, JAVA, 54.78, J, true, 3.56, List]

Example Programs