Write a Java program to retrieve but does not remove, the first element of a linked list


The Java code provided demonstrates how to retrieve the first element of a linked list using the peekFirst method.

  • The code defines a class named Retrieve_FirstElement with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a LinkedList object named b_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Java", "C", "Cpp", "Python", and "Php" are added to b_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the initial contents of b_list before any modifications.
  • The b_list.peekFirst() method is called to retrieve the first element in b_list without removing it. The peekFirst method returns the first element in the linked list, or null if the list is empty.
  • The retrieved first element is stored in a variable b.
  • A System.out.println statement is used to print the message "First Element in the linked list :" followed by the value of b, which will be the first element in b_list.
  • Another System.out.println statement is used to print the contents of b_list after retrieving the first element, which will remain unchanged as the peekFirst method does not remove the element from the linked list.
  • The output of the program will be the initial contents of b_list printed on the first line, followed by the message "First Element in the linked list :" printed on the second line with the value of the first element, and the contents of b_list printed on the third line.

Source Code

import java.util.*;
public class Retrieve_FirstElement
{
	public static void main(String[] args)
	{
		LinkedList <String> b_list = new LinkedList <String> ();
		b_list.add("Java");
		b_list.add("C");
		b_list.add("Cpp");
		b_list.add("Python");
		b_list.add("Php");
		System.out.println("Given linked list: " + b_list); 
		String b = b_list.peekFirst();
		System.out.println("First Element in the linked list : " + b);
		System.out.println("New linked list: " + b_list);   
	}
}

Output

Given linked list: [Java, C, Cpp, Python, Php]
First Element in the linked list : Java
New linked list: [Java, C, Cpp, Python, Php]

Example Programs