Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 76281
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T20:38:56+00:00 2026-05-10T20:38:56+00:00

I use x != null to avoid NullPointerException . Is there an alternative? if

  • 0

I use x != null to avoid NullPointerException. Is there an alternative?

if (x != null) {     // ... } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T20:38:57+00:00Added an answer on May 10, 2026 at 8:38 pm

    This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don’t know or don’t trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.

    To put this another way, there are two instances where null checking comes up:

    1. Where null is a valid response in terms of the contract; and

    2. Where it isn’t a valid response.

    (2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)

    "Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.

    public Foo(Bar bar) {     this.bar = Objects.requireNonNull(bar); } 

    It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.

    Objects.requireNonNull(someobject, "if someobject is null then something is wrong"); someobject.doCalc(); 

    Generally throwing a specific exception like NullPointerException when a value is null but shouldn’t be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.

    (1) is a little harder. If you have no control over the code you’re calling then you’re stuck. If null is a valid response, you have to check for it.

    If it’s code that you do control, however (and this is often the case), then it’s a different story. Avoid using nulls as a response. With methods that return collections, it’s easy: return empty collections (or arrays) instead of nulls pretty much all the time.

    With non-collections it might be harder. Consider this as an example: if you have these interfaces:

    public interface Action {   void doSomething(); }  public interface Parser {   Action findAction(String userInput); } 

    where Parser takes raw user input and finds something to do, perhaps if you’re implementing a command line interface for something. Now you might make the contract that it returns null if there’s no appropriate action. That leads the null checking you’re talking about.

    An alternative solution is to never return null and instead use the Null Object pattern:

    public class MyParser implements Parser {   private static Action DO_NOTHING = new Action() {     public void doSomething() { /* do nothing */ }   };    public Action findAction(String userInput) {     // ...     if ( /* we can't find any actions */ ) {       return DO_NOTHING;     }   } } 

    Compare:

    Parser parser = ParserFactory.getParser(); if (parser == null) {   // now what?   // this would be an example of where null isn't (or shouldn't be) a valid response } Action action = parser.findAction(someInput); if (action == null) {   // do nothing } else {   action.doSomething(); } 

    to

    ParserFactory.getParser().findAction(someInput).doSomething(); 

    which is a much better design because it leads to more concise code.

    That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message — especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.

    try {     ParserFactory.getParser().findAction(someInput).doSomething(); } catch(ActionNotFoundException anfe) {     userConsole.err(anfe.getMessage()); } 

    Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.

    public Action findAction(final String userInput) {     /* Code to return requested Action if found */     return new Action() {         public void doSomething() {             userConsole.err("Action not found: " + userInput);         }     } } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 138k
  • Answers 138k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You could split to get the querystring, then split to… May 12, 2026 at 7:29 am
  • Editorial Team
    Editorial Team added an answer You've already hinted at the explanation: an #import cycle. The… May 12, 2026 at 7:29 am
  • Editorial Team
    Editorial Team added an answer Your actions will return JSON typically. Blog posts all over.… May 12, 2026 at 7:29 am

Related Questions

I have to interface with a slightly archaic system that doesn't use webservices. In
I frequently have code that looks something like this: if (itm != null) {
This is somewhat of a sequel to Slow Exists Check . Alex's suggestion works
I use MVVM architecture to decouple my application. That is, you often see something

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.