检查String数组元素是否为null

时间:2015-05-27 08:49:46

标签: java arrays string null

所以我已经查看了一些关于这个问题的其他线程,似乎我应该能够使用常规比较运算符来检查这个。

How to check if my string is equal to null?

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

但是,即使我的程序声明字符串为null,它也会通过执行if语句与字符串不为空的条件来解决这个问题。为了更清楚,这是我的完整计划:

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);
    }
    }

输出:

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

有些事情让我感到困惑,为什么if语句已执行,即使日志记录另有说明,dates[i]如何等同于null和{ {1}}?

2 个答案:

答案 0 :(得分:10)

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

额外的;导致以下块始终执行(无论if语句的评估如何),因为它结束if语句。删除它。

答案 1 :(得分:0)

问题是&#39;;&#39;在if(condition);之后结束陈述并以正常方式处理剩余的代码而不管任何条件。

代码

    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);
        }
    }

输出

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