Removelast() java: In the previous article, we have discussed about Java LinkedList removeIf() Method with Examples
In this article we are going to see the use of Java LinkedList removeLast() method along with suitable examples.
Java LinkedList removeLast() Method with Examples
This java.util.LinkedList.removeLast()
method is used to remove any single element from the last/tail of the LinkedList. It returns the last element which got removed.
Syntax:
LinkedListName.removeLast()
Where,
LinkedListName
refers to the name of your LinkedList.
Let’s see removeLast() method with suitable examples.
Example-1: Java LinkedList removeLast() Method – Example with String Type LinkedList
Approach:
- Create a new LinkedList of type String.
- Add String elements into the LinkedList using the add() method.
- Display the LinkedList elements.
- Then remove the last element from the LinkedList using
removeLast()
method. - Print the new LinkedList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create a LinkedList of string datatype LinkedList<String> l = new LinkedList<String>(); // Adding some elements to the LinkedList l.add("Hello"); l.add("this"); l.add("is"); l.add("an"); l.add("example of removeLast() method"); // Prints the LinkedList elements System.out.println("The elements of LinkedList are: "+l); // removing the last element from the LinkedList l.removeLast(); // Prints the new LinkedList elements System.out.println("The new elements of LinkedList are: "+l); } }
Output: The elements of LinkedList are: [Hello, this, is, an, example of removeLast() method] The new elements of LinkedList are: [Hello, this, is, an]
Example-2: Java LinkedList removeLast() Method – Example with Integer Type LinkedList
Approach:
- Create a new LinkedList of type Integer.
- Add integer elements into the LinkedList using the add() method.
- Display the LinkedList elements.
- Then remove the last element from the LinkedList using
removeLast()
method. - Print the new LinkedList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create a LinkedList of Integer datatype LinkedList<Integer> l = new LinkedList<Integer>(); // Adding some elements to the LinkedList l.add(2); l.add(4); l.add(6); l.add(8); l.add(10); // Prints the LinkedList elements System.out.println("The elements of LinkedList are: "+l); // removing the last element from the LinkedList l.removeLast(); // Prints the new LinkedList elements System.out.println("The new elements of LinkedList are: "+l); } }
Output: The elements of LinkedList are: [2, 4, 6, 8, 10] The new elements of LinkedList are: [2, 4, 6, 8]
Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.
Related Java Programs: