This week's book giveaway is in the Python forum.
We're giving away four copies of Python Continuous Integration and Delivery and have Moritz Lenz on-line!
See this thread for details.
Win a copy of Python Continuous Integration and Delivery this week in the Python forum!
  • 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 ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
Bartenders:
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

How can i effectively use without causing NPE?  RSS feed

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

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

NewCode:

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.


 
Bartender
Posts: 2216
47
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.
 
Can't .... do .... plaid .... So I did this tiny ad instead:
Become a Java guru with IntelliJ IDEA
https://www.jetbrains.com/idea/
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!