如何在java中根据null检查字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2920525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:30:39  来源:igfitidea点击:

How to check a string against null in java?

javastringnull

提问by user351809

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

如何在java中根据null检查字符串?我在用

stringname.equalsignorecase(null)

but it's not working.

但它不起作用。

回答by miku

s == null

won't work?

不会工作?

回答by aioobe

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

;)

;)

回答by whaley

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

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

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 knowis not a null reference, then do something like this:

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

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.

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

回答by Andreas Dolk

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

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

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

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

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

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

will definitely result in a NullPointerException.

肯定会导致 NullPointerException。

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

所以 equals 方法不是用来测试一个对象是否为空的,只是因为你不能在 上调用它们null

回答by polygenelubricants

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

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

someString.equals("null")

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

不过,这个“修复”只是隐藏了更大的问题,即首先如何null变成"null"

回答by Dean J

string == nullcompares 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.

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


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.

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

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.

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

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.

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

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.

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

回答by Timothy Perez

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.

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

回答by User_86

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

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

if(null == stringName){

  [code]

}

else

[Error Msg]

回答by Reese

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.

在这个例子中,trim 被调用在字符串上,如果字符串是空或空格,它会抛出一个 NPE,但在同一行,你可以检查空或空白,这样你就不会得到大量(更多) 如果块很难格式化。

回答by Satyendra

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

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

  1. stringnamehas 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. stringnamehas a nullvalue:
    Here your code will get stuck, as
    null.equalsignorecase(null)
    However, seems good at first look and you may hope response as true,
    but, nullis not an object that can execute the equalsignorecase()method.
  1. stringname有一个非空字符串值(比如“计算机”):
    您的代码可以正常工作,因为它采用表单
    "computer".equalsignorecase(null)
    并且您得到预期的响应为false.
  2. stringname有一个null值:
    这里你的代码会卡住,因为
    null.equalsignorecase(null)
    然而,乍一看似乎不错,你可能希望响应为true
    但是,null不是可以执行该equalsignorecase()方法的对象。

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

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