Can we insert null values in a Java list?

JavaObject Oriented ProgrammingProgramming

Solution

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

Syntax

boolean add(E e)

Appends the specified element to the end of this list.

Type Parameter

  • − The runtime type of the element.

Parameters

  • − Element to be appended to this list

Returns

It returns true.

Throws

  • UnsupportedOperationException − If the add operation is not supported by this list

  • ClassCastException − If the class of the specified element prevents it from being added to this list

  • NullPointerException − If the specified element is null and this list does not permit null elements

  • IllegalArgumentException − If some property of this element prevents it from being added to this list

Example

The following example shows how to insert null values to the list using add() method.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {

      // Create a list object
      List<String> list = new ArrayList<>();

      // add elements to the list
      list.add("A");
      list.add(null);
      list.add("B");
      list.add(null);
      list.add("C");

      // print the list
      System.out.println(list);
   }
}

Output

This will produce the following result −

[A, null, B, null, C]
raja
Updated on 09-May-2022 11:23:46

Advertisements