
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert Null Values in a 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 − 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]