0
String graphNameUsed = graphName.getName(); if (graphType.equals("All") || graphType.equals("ALL")) graphNameUsed += "_ALL"; 

If my String is null, then will it throw NullPointerException when I am checking whether it equals or not. To avoid this exception, how should I check?

2 Answers 2

4

Flip the comparisons the other way around so you're calling equals() on the string literals, which aren't null and thus won't cause the exception.

When null is passed to the equals() method, it simply returns false right away. However, if you try to call it on a variable that's null, the object isn't there for you to call that method on, which is why you get the exception.

if ("All".equals(graphType) || "ALL".equals(graphType)) 

If you just want to do case-insensitive matches, use the equalsIgnoreCase() method instead so you just perform one check:

if ("All".equalsIgnoreCase(graphType)) 
Sign up to request clarification or add additional context in comments.

3 Comments

How do u say my code can throw null pointer expection and why not this code you have written will not throw?
is there any better way to handle such expections... i mean via expection handling
@John: The solution we've provided is much better than placing a catch (NullPointerException e). Prevention is better than cure.
3

How about:

if("All".equals(graphType) || "ALL".equals(graphType)) 

And you can take advantage of short-circuiting with something like:

if(graphType != null && (graphType.equals("All") || graphType.equals("ALL"))) 

1 Comment

Note: == compares references, not values.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.