Home  >  Article  >  Java  >  Can we insert null value in Java list?

Can we insert null value in Java list?

PHPz
PHPzforward
2023-08-20 19:01:151279browse

Can we insert null value in Java list?

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

  • E − The runtime type of the element.

Parameters

  • e − The element to append to this list

Return value

Return true.

Throws

  • UnsupportedOperationException − If this list does not support the add operation

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

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

  • IllegalArgumentException − If some properties of this element prevent it from being added to this list

Example

The following example demonstrates how to use the add() method to insert null values ​​into a list.

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]

The above is the detailed content of Can we insert null value in Java list?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete