1
public static String firstUpper(String phrase) {
    if (phrase.isEmpty() || phrase == null) return null;

i must test this method in many cases like passing a valid parameter, an empty parameter and a NULL parameter. it passes them all except with the null parameter, it throws an exception when it should return null.

sowailam
  • 13
  • 6
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Pradeep Simha Jan 11 '17 at 11:31
  • 3
    Reverse your or (||) condition check, it would work. – Pradeep Simha Jan 11 '17 at 11:32
  • 4
    Reading up on java short circuit evaluation would probably help to understand why you have to change the order of your boolean statements: http://stackoverflow.com/questions/8759868/java-logical-operator-short-circuiting – OH GOD SPIDERS Jan 11 '17 at 11:36

2 Answers2

0

It should be:

if ( phrase == null || phrase.isEmpty() ) 
  return null;
thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23
  • The operator exhibits "short-circuiting" behavior, which means the second part is only evaluated when the first is `false`, otherwise it is not. Since `phrase` is `null` it satisfies the condition and returns without evaluating the second part of the condition. – thegauravmahawar Jan 11 '17 at 11:44
0

the problm is that when the phrase is null You are trying to call the isEmpty() method on it. Thats lead to a nullpointer Exception. Check first where the phrase is null or not. then check isEmpty() it will work.

if (phrase == null || phrase.isEmpty()) return null;
kaushik
  • 312
  • 1
  • 7