Ensure object not null

Ensure object not null

Easy Java Exceptions 17 views
Explanation Complexity

Problem Statement

Task: if obj is null throw NullPointerException else return it.

Input Format

An object reference obj.

Output Format

If obj is null → throw NullPointerException
Else → return obj.

Example

null
NullPointerException

Constraints

• obj can be any reference type

• Must manually check for null

Concept Explanation

If object reference is null, it means it does not point to any object.
So we throw NullPointerException.
Otherwise, we return the object safely.

Step-by-Step Explanation

1.Read object reference obj.

2.If obj == null:

• Throw new NullPointerException("Object is null").

3.Else:

• Return obj.

Concept Explanation

If object reference is null, it means it does not point to any object.
So we throw NullPointerException.
Otherwise, we return the object safely.

Step-by-Step Explanation

1.Read object reference obj.

2.If obj == null:

• Throw new NullPointerException("Object is null").

3.Else:

• Return obj.

Input / Output Format

Input Format
An object reference obj.
Output Format
If obj is null → throw NullPointerException
Else → return obj.
Constraints
• obj can be any reference type

• Must manually check for null

Examples

Input:
null
Output:
NullPointerException

Example Solution (Public)

Java
static <T> T requireNonNull(T obj){if(obj==null) throw new NullPointerException();return obj;}

Official Solution Code

static <T> T requireNonNull(T obj){if(obj==null) throw new NullPointerException();return obj;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.