Write a Java Program to Add elements to a LinkedList

In Java, a linked list is a type of data structure that allows the storage and manipulation of elements in a sequence.

The LinkedList class in Java provides a built-in implementation of a linked list.


To add elements to a LinkedList in Java, follow these steps:

Create a LinkedList object

First, create an object of the LinkedList class.

This will create an empty list to which you can add elements.

LinkedList<String> list = new LinkedList<>();

Add elements to the LinkedList

To add elements to the LinkedList, use the add() method.

The add() method adds the specified element to the end of the list.

list.add("Java"); 
list.add("Python"); 
list.add("C++");

The above code will add three elements to the LinkedList.

To print the elements of the LinkedList, use a for loop to iterate over the list and print each element.

for (String language : list) 
{ 
  System.out.println(language); 
}

The above code will print the following output:

Java Python C++

The full code to add elements to a LinkedList in Java would look like this:

import java.util.LinkedList;
public class AddElementsToLinkedList 

{ 
public static void main(String[] args) 
{ 

LinkedList<String> list = new LinkedList<>(); 

list.add("Java"); list.add("Python"); 

list.add("C++"); 

for (String language : list) 
{ 
System.out.println(language);

In conclusion, adding elements to a LinkedList in Java is a simple process that involves creating a LinkedList object, adding elements using the add() method, and printing the elements using a for loop.