Please tell me how you can voice this condition if ()

if (name == null ? !name.equals(human.name) : human.name != null) return false; 

My guess is: If the name is empty, then if the name is not equal to human.name ... then the thought is lost. Otherwise, if name is not empty, then if human.name is not empty ... I don’t catch the same nonsense thought. Under which of the above and matching conditions return false ;?

  • 3
    If the name is null, then your code will be a NullPointerException , because of the name.equals - gil9red
  • gil9red and if not null, then I assume there will be another check -> if human.name = null , then there will also be an exception and it will work return false; ? - Prapor Pr

2 answers 2

The fact that in brackets:

If name == null, "! Name.equals (human.name)" is computed

If not, it computes "human.name! = Null"

Both expressions return type boolean.

Well, the expression for the brackets: if (found boolean == true) return false.

  • Maxim Stepanov and if (found boolean == false), then false will still return, i.e. anyway will return false? - Prapor Pr
  • No, if what is in parentheses is false, something that simply does not follow it. That is, the code "return false;" after brackets will not be executed. - Maxim Stepanov
  • Nothing. to return, you need to do this: if (what is in parentheses) {return false;} else {some other code, for example, "return true;"} - Maxim Stepanov
  • Understood thank) - Prapor Pr
  • But if name == null , then no "calculated !name.equals(human.name) " will not be NPE - pavlofff

In general, in such cases it is necessary to convert the code step by step:

 if (name == null ? !name.equals(human.name) : human.name != null) return false; 

Step 1: select the boolean

 boolean flag = name == null ? !name.equals(human.name) : human.name != null; if (flag) { return false; } 

Step 2: turn the operator?: Into just if

 boolean flag; if(name == null) { flag = !name.equals(human.name); // null.equals(human.name); - выкинет NullPointerException } else { flag = human.name != null; } if (flag) { return false; } 

Step 3: Considering a NullPointerException with !name.equals(human.name); The code will be equal to this:

 if(name == null) { throw new NullPointerException(); } if (human.name != null) { return false; }