Write a Java program to iterate through all elements in a linked list


This Java code demonstrates how to iterate over the elements of a linked list using a for-each loop.

  • The code defines a class named Iterate_Element with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a new LinkedList object named book_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Java", "C", "Cpp", etc., are added to the book_list using the add method, which appends the elements to the end of the list.
  • A for-each loop is used to iterate over the elements of the book_list. The loop iterates over each element of the list and assigns it to a local variable b of type String in each iteration.
  • Inside the loop, the System.out.println statement is used to print the value of b, which represents the current element of the linked list.
  • The loop continues until all elements of the book_list have been iterated over.
  • The output of the program will be the elements of the book_list printed on separate lines, as each element is printed by the System.out.println statement inside the loop.

Source Code

import java.util.LinkedList;
public class Iterate_Element
{
	public static void main(String[] args)
	{
		LinkedList<String> book_list = new LinkedList<String>();
		book_list.add("Java");
		book_list.add("C");
		book_list.add("Cpp");
		book_list.add("Python");
		book_list.add("Php");
		book_list.add("Css");
		book_list.add("Html");
		book_list.add("MySql");
		for (String b : book_list)
		{
			System.out.println(b);
		}
	}
}

Output

Java
C
Cpp
Python
Php
Css
Html
MySql

Example Programs