Insert Null Values in a Java List



Yes, we can insert null values into a list easily using its add() method. In case of List implementation does not support null, then it will thrown a NullPointerException

List is an interface in Java that extends the Collection interface and provides a way to store an ordered collection of elements. It allows us to store duplicate elements, and it also maintains the order of insertion. The List interface is implemented by classes such as ArrayList, LinkedList, and Vector.

Null Values in a Java List

In Java, a List can contain null values. The List interface allows for the insertion of null elements, and most implementations of the List interface, such as ArrayList and LinkedList, support null values.

Let's look at an example of how to insert null values into a List:

Example 1

In this example, we will create a List of integers and insert null values into it using the add() method.

import java.util.ArrayList;
import java.util.List;
public class NullValuesInsertion {
   public static void main(String[] args){
      List<Integer> list = new ArrayList<>();
      list.add(1);  
      list.add(null);
      list.add(2);
      list.add(null);
      list.add(null);
      list.add(3);
      
      System.out.println("List after adding null values: " + list);
   }
}

Output

Following is the output of the above code:

List after adding null values: [1, null, 2, null, null, 3]

Example 2

In this example, we will create a List of strings and insert null values into it using the add() method.

import java.util.ArrayList;
import java.util.List;
public class NullValuesInsertion {
   public static void main(String[] args){
      List<String> list = new ArrayList<>();
      list.add("Hello");
      list.add(null);
      list.add("World");
      list.add(null);
      list.add("Java");
      list.add(null);
      
      System.out.println("List after adding null values: " + list);
   }
}

Output

Following is the output of the above code:

List after adding null values: [Hello, null, World, null, Java, null]
Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-06-13T12:42:48+05:30

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements