CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2022
    Location
    Urbana, Illinios
    Posts
    14

    Java equals() selection

    In Java, if I try to do.equals() on a null string, a null pointer error is issued. I’m wondering whether I can perform the following if I’m attempting to compare if a string is equal to a constant string:
    Code:
    MY CONSTANT STRING.equals(aStringVariable)
    I’m sure it’ll work, but is this simply extremely bad code?
    This is a common Java idiom known colloquially as a Yoda condition. Personally, I prefer to handle the null situation directly, but the Yoda method is widely used, and any competent Java programmer should quickly grasp what is going on. How should I proceed?

  2. #2
    Join Date
    Feb 2017
    Posts
    677

    Re: Java equals() selection

    Quote Originally Posted by Nathan D View Post
    How should I proceed?
    If the null pointer has meaning and represents "nothing" or "empty" or something of that kind, I would use the Yoda condition. Otherwise, the null pointer is an error, and I would check for it directly.

    Tony Hoare, the inventor of the null pointer, calls it his billion-dollar mistake. The best strategy is to avoid them. You may search the internet for suggestions.

  3. #3
    Join Date
    Dec 2013
    Posts
    5

    Re: Java equals() selection

    Quote Originally Posted by Nathan D View Post
    In Java, if I try to do.equals() on a null string, a null pointer error is issued.
    Sorry for late answer but I regained the login on this forum only today.

    Yes, you get a NullPointerException. And if you want to avoid this, there are some possibilities:

    1) The classic null-safe explicit test:

    if (yourStr != null && yourStr.equals("expected"))

    2) The static equals() in java.util.Objects (JDK 7+) which is null-safe:

    if (Objects.equals(yourStr, "expected"))

    3) There is a similar static utility in notable libraries like Google Guava

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured