2

Sometimes, or well, pretty often i need to see if a String is null or isn't, so i use a conditional like this:

if(str != null) {
}

It worked fine until this day, now even strings that are null pass for some reason which I don't get. Does anyone that knows an explanation? or a solution?

Edit: OK, so for some reason the string doesn't seem to be null, which is very odd since i never defined what it was, only denfined that it existed. So instead the string was a string of the word "null". Which i have totally no idea why it would be? When i do following:

String str;

then it's automatically null, right? And either way if it's not why would it become the string "null"?

pmr
  • 58,701
  • 10
  • 113
  • 156
Olindholm
  • 340
  • 4
  • 16
  • would you mind CTRL+A,CTRL+C your source code fragment and post it here? – aviad Jan 16 '12 at 07:44
  • Post the full source-code or stacktrace of your error. – Buhake Sindi Jan 16 '12 at 07:45
  • check for the condition `str.length();` too – Shankar Narayana Damodaran Jan 16 '12 at 07:47
  • @aviad Well I belive it would be to much for people to give a shit if i would post my complete source code. and i gave you all the information u ned, the string is null, but still passes... why? – Olindholm Jan 16 '12 at 07:51
  • 2
    @Wiggyboy - what you are saying is literally impossible. If you post the code, we can figure out why you *think* that something impossible has happened. We don't need the entire source code. Just the relevant part; i.e. the statements inside the `if` that you think mean that `str` is `null` ... and related exception traces, if relevant. – Stephen C Jan 16 '12 at 07:53
  • @wiggyboy, u right noone gives a shit about your source code only trying to help (the reason for asking appears in my answer below) – aviad Jan 16 '12 at 07:59
  • @StephenC Okey so i updated the question with further information, now maybe we could figure this out? – Olindholm Jan 16 '12 at 15:25
  • Did you see my answer below? Could the value of spell.body[cur] be "null" (the four-letter word)? Another possibility is that the output is printed from a different line than you expect, to find out you could distinguish the output with a label or even better switch to using a logging framework like Log4J instead of using System.out. A logging framework usually allows you to log the class and line number automatically. – Adriaan Koster Jan 16 '12 at 17:11
  • @AdriaanKoster Ye i did, but no that's not the problem :/ – Olindholm Jan 16 '12 at 18:34
  • Solved i guess... still don't get how, – Olindholm Jan 16 '12 at 20:18
  • So my suggestion was the correct solution! – Adriaan Koster Jan 17 '12 at 08:52
  • Yes but I don't see why it was like this, and either i don't get why it didn't work when i tried @Sean87 solution – Olindholm Jan 17 '12 at 15:29
  • Without posting more of your code, we can't determine why this happens. Just check all assignments to spell.body[] in your code. Somewhere a 'stringified' null value must be set by code like String.valueOf(yourValue) or "" + yourValue or the like. I would suggest you either provide us with enough information to help you find the cause, or accept my answer since it gave you the best clue. – Adriaan Koster Jan 18 '12 at 08:52
  • ohh don't worry i found it, it now is null, not the word anymore, it was alittle bug back in the data import, – Olindholm Jan 19 '12 at 17:00

7 Answers7

9

The explanation is that your diagnosis is incorrect. If str is null, the body of that if statement will not be executed - it's as simple as that. You haven't said anything about how you've diagnosed that str is null but that code is still being executed - if it's because you're seeing a NullPointerException, there are various reasons you might still be getting that. In particular, it could well be due to a different expression being dereferenced when null within the if block.

Alternatively, is str a non-local variable being modified by other threads, by any chance?

EDIT: Note that I've been assuming you know the difference between null and a reference to an empty string - you really are talking about the value of str being null, right? If you're talking about empty strings, that's a very different matter.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • My str string is from another class and is modified by another class but it's the same class that calls the if function as the str is located in. if that answered ur question – Olindholm Jan 16 '12 at 07:52
  • @Wiggyboy: Not really - it's still not clear whether `str` is actually a local variable or not by the time you're testing it. – Jon Skeet Jan 16 '12 at 07:54
1

I would check for length as well after checking for null:

if(stringVar == null || stringVar.length() == 0) { /* DO STUFF */ }

To make life easier you can make a extension method:

public static boolean notEmpty(String s) 
{ 
return (s != null && s.length() > 0);
}
Dumbo
  • 13,555
  • 54
  • 184
  • 288
1

Based on your null being lower case, I assume you're using java or C#.

The classiest way for an if statement to be executed when its obviously false is for you to accidentally put a semicolon on the end. Like this

if (false);
{
    System.out.println("How can this be happening!?");
}

I recommend looking very carefully at your if statements, and putting printlns in both the if and else clauses as necessary. I guarantee you, if (str != null) will definitely not run when str is null.

dhakim
  • 508
  • 3
  • 10
1

A possible cause is to leave out the curly braces altogether in a multiline conditional block:

if(str != null)
    callSomeMethod();
    System.out.println("length=" + str.length());

In this classy (and classic) example System.out.println will always be executed since it is equivalent to:

if(str != null) {
    callSomeMethod();
}
System.out.println("length=" + str.length());

--

Just thought of another possible pitfall:

if(str != null) {
    System.out.println("str=" + str);
}

If this prints:

str=null

then the value of str might be "null" (the four-character word "null").

Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
1

And either way if it's not why would it become the string "null"?

If you come across a String with the value "null" (the 4 character word, not a null reference), then you or someone has set that string to "n"-"u"-"l"-"l". It's possible you did it without meaning to. If you meant this:

str = null

You may have typed this:

str = "null"

Compile and run this test program, then take out the quotes on the str = "null" line. Compile and run again - you'll see the different behavior.

public class shortfile {
    public static void main(String[] argv) {
        String str;
        str = "null";
        if (str == null) {
            System.out.println("str is really a null reference");
        }
        else {
            int len = str.length();
            System.out.println("We set str to the literal word null");
            System.out.println("str's length is " + len);
        }
    }
}
Matt Stephenson
  • 8,442
  • 1
  • 19
  • 19
0

That's probably because of empty strings or strings with whitespace characters. Use the below code:

if(str != null && !str.trim().isEmpty()) {
}

EDIT: Sorry for misreading and submitting a fast solution, before I rushed up to work.

Maybe the null check fails because of how 'null' is interpreted by different programming languages or libraries. Below are some interesting links with good discussion:

1) Stackoverflow - What is null in Java?

2) Stackoverflow - Where is null in memory?

3) Stackoverlfow - Null \u0000 in Java String?

Community
  • 1
  • 1
bchetty
  • 2,231
  • 1
  • 19
  • 26
  • We can't be sure if this is a valid addition in the context of OP's code. – Adriaan Koster Jan 16 '12 at 08:08
  • I understand your reasoning (I replied also before going to work very fast) so altough I didn't down vote, I contribute an upvote for your answer (since it is edited!) – Dumbo Jan 16 '12 at 09:23
0

Sorry for off-topic, but I remember once I got into similar situation because of a ';' (semicolon) that sneaked into the end of the line of the if condition. It got me really crazy because no matter how I changed the condition the following block of code always executed...I found the problem after an hour when I copied and pasted the block of code into text editor.

aviad
  • 8,229
  • 9
  • 50
  • 98