-2

I am able to handle null check on a String with this below piece of code

 if (acct != null && !acct.isEmpty()|| !acct.equals(""))

what i mean from the above code is , if

  1. Accountid is not equal to null And
  2. Accountid length is greater than 0 (These two is a combination of checks )

Or

  1. Accountid is not equal to ""

Does my code satisfy these combination i mentioned above , or do i need to add any brackets ?? to satisfy the combination ( first 1 and 2 ) i mentioned above ??

Thanks

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440

3 Answers3

2

Yes it does, and is always evaluated before or, i.e. your code is the same as

if ((acct != null && !acct.isEmpty()) || !acct.equals(""))

However, logically it does not make sense to me. Do you really need the last part? Isn't "acct.isEmpty()" the same as "acct.equals(""))" in this specific instance?

Jaco Van Niekerk
  • 4,180
  • 2
  • 21
  • 48
2

isEmpty() and .equals("") are exactly the same condition. And your test will throw a NullPointerException if acct is null.

I don't understand exactly which test you want to make, but this one is wrong. Think about it once again, and implement a unit test to test all the cases:

  • null string,
  • empty string,
  • not empty string.
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

As per your question framed by you, it should have brackets as below

if ((acct != null && !acct.isEmpty()) || !("".equals(acct) )) 

After the || operator, the code is changed which will avoid facing NullPointerException when acct is NULL.

This SO answer explains more about using "".equals().

https://stackoverflow.com/a/3321548/713414

Community
  • 1
  • 1
Jayy
  • 2,368
  • 4
  • 24
  • 35
  • I kind of know what you're saying but as others have pointed out, this will still cause a NullPointerException. The bracketing means the test on the other side of the '||' will be executed whether 'acct!=null' or not. – wmorrison365 Jan 23 '12 at 12:16