Java Add Element To List Example
Chapter:
Miscellaneous
Last Updated:
19-05-2023 05:53:13 UTC
Program:
/* ............... START ............... */
import java.util.ArrayList;
import java.util.List;
public class AddElementToListExample {
public static void main(String[] args) {
// Create a list
List<String> list = new ArrayList<>();
// Add elements to the list
list.add("Apple");
list.add("Banana");
list.add("Orange");
System.out.println("List before adding an element: " + list);
// Add a new element to the list
String newElement = "Grape";
list.add(newElement);
System.out.println("List after adding an element: " + list);
}
}
/* ............... END ............... */
Output
List before adding an element: [Apple, Banana, Orange]
List after adding an element: [Apple, Banana, Orange, Grape]
Notes:
-
In this example, we create an ArrayList called list to store a collection of strings. We add three elements ("Apple", "Banana", and "Orange") to the list using the add method. Then, we print the list before adding an element.
- Next, we create a String variable called newElement and assign it the value "Grape". We add this new element to the list using the add method again. Finally, we print the list after adding the new element.
Tags
Java Add Element To List Example #How do you add an element to a list in Java #List add elements