after much trial and error I've got the code to work but i don't understand why if the if statement is
if (name == null || name.isEmpty())
the code works, but if it's
if (name.isEmpty() || name == null)
or
if (name.isEmpty())
i get a nullpointerexception error
Angela York
Level 14
can anyone tell me why?
Resolved
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Usha Mathivanan
4 May 2020, 09:11
- "name == null" : Checks the "name" variable is pointing to null. But,
- "name.isEmpty()" : Checks the "name" variable's "value" is empty or not.
- So, here we go :
If you enter an empty line like below in your input:
------ex 1-----
Tommy
2
3
4
(empty line)
(cursor is now in this line)
- Now, "name" variable has a value of the empty string, thus "name.isEmpty()" will work ( because it checks the value of "name" variable which is an empty string)
- But "name == null" will NOT work because it checks if "name" is pointing to a null variable which is obviously false (because "name" contains an empty string and not null).
- if (name == null || name.isEmpty()) throws an error bcz, the first condition doesn't work
- if (name.isEmpty() || name == null) works fine bcz, first condition is satisfied
------ex 2-----
Tommy
2
3
4
(cursor is now in this line)
- In the above example, there is no empty space left after "4". So here, "name" variable has "no value".
- Now, "name.isEmpty()" checks for the value of the variable "name".
- Variable "name" first of all doesn't have a "value", and thus "name" is pointing to a "null variable", So it throws an error of "nullPointer Exception"
- But "name == null" will work because it checks if "name" is pointing to the null variable which is obviously true.
- if (name == null || name.isEmpty()) works fine bcz, first condition is satisfied.
- if (name.isEmpty() || name == null) throws an error bcz, first condition doesn't work.
+1
Gil Allen
10 August 2020, 21:47
Hi, i understand what you are saying, but I think the crux of the matter is how do you know how your input is going to end? whether it has blank lines or not even a carriage return at the end. So if you put if (name.isEmpty() || name == null) or vice versa, you will get exception depending on the input you're receiveing?? Can you 'splain a little bit more, including handling different inputs. Thanks
0
rydenfoo
6 December 2019, 21:23solution
Hey!
If a string is null, then isEmpty() will throw a NullPointerException. However, you are evaluating your expression in different ways. Now, if the left side of the expression (bool || bool_2) is true, then the right side will not be evaluated. So if your string is null, the first expression works fine because "name.isEmpty()" will not be evaluated.
In the remaining two options, it will, and it throws a NullPointerException.
Best wishes :)
+2
Jay
14 November 2019, 14:48
@Angela, You need to raise a question with your task code included with it for any help..
0