www.baeldung.com Open in urlscan Pro
2606:4700:3108::ac42:28f8  Public Scan

Submitted URL: https://t.dripemail3.com/c/eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJkZXRvdXIiLCJpc3MiOiJtb25vbGl0aCIsInN1YiI6ImRldG91cl9saW5rIiwia...
Effective URL: https://www.baeldung.com/java-convert-null-default-value?__s=p0jt5hmo26c8zpzrht7z
Submission: On January 23 via manual from US — Scanned from DE

Form analysis 3 forms found in the DOM

POST https://www.baeldung.com/wp-admin/admin-ajax.php?action=wpdAddSubscription

<form action="https://www.baeldung.com/wp-admin/admin-ajax.php?action=wpdAddSubscription" method="post" id="wpdiscuz-subscribe-form">
  <div class="wpdiscuz-subscribe-form-intro">Notify of </div>
  <div class="wpdiscuz-subscribe-form-option" style="width:40%;">
    <select class="wpdiscuz_select" name="wpdiscuzSubscriptionType">
      <option value="post">new follow-up comments</option>
      <option value="all_comment">new replies to my comments</option>
    </select>
  </div>
  <div class="wpdiscuz-item wpdiscuz-subscribe-form-email">
    <input class="email" type="email" name="wpdiscuzSubscriptionEmail" required="required" value="" placeholder="Email">
  </div>
  <div class="wpdiscuz-subscribe-form-button">
    <input id="wpdiscuz_subscription_button" class="wpd-prim-button wpd_not_clicked" type="submit" value="›" name="wpdiscuz_subscription_button">
  </div>
  <input type="hidden" id="wpdiscuz_subscribe_form_nonce" name="wpdiscuz_subscribe_form_nonce" value="07bf4bff6f"><input type="hidden" name="_wp_http_referer" value="/java-convert-null-default-value?__s=p0jt5hmo26c8zpzrht7z">
</form>

POST

<form method="post" enctype="multipart/form-data" data-uploading="false" class="wpd_comm_form wpd_main_comm_form">
  <div class="wpd-field-comment">
    <div class="wpdiscuz-item wc-field-textarea">
      <div class="wpdiscuz-textarea-wrap ">
        <div class="wpd-avatar">
          <img alt="guest" src="https://secure.gravatar.com/avatar/bc5932df0989492a16a4052a3836dfc8?s=56&amp;r=g" srcset="https://secure.gravatar.com/avatar/bc5932df0989492a16a4052a3836dfc8?s=112&amp;r=g 2x" class="avatar avatar-56 photo" height="56"
            width="56" decoding="async">
        </div>
        <div id="wpd-editor-wraper-0_0" style="">
          <label style="display: none;" for="wc-textarea-0_0">Label</label>
          <div id="wpd-editor-0_0" class="ql-container ql-snow">
            <div class="ql-editor ql-blank" data-gramm="false" contenteditable="true" data-placeholder="Join the discussion">
              <p><br></p>
            </div>
            <div class="ql-clipboard" contenteditable="true" tabindex="-1"></div>
            <div class="ql-tooltip ql-hidden"><a class="ql-preview" target="_blank" href="about:blank"></a><input type="text" data-formula="e=mc^2" data-link="https://example.com"
                data-video="Embed URL"><a class="ql-action"></a><a class="ql-remove"></a></div>
            <div class="ql-texteditor"><textarea id="wc-textarea-0_0" name="wc_comment" class="wc_comment wpd-field" style="display: none;"></textarea></div>
          </div>
          <div id="wpd-editor-toolbar-0_0" class="ql-toolbar ql-snow">
            <button title="Bold" class="ql-bold" type="button"><svg viewBox="0 0 18 18">
                <path class="ql-stroke" d="M5,4H9.5A2.5,2.5,0,0,1,12,6.5v0A2.5,2.5,0,0,1,9.5,9H5A0,0,0,0,1,5,9V4A0,0,0,0,1,5,4Z"></path>
                <path class="ql-stroke" d="M5,9h5.5A2.5,2.5,0,0,1,13,11.5v0A2.5,2.5,0,0,1,10.5,14H5a0,0,0,0,1,0,0V9A0,0,0,0,1,5,9Z"></path>
              </svg></button>
            <button title="Italic" class="ql-italic" type="button"><svg viewBox="0 0 18 18">
                <line class="ql-stroke" x1="7" x2="13" y1="4" y2="4"></line>
                <line class="ql-stroke" x1="5" x2="11" y1="14" y2="14"></line>
                <line class="ql-stroke" x1="8" x2="10" y1="14" y2="4"></line>
              </svg></button>
            <button title="Underline" class="ql-underline" type="button"><svg viewBox="0 0 18 18">
                <path class="ql-stroke" d="M5,3V9a4.012,4.012,0,0,0,4,4H9a4.012,4.012,0,0,0,4-4V3"></path>
                <rect class="ql-fill" height="1" rx="0.5" ry="0.5" width="12" x="3" y="15"></rect>
              </svg></button>
            <button title="Strike" class="ql-strike" type="button"><svg viewBox="0 0 18 18">
                <line class="ql-stroke ql-thin" x1="15.5" x2="2.5" y1="8.5" y2="9.5"></line>
                <path class="ql-fill" d="M9.007,8C6.542,7.791,6,7.519,6,6.5,6,5.792,7.283,5,9,5c1.571,0,2.765.679,2.969,1.309a1,1,0,0,0,1.9-.617C13.356,4.106,11.354,3,9,3,6.2,3,4,4.538,4,6.5a3.2,3.2,0,0,0,.5,1.843Z"></path>
                <path class="ql-fill" d="M8.984,10C11.457,10.208,12,10.479,12,11.5c0,0.708-1.283,1.5-3,1.5-1.571,0-2.765-.679-2.969-1.309a1,1,0,1,0-1.9.617C4.644,13.894,6.646,15,9,15c2.8,0,5-1.538,5-3.5a3.2,3.2,0,0,0-.5-1.843Z"></path>
              </svg></button>
            <button title="Ordered List" class="ql-list" value="ordered" type="button"><svg viewBox="0 0 18 18">
                <line class="ql-stroke" x1="7" x2="15" y1="4" y2="4"></line>
                <line class="ql-stroke" x1="7" x2="15" y1="9" y2="9"></line>
                <line class="ql-stroke" x1="7" x2="15" y1="14" y2="14"></line>
                <line class="ql-stroke ql-thin" x1="2.5" x2="4.5" y1="5.5" y2="5.5"></line>
                <path class="ql-fill" d="M3.5,6A0.5,0.5,0,0,1,3,5.5V3.085l-0.276.138A0.5,0.5,0,0,1,2.053,3c-0.124-.247-0.023-0.324.224-0.447l1-.5A0.5,0.5,0,0,1,4,2.5v3A0.5,0.5,0,0,1,3.5,6Z"></path>
                <path class="ql-stroke ql-thin" d="M4.5,10.5h-2c0-.234,1.85-1.076,1.85-2.234A0.959,0.959,0,0,0,2.5,8.156"></path>
                <path class="ql-stroke ql-thin" d="M2.5,14.846a0.959,0.959,0,0,0,1.85-.109A0.7,0.7,0,0,0,3.75,14a0.688,0.688,0,0,0,.6-0.736,0.959,0.959,0,0,0-1.85-.109"></path>
              </svg></button>
            <button title="Unordered List" class="ql-list" value="bullet" type="button"><svg viewBox="0 0 18 18">
                <line class="ql-stroke" x1="6" x2="15" y1="4" y2="4"></line>
                <line class="ql-stroke" x1="6" x2="15" y1="9" y2="9"></line>
                <line class="ql-stroke" x1="6" x2="15" y1="14" y2="14"></line>
                <line class="ql-stroke" x1="3" x2="3" y1="4" y2="4"></line>
                <line class="ql-stroke" x1="3" x2="3" y1="9" y2="9"></line>
                <line class="ql-stroke" x1="3" x2="3" y1="14" y2="14"></line>
              </svg></button>
            <button title="Blockquote" class="ql-blockquote" type="button"><svg viewBox="0 0 18 18">
                <rect class="ql-fill ql-stroke" height="3" width="3" x="4" y="5"></rect>
                <rect class="ql-fill ql-stroke" height="3" width="3" x="11" y="5"></rect>
                <path class="ql-even ql-fill ql-stroke" d="M7,8c0,4.031-3,5-3,5"></path>
                <path class="ql-even ql-fill ql-stroke" d="M14,8c0,4.031-3,5-3,5"></path>
              </svg></button>
            <button title="Code Block" class="ql-code-block" type="button"><svg viewBox="0 0 18 18">
                <polyline class="ql-even ql-stroke" points="5 7 3 9 5 11"></polyline>
                <polyline class="ql-even ql-stroke" points="13 7 15 9 13 11"></polyline>
                <line class="ql-stroke" x1="10" x2="8" y1="5" y2="13"></line>
              </svg></button>
            <button title="Link" class="ql-link" type="button"><svg viewBox="0 0 18 18">
                <line class="ql-stroke" x1="7" x2="11" y1="7" y2="11"></line>
                <path class="ql-even ql-stroke" d="M8.9,4.577a3.476,3.476,0,0,1,.36,4.679A3.476,3.476,0,0,1,4.577,8.9C3.185,7.5,2.035,6.4,4.217,4.217S7.5,3.185,8.9,4.577Z"></path>
                <path class="ql-even ql-stroke" d="M13.423,9.1a3.476,3.476,0,0,0-4.679-.36,3.476,3.476,0,0,0,.36,4.679c1.392,1.392,2.5,2.542,4.679.36S14.815,10.5,13.423,9.1Z"></path>
              </svg></button>
            <button title="Source Code" class="ql-sourcecode" data-wpde_button_name="sourcecode" type="button">{}</button>
            <button title="Spoiler" class="ql-spoiler" data-wpde_button_name="spoiler" type="button">[+]</button>
            <div class="wpd-editor-buttons-right">
              <span class="wmu-upload-wrap" wpd-tooltip="Attach an image to this comment" wpd-tooltip-position="left"><label class="wmu-add"><i class="far fa-image"></i><input style="display:none;" class="wmu-add-files" type="file" name="wmu_files[]"
                    accept="image/*"></label></span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="wpd-form-foot" style="display:none;">
    <div class="wpdiscuz-textarea-foot">
      <div class="wpdiscuz-button-actions">
        <div class="wmu-action-wrap">
          <div class="wmu-tabs wmu-images-tab wmu-hide"></div>
        </div>
      </div>
    </div>
    <div class="wpd-form-row">
      <div class="wpd-form-col-left">
        <div class="wpdiscuz-item wc_name-wrapper wpd-has-icon">
          <div class="wpd-field-icon"><i class="fas fa-user"></i>
          </div>
          <input id="wc_name-0_0" value="" required="required" aria-required="true" class="wc_name wpd-field" type="text" name="wc_name" placeholder="Name*" maxlength="50" pattern=".{3,50}" title="">
          <label for="wc_name-0_0" class="wpdlb">Name*</label>
        </div>
        <div class="wpdiscuz-item wc_email-wrapper wpd-has-icon">
          <div class="wpd-field-icon"><i class="fas fa-at"></i>
          </div>
          <input id="wc_email-0_0" value="" required="required" aria-required="true" class="wc_email wpd-field" type="email" name="wc_email" placeholder="Email*">
          <label for="wc_email-0_0" class="wpdlb">Email*</label>
        </div>
        <div class="wpdiscuz-item wc_website-wrapper wpd-has-icon">
          <div class="wpd-field-icon"><i class="fas fa-link"></i>
          </div>
          <input id="wc_website-0_0" value="" class="wc_website wpd-field" type="text" name="wc_website" placeholder="Website">
          <label for="wc_website-0_0" class="wpdlb">Website</label>
        </div>
      </div>
      <div class="wpd-form-col-right">
        <div class="wpd-field-captcha wpdiscuz-item">
          <div class="wpdiscuz-recaptcha" id="wpdiscuz-recaptcha-0_0" style="transform: scale(0.9);">
            <div style="width: 304px; height: 78px;">
              <div><iframe title="reCAPTCHA" width="304" height="78" role="presentation" name="a-jptleobb820h" frameborder="0" scrolling="no"
                  sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox allow-storage-access-by-user-activation"
                  src="https://www.google.com/recaptcha/api2/anchor?ar=1&amp;k=6Ld-Zx0lAAAAAPX0M-0_gK5m8ehXrTgnk0lR9d4a&amp;co=aHR0cHM6Ly93d3cuYmFlbGR1bmcuY29tOjQ0Mw..&amp;hl=de&amp;v=Ya-Cd6PbRI5ktAHEhm9JuKEu&amp;theme=light&amp;size=normal&amp;cb=a6pv5kw6jmzn"></iframe>
              </div><textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response"
                style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none; display: none;"></textarea>
            </div><iframe style="display: none;"></iframe>
          </div>
          <input id="wpdiscuz-recaptcha-field-0_0" type="hidden" name="wc_captcha" value="" required="required" aria-required="true" class="wpdiscuz_reset">
          <div class="clearfix"></div>
        </div>
        <div class="wc-field-submit">
          <label class="wpd_label" wpd-tooltip="Notify of new replies to this comment">
            <input id="wc_notification_new_comment-0_0" class="wc_notification_new_comment-0_0 wpd_label__checkbox" value="comment" type="checkbox" name="wpdiscuz_notification_type">
            <span class="wpd_label__text">
              <span class="wpd_label__check">
                <i class="fas fa-bell wpdicon wpdicon-on"></i>
                <i class="fas fa-bell-slash wpdicon wpdicon-off"></i>
              </span>
            </span>
          </label>
          <input id="wpd-field-submit-0_0" class="wc_comm_submit wpd_not_clicked wpd-prim-button" type="submit" name="submit" value="Post Comment" aria-label="Post Comment">
        </div>
      </div>
      <div class="clearfix"></div>
    </div>
  </div>
  <input type="hidden" class="wpdiscuz_unique_id" value="0_0" name="wpdiscuz_unique_id">
</form>

POST

<form method="post" enctype="multipart/form-data" data-uploading="false" class="wpd_comm_form wpd-secondary-form-wrapper">
  <div class="wpd-field-comment">
    <div class="wpdiscuz-item wc-field-textarea">
      <div class="wpdiscuz-textarea-wrap ">
        <div class="wpd-avatar">
          <img alt="guest" src="https://secure.gravatar.com/avatar/ed41c1d59b0cab1d086efe260ae08753?s=56&amp;r=g" srcset="https://secure.gravatar.com/avatar/ed41c1d59b0cab1d086efe260ae08753?s=112&amp;r=g 2x" class="avatar avatar-56 photo" height="56"
            width="56" decoding="async">
        </div>
        <div id="wpd-editor-wraper-wpdiscuzuniqueid" style="display: none;">
          <div id="wpd-editor-char-counter-wpdiscuzuniqueid" class="wpd-editor-char-counter"></div>
          <label style="display: none;" for="wc-textarea-wpdiscuzuniqueid">Label</label>
          <textarea id="wc-textarea-wpdiscuzuniqueid" name="wc_comment" class="wc_comment wpd-field"></textarea>
          <div id="wpd-editor-wpdiscuzuniqueid"></div>
          <div id="wpd-editor-toolbar-wpdiscuzuniqueid">
            <button title="Bold" class="ql-bold"></button>
            <button title="Italic" class="ql-italic"></button>
            <button title="Underline" class="ql-underline"></button>
            <button title="Strike" class="ql-strike"></button>
            <button title="Ordered List" class="ql-list" value="ordered"></button>
            <button title="Unordered List" class="ql-list" value="bullet"></button>
            <button title="Blockquote" class="ql-blockquote"></button>
            <button title="Code Block" class="ql-code-block"></button>
            <button title="Link" class="ql-link"></button>
            <button title="Source Code" class="ql-sourcecode" data-wpde_button_name="sourcecode">{}</button>
            <button title="Spoiler" class="ql-spoiler" data-wpde_button_name="spoiler">[+]</button>
            <div class="wpd-editor-buttons-right">
              <span class="wmu-upload-wrap" wpd-tooltip="Attach an image to this comment" wpd-tooltip-position="left"><label class="wmu-add"><i class="far fa-image"></i><input style="display:none;" class="wmu-add-files" type="file" name="wmu_files[]"
                    accept="image/*"></label></span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="wpd-form-foot" style="display:none;">
    <div class="wpdiscuz-textarea-foot">
      <div class="wpdiscuz-button-actions">
        <div class="wmu-action-wrap">
          <div class="wmu-tabs wmu-images-tab wmu-hide"></div>
        </div>
      </div>
    </div>
    <div class="wpd-form-row">
      <div class="wpd-form-col-left" style="width: 45%;">
        <div class="wpdiscuz-item wc_name-wrapper wpd-has-icon">
          <div class="wpd-field-icon"><i class="fas fa-user"></i>
          </div>
          <input id="wc_name-wpdiscuzuniqueid" value="" required="required" aria-required="true" class="wc_name wpd-field" type="text" name="wc_name" placeholder="Name*" maxlength="50" pattern=".{3,50}" title="">
          <label for="wc_name-wpdiscuzuniqueid" class="wpdlb">Name*</label>
        </div>
        <div class="wpdiscuz-item wc_email-wrapper wpd-has-icon">
          <div class="wpd-field-icon"><i class="fas fa-at"></i>
          </div>
          <input id="wc_email-wpdiscuzuniqueid" value="" required="required" aria-required="true" class="wc_email wpd-field" type="email" name="wc_email" placeholder="Email*">
          <label for="wc_email-wpdiscuzuniqueid" class="wpdlb">Email*</label>
        </div>
        <div class="wpdiscuz-item wc_website-wrapper wpd-has-icon">
          <div class="wpd-field-icon"><i class="fas fa-link"></i>
          </div>
          <input id="wc_website-wpdiscuzuniqueid" value="" class="wc_website wpd-field" type="text" name="wc_website" placeholder="Website">
          <label for="wc_website-wpdiscuzuniqueid" class="wpdlb">Website</label>
        </div>
      </div>
      <div class="wpd-form-col-right" style="width: 55%;">
        <div class="wpd-field-captcha wpdiscuz-item">
          <div class="wpdiscuz-recaptcha" id="wpdiscuz-recaptcha-wpdiscuzuniqueid" style="transform-origin: right 0px; transform: scale(0.8);"></div>
          <input id="wpdiscuz-recaptcha-field-wpdiscuzuniqueid" type="hidden" name="wc_captcha" value="" required="required" aria-required="true" class="wpdiscuz_reset">
          <div class="clearfix"></div>
        </div>
        <div class="wc-field-submit">
          <label class="wpd_label" wpd-tooltip="Notify of new replies to this comment">
            <input id="wc_notification_new_comment-wpdiscuzuniqueid" class="wc_notification_new_comment-wpdiscuzuniqueid wpd_label__checkbox" value="comment" type="checkbox" name="wpdiscuz_notification_type">
            <span class="wpd_label__text">
              <span class="wpd_label__check">
                <i class="fas fa-bell wpdicon wpdicon-on"></i>
                <i class="fas fa-bell-slash wpdicon wpdicon-off"></i>
              </span>
            </span>
          </label>
          <input id="wpd-field-submit-wpdiscuzuniqueid" class="wc_comm_submit wpd_not_clicked wpd-prim-button" type="submit" name="submit" value="Post Comment" aria-label="Post Comment">
        </div>
      </div>
      <div class="clearfix"></div>
    </div>
  </div>
  <input type="hidden" class="wpdiscuz_unique_id" value="wpdiscuzuniqueid" name="wpdiscuz_unique_id">
</form>

Text Content

WE VALUE YOUR PRIVACY

We and our partners store and/or access information on a device, such as cookies
and process personal data, such as unique identifiers and standard information
sent by a device for personalised ads and content, ad and content measurement,
and audience insights, as well as to develop and improve products. With your
permission we and our partners may use precise geolocation data and
identification through device scanning. You may click to consent to our and our
760 partners’ processing as described above. Alternatively you may access more
detailed information and change your preferences before consenting or to refuse
consenting. Please note that some processing of your personal data may not
require your consent, but you have a right to object to such processing. Your
preferences will apply to this website only. You can change your preferences at
any time by returning to this site or visit our privacy policy.
MORE OPTIONSAGREE

 * 
 * 
 * Start Here
 * Courses ▼▲
   
   
    * REST WITH SPRING
      
      The canonical reference for building a production grade API with Spring
   
   
    * LEARN SPRING SECURITY ▼▲
      
      THE unique Spring Security education if you’re working with Java today
      
      
       * LEARN SPRING SECURITY CORE
         
         Focus on the Core of Spring Security 6
      
      
       * LEARN SPRING SECURITY OAUTH
         
         Focus on the new OAuth2 stack in Spring Security 6
   
   
    * LEARN SPRING
      
      From no experience to actually building stuff
   
   
    * LEARN SPRING DATA JPA
      
      The full guide to persistence with Spring Data JPA

 * Guides ▼▲
   
   
    * PERSISTENCE
      
      The Persistence with Spring guides
   
   
    * REST
      
      The guides on building REST APIs with Spring
   
   
    * SECURITY
      
      The Spring Security guides

 * About ▼▲
   
   
    * FULL ARCHIVE
      
      The high level overview of all the articles on the site.
   
   
    * BAELDUNG EBOOKS
      
      Discover all of our eBooks
   
   
    * ABOUT BAELDUNG
      
      About Baeldung.

 * 
 * 




CONVERT NULL VALUE TO A DEFAULT VALUE IN JAVA



Last updated: January 22, 2024

Written by: Eugene Kovko
 * Core Java

 * Java Null

Course – LS – All


GET STARTED WITH SPRING AND SPRING BOOT, THROUGH THE LEARN SPRING COURSE:

>> CHECK OUT THE COURSE



1. OVERVIEW



In 1965, Tony Hoare introduced the concept of a null reference. Since then,
countless hours have been spent reading the logs and trying to find the source
of NullPointerExceptions. This exception is so ubiquitous that it’s common to
refer to it as NPE.

In this tutorial, we’ll learn how to mitigate this problem. We’ll review several
techniques that simplify converting nulls to default values.


2. SIMPLE IF STATEMENTS



The easiest way to approach the conversion is to use if statements. They’re
basic language structures and benefit from being clear to developers with
different experiences and levels. The best part of this approach is that it’s
verbose, which simultaneously is the worst part:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenIfWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = defaultValue;
    if (givenValue != null) {
        actual = givenValue;
    }
    assertDefaultConversion(givenValue, defaultValue, actual);
}Copy

Because we have total control over the logic, we can easily change, extract, and
reuse it. Additionally, we can make it lazy if we want:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenIfWhenNotNullThenReturnsDefault(String givenValue, String expected, Supplier<String> expensiveSupplier) {
    String actual;
    if (givenValue != null) {
        actual = givenValue;
    } else {
        actual = expensiveSupplier.get();
    }
    assertDefaultConversion(givenValue, expected, actual);
}Copy

If the operations are quite simple, we can use a ternary operator to make them
more inlined. The Elvis operator didn’t make it into Java, but we still can
improve the code:



@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenTernaryWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = givenValue != null ? givenValue : defaultValue;
    assertDefaultConversion(givenValue, defaultValue, actual);
}Copy

Also, it allows a lazy approach as only the required expressions are evaluated:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenLazyTernaryWhenNotNullThenReturnsDefault(String givenValue, String expected, 
  Supplier<String> expensiveSupplier) {
    String actual = givenValue != null ? givenValue : expensiveSupplier.get();
    assertDefaultConversion(givenValue, expected, actual);
}Copy

We can extract this logic into a separate method with a good name to make our
code more readable. However, Java and some external libraries have done it
already.


3. JAVA OBJECTS



Java 9 provides us with two utility methods: Objects.requireNonNullElse and
Objects.requireNonNullElseGet. These methods have implementations similar to
those we reviewed. Overall, they provide a better API and make the code
self-explanatory:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenObjectsWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = requireNonNullElse(givenValue, defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}Copy

Static imports can help us remove the Objects class name to reduce the noise.
The lazy version looks like this:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenLazyObjectsWhenNotNullThenReturnsDefault(String givenValue, String expected,
  Supplier<String> expensiveSupplier) {
    String actual = requireNonNullElseGet(givenValue, expensiveSupplier);
    assertDefaultConversion(givenValue, expected, actual);
}Copy

However, this API is accessible starting only from Java 9. At the same time,
Java 8 also provides some convenient tools to achieve a similar result.




4. JAVA OPTIONAL<T>



The main idea behind the Optional<T> class was to fight the issue with null
checks and NullPointerExceptions. It’s possible to identify nullable APIs in
documentation, but a better solution is to show it explicitly in the code.
Getting an Optional<T> from some method unambiguously tells us the value might
be null. Also, IDEs can use static analysis for notifications and highlighting.

Explicit null checks weren’t the goal of this class. However, we can use it to
wrap a value we would like to check and do some operations over it:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenOptionalWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = Optional.ofNullable(givenValue).orElse(defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}Copy

The lazy version looks quite similar:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenLazyOptionalWhenNotNullThenReturnsDefault(String givenValue, String expected,
  Supplier<String> expensiveSupplier) {
    String actual = Optional.ofNullable(givenValue).orElseGet(expensiveSupplier);
    assertDefaultConversion(givenValue, expected, actual);
}Copy

Creating a separate wrapper object for a null check might be questionable. At
the same time, it might be useful for reaching through data objects without
chained null checks:

@Override
public Delivery calculateDeliveryForPerson(Long id) {
    Person person = getPersonById(id);
    if (person != null && person.getAddress() != null && person.getAddress().getZipCode() != null) {
        ZipCode zipCode = person.getAddress().getZipCode();
        String code = zipCode.getCode();
        return calculateDeliveryForZipCode(code);
    }
    return Delivery.defaultDelivery();
}Copy

We can do the same, but using Optional.map(Function<T, U>):



public Delivery calculateDeliveryForPerson(Long id) {
    return Optional.ofNullable(getPersonById(id))
      .map(Person::getAddress)
      .map(Address::getZipCode)
      .map(ZipCode::getCode)
      .map(this::calculateDeliveryForZipCode)
      .orElse(Delivery.defaultDelivery());
}Copy

Wrapping objects in Optional<T> early on can reduce the checking we must do
later.


5. GUAVA LIBRARY



We can import Guava to get a similar functionality if all the previous methods
aren’t suitable, for example, when using earlier versions of Java. Let’s start
by adding the dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.0.0-jre</version>
</dependency>Copy

It mirrors the Java functionality and doesn’t add any explicitly useful
features. To get a default value if the provided is null, we can use
MoreObjects:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenGuavaWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = MoreObjects.firstNonNull(givenValue, defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}Copy

MoreObjects replaces the Guava’s Objects utility class, which was deprecated and
planned for removal. However, it doesn’t allow the default value to be supplied
lazily. Also, it provides an Optional<T> class with the same name as Java but
resides in a different package:

@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenGuavaOptionalWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = com.google.common.base.Optional.fromNullable(givenValue).or(defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}Copy

We can also implement a chain of modifications using this class as well:

@Override
public Delivery calculateDeliveryForPerson(Long id) {
    return Optional.fromNullable(getPersonById(id))
      .transform(Person::getAddress)
      .transform(Address::getZipCode)
      .transform(ZipCode::getCode)
      .transform(this::calculateDeliveryForZipCode)
      .or(Delivery.defaultDelivery());
}
Copy

The transform method doesn’t allow null-returning functions. Thus, we must
ensure that none of the methods in the pipeline returns null. Overall, Guava is
a good substitution for Java features if they’re unavailable, but it provides
less functionality than Java Optional<T>.


6. APACHE COMMONS



Another library we can use to simplify our null checks is Apache Commons. Let’s
add dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>Copy

However, it provides only simple methods to get the first non-null value out of
several arguments:



@ParameterizedTest
@ArgumentsSource(ObjectsProvider.class)
void givenApacheWhenNotNullThenReturnsDefault(String givenValue, String defaultValue) {
    String actual = ObjectUtils.firstNonNull(givenValue, defaultValue);
    assertDefaultConversion(givenValue, defaultValue, actual);
}Copy

The lazy version is a little bit inconvenient API, as it requires Supplier<T>,
so we’ll have to wrap a value if we already have one:

@ParameterizedTest
@ArgumentsSource(ObjectsSupplierProvider.class)
void givenLazyApacheWhenNotNullThenReturnsDefault(String givenValue, String expected,
  Supplier<String> expensiveSupplier) {
    String actual = ObjectUtils.getFirstNonNull(() -> givenValue, expensiveSupplier);
    assertDefaultConversion(givenValue, expected, actual);
}Copy

Overall, this is also a nice substitution for Java features if they’re not
accessible to us for any reason.


7. CONCLUSION



NullPointerException is the most common exception developers face. There are
several convenient ways to ensure null safety. Java APIs and external libraries
provide many techniques. However, there’s nothing shameful to fall back to
simple if statements, as it’s clean, simple, and explicit.

The main goal of null checking is to do it as early as possible and ensure it’s
uniform across the project. The way we’re doing it isn’t essential.

As usual, all the code from the tutorial is available over on GitHub.

Course – LS – All


GET STARTED WITH SPRING AND SPRING BOOT, THROUGH THE LEARN SPRING COURSE:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Learning to build your API
with Spring?
Download the E-book

Subscribe

Notify of
new follow-up comments new replies to my comments


Label







{} [+]


Name*

Email*

Website



Label

{} [+]


Name*

Email*

Website


2 Comments

Oldest
Newest
Inline Feedbacks
View all comments
View Comments
Load More Comments



res – REST API (eBook) (everywhere)
Building a REST API with Spring?
Download the E-book





COURSES

 * All Courses
 * All Bulk Courses
 * All Bulk Team Courses
 * The Courses Platform

SERIES

 * Java “Back to Basics” Tutorial
 * Jackson JSON Tutorial
 * Apache HttpClient Tutorial
 * REST with Spring Tutorial
 * Spring Persistence Tutorial
 * Security with Spring
 * Spring Reactive Tutorials

ABOUT

 * About Baeldung
 * The Full Archive
 * Editors
 * Jobs
 * Our Partners
 * Partner with Baeldung

 * Terms of Service
 * Privacy Policy
 * Company Info
 * Contact


wpDiscuz


Insert