java中如何检查字符串是否为空?

发布于 2024-09-03 00:50:56 字数 107 浏览 5 评论 0原文

如何在java中检查字符串是否为空?我正在使用,

stringname.equalsignorecase(null)

但它不起作用。

How can I check a string against null in java? I am using

stringname.equalsignorecase(null)

but it's not working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

新一帅帅 2024-09-10 00:50:56

string == null 比较对象是否为 null。 string.equals("foo") 比较该对象内部的值。 string == "foo" 并不总是有效,因为您试图查看对象是否相同,而不是它们代表的值。

更长的答案:

如果你尝试这个,它不会工作,正如你所发现的:

String foo = null;
if (foo.equals(null)) {
    // That fails every time. 
}

原因是 foo 为空,所以它不知道 .equals 是什么;那里没有可以调用 .equals 的对象。

您可能想要的是:

String foo = null;
if (foo == null) {
    // That will work.
}

在处理字符串时防止出现 null 的典型方法是:

String foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
    // Do something here.
}

这样,如果 foo 为 null,则它不会评估条件的后半部分,并且一切正常。

如果您使用字符串文字(而不是变量),最简单的方法是:

String foo = null;
...
if ("some String".equals(foo)) {
    // Do something here.
}

如果您想解决这个问题,Apache Commons 有一个类 - StringUtils - 提供空安全字符串操作。

if (StringUtils.equals(foo, bar)) {
    // Do something here.
}

另一个回应是开玩笑,并说你应该这样做:

boolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

请不要这样做。您应该只针对异常错误抛出异常;如果你期望一个空值,你应该提前检查它,不要让它抛出异常。

在我看来,这有两个原因。首先,异常处理速度很慢;检查 null 很快,但是当 JVM 抛出异常时,需要花费很多时间。其次,如果您只是提前检查空指针,则代码更容易阅读和维护。

string == null compares if the object is null. string.equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.

Longer answer:

If you try this, it won't work, as you've found:

String foo = null;
if (foo.equals(null)) {
    // That fails every time. 
}

The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.

What you probably wanted was:

String foo = null;
if (foo == null) {
    // That will work.
}

The typical way to guard yourself against a null when dealing with Strings is:

String foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
    // Do something here.
}

That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.

The easy way, if you're using a String literal (instead of a variable), is:

String foo = null;
...
if ("some String".equals(foo)) {
    // Do something here.
}

If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.

if (StringUtils.equals(foo, bar)) {
    // Do something here.
}

Another response was joking, and said you should do this:

boolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.

In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.

心作怪 2024-09-10 00:50:56
s == null

行不通?

s == null

won't work?

像极了他 2024-09-10 00:50:56

当然有效。您错过了代码的重要部分。你只需要这样做:

boolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

;)

Sure it works. You're missing out a vital part of the code. You just need to do like this:

boolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

;)

嘿看小鸭子会跑 2024-09-10 00:50:56

如果您在 Android 中工作,请使用 TextUtils 方法。

TextUtils.isEmpty(str):如果字符串为空或长度为 0,则返回 true。
参数:
str 要检查的字符串
返回:
如果 str 为 null 或零长度,则为 true

  if(TextUtils.isEmpty(str)) {
        // str is null or lenght is 0
    }

下面是 该方法的源代码。您可以直接使用。

 /**
     * Returns true if the string is null or 0-length.
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
    public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;
    }

Use TextUtils Method if u working in Android.

TextUtils.isEmpty(str) : Returns true if the string is null or 0-length.
Parameters:
str the string to be examined
Returns:
true if str is null or zero length

  if(TextUtils.isEmpty(str)) {
        // str is null or lenght is 0
    }

Below is source code of this method.You can use direclty.

 /**
     * Returns true if the string is null or 0-length.
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
    public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;
    }
美男兮 2024-09-10 00:50:56

如果我们查看 equalsIgnoreCase 方法的实现,我们会发现这部分:

if (string == null || count != string.count) {
    return false;
}

因此,如果参数为 null,它将始终返回 false。这显然是正确的,因为它应该返回 true 的唯一情况是在 null String 上调用 equalsIgnoreCase 时,但

String nullString = null;
nullString.equalsIgnoreCase(null);

肯定会导致 NullPointerException。

因此 equals 方法并不是为了测试对象是否为 null 而设计的,只是因为您无法在 null 上调用它们。

If we look at the implementation of the equalsIgnoreCase method, we find this part:

if (string == null || count != string.count) {
    return false;
}

So it will always return false if the argument is null. And this is obviously right, because the only case where it should return true is when equalsIgnoreCase was invoked on a null String, but

String nullString = null;
nullString.equalsIgnoreCase(null);

will definitely result in a NullPointerException.

So equals methods are not designed to test whether an object is null, just because you can't invoke them on null.

最近可好 2024-09-10 00:50:56

这看起来有点奇怪,但是......

stringName == null || "".equals(stringName)

这样做从来没有任何问题,而且这是一种更安全的检查方法,同时避免潜在的空点异常。

This looks a bit strange, but...

stringName == null || "".equals(stringName)

Never had any issues doing it this way, plus it's a safer way to check while avoiding potential null point exceptions.

盗琴音 2024-09-10 00:50:56

我不确定 MYYN 的回答有什么问题。

if (yourString != null) {
  //do fun stuff with yourString here
}

上面的空检查是完全没问题的。

如果您尝试检查 String 引用是否与您知道不是空引用的另一个字符串相等(忽略大小写),请执行以下操作:

String x = "this is not a null reference"
if (x.equalsIgnoreCase(yourStringReferenceThatMightBeNull) ) {
  //do fun stuff
}

如果对是否或存在任何疑问不是您正在比较的两个字符串都有空引用,您需要检查至少其中一个字符串是否有空引用,以避免出现 NullPointerException 的可能性。

I'm not sure what was wrong with The MYYN's answer.

if (yourString != null) {
  //do fun stuff with yourString here
}

The above null check is quite alright.

If you are trying to check if a String reference is equal (ignoring case) to another string that you know is not a null reference, then do something like this:

String x = "this is not a null reference"
if (x.equalsIgnoreCase(yourStringReferenceThatMightBeNull) ) {
  //do fun stuff
}

If there is any doubt as to whether or not you have null references for both Strings you are comparing, you'll need to check for a null reference on at least one of them to avoid the possibility of a NullPointerException.

傾城如夢未必闌珊 2024-09-10 00:50:56

如果您的字符串具有“null”值,那么您可以使用

if(null == stringName){

  [code]

}

else

[Error Msg]

If your string having "null" value then you can use

if(null == stringName){

  [code]

}

else

[Error Msg]
时光与爱终年不遇 2024-09-10 00:50:56

将其导入到您的类中

import org.apache.commons.lang.StringUtils;

然后使用它,它们都会返回 true

System.out.println(StringUtils.isEmpty(""));
System.out.println(StringUtils.isEmpty(null)); 

import it in your class

import org.apache.commons.lang.StringUtils;

then use it, they both will return true

System.out.println(StringUtils.isEmpty(""));
System.out.println(StringUtils.isEmpty(null)); 
书信已泛黄 2024-09-10 00:50:56

您可以检查 String == null

这对我有用

    String foo = null;
    if(foo == null){
        System.out.println("String is null");
    }

You can check with String == null

This works for me

    String foo = null;
    if(foo == null){
        System.out.println("String is null");
    }
北方。的韩爷 2024-09-10 00:50:56

简单方法:

public static boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}

Simple method:

public static boolean isBlank(String value) {
    return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
抠脚大汉 2024-09-10 00:50:56

当然user351809,stringname.equalsignorecase(null)会抛出NullPointerException。
看,您有一个字符串对象 stringname,它遵循 2 个可能的条件:-

  1. stringname 有一个非空字符串值(例如“computer”):
    您的代码将正常工作,因为它采用以下形式
    "computer".equalsignorecase(null)
    您会得到预期的响应 false
  2. stringname 具有 null 值:
    在这里你的代码将被卡住,如
    null.equalsignorecase(null)
    然而,乍一看似乎不错,您可能希望响应为 true
    但是,null 不是可以执行 equalsignorecase() 方法的对象。

因此,您会因情况 2 而得到异常。
我建议你简单地使用 stringname == null

Of course user351809, stringname.equalsignorecase(null) will throw NullPointerException.
See, you have a string object stringname, which follows 2 possible conditions:-

  1. stringname has a some non-null string value (say "computer"):
    Your code will work fine as it takes the form
    "computer".equalsignorecase(null)
    and you get the expected response as false.
  2. stringname has a null value:
    Here your code will get stuck, as
    null.equalsignorecase(null)
    However, seems good at first look and you may hope response as true,
    but, null is not an object that can execute the equalsignorecase() method.

Hence, you get the exception due to case 2.
What I suggest you is to simply use stringname == null

不知所踪 2024-09-10 00:50:56

在 Java 7 中,如果两个参数都为 null,则可以使用

if (Objects.equals(foo, null)) {
    ...
}

它将返回 true

With Java 7 you can use

if (Objects.equals(foo, null)) {
    ...
}

which will return true if both parameters are null.

诠释孤独 2024-09-10 00:50:56

如果我理解正确的话,应该这样做:

if(!stringname.isEmpty())
// an if to check if stringname is not null
if(stringname.isEmpty())
// an if to check if stringname is null

If I understand correctly, this should do it:

if(!stringname.isEmpty())
// an if to check if stringname is not null
if(stringname.isEmpty())
// an if to check if stringname is null
椒妓 2024-09-10 00:50:56

我意识到这个问题很久以前就得到了回答,但我还没有看到这篇文章,所以我想我应该分享我所做的事情。这对于代码可读性来说并不是特别好,但是如果您必须执行一系列 null 检查,我喜欢使用:

String someString = someObject.getProperty() == null ? "" : someObject.getProperty().trim();

在本示例中,对字符串调用 trim,如果字符串为 null,则会抛出 NPE或空格,但在同一行上,您可以检查 null 或空白,这样您就不会得到大量(更)难以格式化的 if 块。

I realize this was answered a long time ago, but I haven't seen this posted, so I thought I'd share what I do. This isn't particularly good for code readability, but if you're having to do a series of null checks, I like to use:

String someString = someObject.getProperty() == null ? "" : someObject.getProperty().trim();

In this example, trim is called on the string, which would throw an NPE if the string was null or spaces, but on the same line, you can check for null or blank so you don't end up with a ton of (more) difficult to format if blocks.

相守太难 2024-09-10 00:50:56

如果返回的value为null,请使用:

if(value.isEmpty());

有时检查null,java中的if(value == null),即使String为null也可能不会给出true。

If the value returned is null, use:

if(value.isEmpty());

Sometime to check null, if(value == null) in java, it might not give true even the String is null.

青芜 2024-09-10 00:50:56

Apache StringUtils 类将为您做这件事。
StringUtils.equals(col1, col2)
当 col1、col2 或两者都为空时,可以正常工作。

考虑阅读整个 StringUtils JavaDoc 页面。
它已经解决了大部分(如果不是全部)字符串操作和/或比较
你会遇到的问题。

The Apache StringUtils class will do this for you.
StringUtils.equals(col1, col2)
works correctly when col1, col2, or both are null.

Consider reading the entire StringUtils JavaDoc page.
It has solved most if not all of the String manipulation and/or comparison
problems you will encounter.

离去的眼神 2024-09-10 00:50:56

如果对 null 字符串使用 equalsIgnoreCase,它将抛出 NullPointerException

因此,你可以使用这个:

    String one = null;
    String other = "ntg";
    try {
        one.equalsIgnoreCase(other);
    } catch (NullPointerException e) {
        System.out.println("The first string is null.");
    }

但我建议使用String == null

If you use equalsIgnoreCase for a null String, it will throw NullPointerException.

Therefore, you can use this:

    String one = null;
    String other = "ntg";
    try {
        one.equalsIgnoreCase(other);
    } catch (NullPointerException e) {
        System.out.println("The first string is null.");
    }

but I recommend using String == null.

情绪 2024-09-10 00:50:56

好吧,上次有人问这个愚蠢的问题时,答案是:

someString.equals("null")

这个“修复”只是隐藏了更大的问题,即 null 如何变成 “null”,尽管。

Well, the last time someone asked this silly question, the answer was:

someString.equals("null")

This "fix" only hides the bigger problem of how null becomes "null" in the first place, though.

输什么也不输骨气 2024-09-10 00:50:56

有两种方法可以做到这一点..说 String==nullstring.equals()..

public class IfElse {

    public int ifElseTesting(String a){
        //return null;
        return (a== null)? 0: a.length();
    }

}

public class ShortCutifElseTesting {

    public static void main(String[] args) {

        Scanner scanner=new Scanner(System.in);
        System.out.println("enter the string please:");
        String a=scanner.nextLine();
        /*
        if (a.equals(null)){
            System.out.println("you are not correct");
        }
        else if(a.equals("bangladesh")){
            System.out.println("you are right");
        }
        else
            System.out.println("succesful tested");

        */
        IfElse ie=new IfElse();
        int result=ie.ifElseTesting(a);
        System.out.println(result);

    }

}

检查这个示例..这是另一个快捷版本的示例如果不然..

There are two ways to do it..Say String==null or string.equals()..

public class IfElse {

    public int ifElseTesting(String a){
        //return null;
        return (a== null)? 0: a.length();
    }

}

public class ShortCutifElseTesting {

    public static void main(String[] args) {

        Scanner scanner=new Scanner(System.in);
        System.out.println("enter the string please:");
        String a=scanner.nextLine();
        /*
        if (a.equals(null)){
            System.out.println("you are not correct");
        }
        else if(a.equals("bangladesh")){
            System.out.println("you are right");
        }
        else
            System.out.println("succesful tested");

        */
        IfElse ie=new IfElse();
        int result=ie.ifElseTesting(a);
        System.out.println(result);

    }

}

Check this example..Here is an another example of shortcut version of If Else..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文