0

So I have looked in to some other threads about this issue and it seems like if I should be able to use the regular comparison operators to check this.

How to check if my string is equal to null?

Java, check whether a string is not null and not empty?

However, even if my program says that the string is null, it later contradicts this by executing an if statement with the condition that the string is not null. To make it clearer, here is my full program:

package bank;

public class HowCheckForNull {

    static void showDates(String[] dates){
        for(int i = 0; i < dates.length; i++){
            System.out.println(dates[i]);
            System.out.println(dates[i] == null);
            System.out.println(dates[i] == (String) null);
            System.out.println(dates[i] != null);
            if(dates[i] != null);{ //This should not execute!?
                System.out.print("A transaction of X$ was made on the " + dates[i] + "\n");
            }
        }
        System.out.println("");
    }

    public static void main(String args[]){
        String[] dates = new String[3];
        showDates(dates);
    }
    }

Output:

null
true
true
false
A transaction of X$ was made on the null
null
true
true
false
A transaction of X$ was made on the null
null
true
true
false
A transaction of X$ was made on the null

A couple of things baffles me here, why is the if statement executed even though the logging suggests otherwise, and how can it be that dates[i] is equal to both null and (String) null ?

2 Answers 2

11
if(dates[i] != null);
                    ^

the extra ; causes the following block to always execute (regardless of the evaluation of the if statement), since it ends the if statement. Remove it.

0
0

The problem is ';' after if(condition); that ends the statement and treats the remaining piece of code in normal manner irrespective of any condition.

Code

    package bank;

    public class HowCheckForNull {

        static void showDates(String[] dates){
            for(int i = 0; i < dates.length; i++){
                System.out.println(dates[i]);
                System.out.println(dates[i] == null);
                System.out.println(dates[i] == (String) null);
                System.out.println(dates[i] != null);
                if(dates[i] != null){ //Now it will not execute.
                    System.out.print("A transaction of X$ was made on the " + dates[i] + "\n");
                }
            }
            System.out.println("");
        }

        public static void main(String args[]){
            String[] dates = new String[3];
            showDates(dates);
        }
    }

Output

null
true
true
false
null
true
true
false
null
true
true
false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.