• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

How can i effectively use without causing NPE?  RSS feed

Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Existing code:

if (messsage !="" && messsage !=null && (err=="" || err==null)){


if (messsage !="" && messsage !=null && (err.equals("") || err.equals(null))){

If i modify the code as above , will there be an issue? i am doing it to prevent security exceptions of '==' operator.

Posts: 2203
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wecome to the Ranch!

What security exception are there with == operator?

You shouldn't use == to compare strings.

You coud use a 'reversed' notation to avoid NPE, like: if(!"".equals(message)). I'll let you decide if it looks readable enough.

Writing err.equals("") || err.equals(null) won't guard you against a NPE.
First, you should always check for null first. If err is null then err.equals("") will throw a NPE.
Second, err.equals(null) is an incorrect way to do a null check. It will throw NPE if err is null. Also, a properly designed equals method (String class has one) will never return true for null argument. For a null check you have to use the == operator.
Watchya got in that poodle gun? Anything for me? Or this tiny ad?
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!