如何检查我的字符串是否等于null?

时间:2021-10-15 22:25:03

I want to perform some action ONLY IF my string has a meaningful value. So, I tried this.

我只想在我的字符串有一个有意义的值时执行一些操作。所以,我试着这一点。

if (!myString.equals("")) {
doSomething
}

and this

if (!myString.equals(null)) {
doSomething
}

and this

if ( (!myString.equals("")) && (!myString.equals(null))) {
doSomething
}

and this

if ( (!myString.equals("")) && (myString!=null)) {
doSomething
}

and this

if ( myString.length()>0) {
doSomething
}

And in all cases my program doSomething in spite on the fact that my string IS EMPTY. It equals to null. So, what is wrong with that?

在所有情况下,我的程序都在做,尽管我的字符串是空的。它等于零。那么,这有什么错呢?

ADDED:

补充道:

I found the reason of the problem. The variable was declared as a string and, as a consequence, null assigned to this variable was transformed to "null"! So, if (!myString.equals("null")) works.

我找到了问题的原因。变量被声明为一个字符串,因此,将该变量赋值为“null”!所以,如果(! myString.equals(“空”))。

25 个解决方案

#1


197  

if (myString != null && !myString.isEmpty()) {
  // doSomething
}

As further comment, you should be aware of this term in the equals contract:

作为进一步的评论,你应该意识到这一术语在等于合同中:

From Object.equals(Object):

从Object.equals(对象):

For any non-null reference value x, x.equals(null) should return false.

对于任何非空引用值x, x.equals(null)应该返回false。

The way to compare with null is to use x == null and x != null.

与null比较的方法是使用x == null和x != null。

Moreover, x.field and x.method() throws NullPointerException if x == null.

此外,x。字段和x.method()在x == null时抛出NullPointerException。

#2


24  

If myString is null, then calling myString.equals(null) or myString.equals("") will fail with a NullPointerException. You cannot call any instance methods on a null variable.

如果myString是空的,那么调用myString.equals(null)或myString.equals(“”)将以NullPointerException失败。不能在空变量上调用任何实例方法。

Check for null first like this:

像这样检查null:

if (myString != null && !myString.equals("")) {
    //do something
}

This makes use of short-circuit evaluation to not attempt the .equals if myString fails the null check.

如果myString失败,则使用短路评估来不尝试。

#3


15  

Apache commons StringUtils.isNotEmpty is the best way to go.

Apache commons stringutil的。这是最好的方法。

#4


10  

If myString is in fact null, then any call to the reference will fail with a Null Pointer Exception (NPE). Since java 6, use #isEmpty instead of length check (in any case NEVER create a new empty String with the check).

如果myString实际上是空的,那么任何对引用的调用都将失败,只有一个空指针异常(NPE)。由于java 6,使用#isEmpty而不是长度检查(在任何情况下都不要用check创建一个新的空字符串)。

if (myString !=null &&  !myString.isEmpty()){
    doSomething();
}

Incidentally if comparing with String literals as you do, would reverse the statement so as not to have to have a null check, i.e,

顺便说一下,如果与字符串字面量比较,将会颠倒语句,这样就不必进行空检查,也就是说,

if (("some string to check").equals(myString)){
  doSomething();
} 

instead of :

而不是:

if (myString !=null &&  !myString.equals("some string to check")){
    doSomething();
}

#5


5  

If your string is null, calls like this should throw a NullReferenceException:

如果字符串为空,那么这样的调用应该抛出一个NullReferenceException:

myString.equals(null)

myString.equals(空)

But anyway, I think a method like this is what you want:

但无论如何,我认为这样的方法是你想要的:

public static class StringUtils
{
    public static bool isNullOrEmpty(String myString)
    {
         return myString == null || "".equals(myString);
    }
}

Then in your code, you can do things like this:

在你的代码中,你可以这样做:

if (!StringUtils.isNullOrEmpty(myString))
{
    doSomething();
}

#6


5  

You need to check that the myString object is null:

您需要检查myString对象是否为空:

if (myString != null) {
    doSomething
}

#7


4  

Try,

试,

myString!=null && myString.length()>0

#8


4  

 if (myString != null && myString.length() > 0) {

        // your magic here

 }

Incidently, if you are doing much string manipulation, there's a great Spring class with all sorts of useful methods:

如果你做了大量的字符串操作,那么有一个很棒的Spring类,它有各种各样有用的方法:

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html

#9


4  

I would encourage using an existing utility, or creating your own method:

我鼓励使用现有的实用工具,或者创建自己的方法:

public static boolean isEmpty(String string) {
    return string == null || string.length() == 0;
}

Then just use it when you need it:

那么当你需要的时候就用它:

if (! StringUtils.isEmpty(string)) {
  // do something
}

As noted above, the || and && operators short circuit. That means as soon as they can determine their value they stop. So if (string == null) is true, the length part does not need to be evaluated, as the expression would always be true. Likewise with &&, where if the left side is false, the expression is always false and need not be evaluated further.

如上所述,||和&&操作符短路。这意味着一旦他们能够确定他们的价值,他们就会停止。因此,如果(string == null)是正确的,那么长度部分不需要被计算,因为表达式总是正确的。同样的,如果左边是假的,表达式总是错误的,不需要进一步评估。

As an additional note, using length is generally a better idea than using .equals. The performance is slightly better (not much), and doesn't require object creation (though most compilers might optimize this out).

另外,使用长度通常比使用.equals更好。性能稍微好一点(不是很多),不需要对象创建(尽管大多数编译器可能会优化这个)。

#10


4  

Every time i have to deal with strings (almost every time) I stop and wonder which way is really the fastest way to check for an empty string. Of course the string.Length == 0 check should be the fastest since Length is a property and there shouldn't be any processing other than retrieving the value of the property. But then I ask myself, why is there a String.Empty? It should be faster to check for String.Empty than for length, I tell myself. Well i finnaly decided to test it out. I coded a small Windows Console app that tells me how long it takes to do a certain check for 10 million repitions. I checked 3 different strings: a NULL string, an Empty string, and a "" string. I used 5 different methods: String.IsNullOrEmpty(), str == null, str == null || str == String.Empty, str == null || str == "", str == null || str.length == 0. Below are the results:

每当我要处理字符串(几乎每次)时,我都会停下来,想知道哪种方法是检查空字符串的最快方法。当然,字符串。Length == 0检查应该是最快的,因为长度是一个属性,除了检索属性值之外,不应该有任何处理。然后我问自己,为什么会有一个字符串,空的?应该更快地检查字符串。我对自己说,空比长。我决定试一试。我编写了一个小的Windows控制台应用程序,它告诉我要花多长时间才能完成1000万次的检查。我检查了3个不同的字符串:空字符串、空字符串和“”字符串。我使用了5种不同的方法:String. isnullorempty (), str == null, str == null || str == String。空的,str == null || ||。下面的结果:

String.IsNullOrEmpty()
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds

str == null
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds

str == null || str == String.Empty
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds

str == null || str == ""
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds

str == null || str.length == 0
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds

According to these results, on average checking for str == null is the fastest, but might not always yield what we're looking for. if str = String.Empty or str = "", it results in false. Then you have 2 that are tied in second place: String.IsNullOrEmpty() and str == null || str.length == 0. Since String.IsNullOrEmpty() looks nicer and is easier (and faster) to write I would recommend using it over the other solution.

根据这些结果,对str == null的平均检查是最快的,但可能不会总是产生我们正在寻找的东西。如果字符串str =。空或str = "",结果为false。然后有两个并列在第二的位置:String.IsNullOrEmpty()和str == null || .length == 0。因为String.IsNullOrEmpty()看起来更好,而且更容易(而且更快),所以我建议在其他解决方案中使用它。

#11


4  

WORKING !!!!

工作! ! ! !

if (myString != null && !myString.isEmpty()) {
        return true;
}
else{
        return false;
}

#12


3  

I'd do something like this:

我会做这样的事情:

( myString != null && myString.length() > 0 )
    ? doSomething() : System.out.println("Non valid String");
  • Testing for null checks whether myString contains an instance of String.
  • 测试null检查myString是否包含字符串实例。
  • length() returns the length and is equivalent to equals("").
  • length()返回长度,相当于等于(“”)。
  • Checking if myString is null first will avoid a NullPointerException.
  • 检查myString是否为空首先将避免NullPointerException。

#13


3  

I been using StringUtil.isBlank(string)

我使用StringUtil.isBlank(字符串)

It tests if a string is blank: null, emtpy, or only whitespace.

它测试字符串是否为空:null、emtpy或只有空格。

So this one is the best so far

这是迄今为止最好的。

Here is the orignal method from the docs

这是来自文档的orignal方法。

/**
    * Tests if a string is blank: null, emtpy, or only whitespace (" ", \r\n, \t, etc)
    * @param string string to test
    * @return if string is blank
    */
    public static boolean isBlank(String string) {
        if (string == null || string.length() == 0)
            return true;

        int l = string.length();
        for (int i = 0; i < l; i++) {
            if (!StringUtil.isWhitespace(string.codePointAt(i)))
                return false;
        }
        return true;
    } 

#14


2  

This should work:

这应该工作:

if (myString != null && !myString.equals(""))
    doSomething
}

If not, then myString likely has a value that you are not expecting. Try printing it out like this:

如果没有,那么myString可能具有您不期望的值。试着这样打印:

System.out.println("+" + myString + "+");

Using the '+' symbols to surround the string will show you if there is extra whitespace in there that you're not accounting for.

使用“+”符号包围字符串将显示,如果有额外的空白,您没有考虑。

#15


2  

if(str.isEmpty() || str==null){ do whatever you want }

if(string . isempty () || | str==null){做你想做的任何事}

#16


1  

I had this problem in android and i use this way (Work for me):

我在android上有这个问题,我用这个方法(为我工作):

String test = null;
if(test == "null"){
// Do work
}

But in java code I use :

但在java代码中,我使用:

String test = null;
if(test == null){
// Do work
}

And :

和:

private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
    String strDate0 = BeanUtils.getProperty(arg0, strProperty);_logger.debug("strDate0 = " + strDate0);
    String strDate1 = BeanUtils.getProperty(arg1, strProperty);_logger.debug("strDate1 = " + strDate1);
    return compareDateStrings(strDate0, strDate1);
}

private Integer compareDateStrings(String strDate0, String strDate1) {
    int cmp = 0;
    if (isEmpty(strDate0)) {
        if (isNotEmpty(strDate1)) {
            cmp = -1;
        } else {
            cmp = 0;
        }
    } else if (isEmpty(strDate1)) {
        cmp = 1;
    } else {
        cmp = strDate0.compareTo(strDate1);
    }
    return cmp;
}

private boolean isEmpty(String str) {
    return str == null || str.isEmpty();
}
private boolean isNotEmpty(String str) {
    return !isEmpty(str);
}

#17


1  

I prefer to use:

我更喜欢使用:

if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
    // do something
}

Read StringUtils.isBlank() vs String.isEmpty().

读StringUtils.isBlank vs String.isEmpty()()。

#18


1  

In Android you can check this with utility method isEmpty from TextUtils,

在安卓系统中,你可以用效用方法从TextUtils检测到这个,

public static boolean isEmpty(CharSequence str) {
    return str == null || str.length() == 0;
}

isEmpty(CharSequence str) method check both condition, for null and length.

isEmpty(CharSequence str)方法检查这两个条件,为null和长度。

#19


1  

Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab. You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists. For example, there are all numbers, char, boolean etc. The normal data types or complex data types is everything else. A String is an array of chars, therefore a complex data type.

这就是数据类型在Java中的作用。(你得原谅我的英语,我是prob。不使用正确的vocab。你必须区分它们中的两个。基本数据类型和正常数据类型。基本数据类型几乎构成了所有存在的东西。例如,所有的数字、char、boolean等都是正常的数据类型或复杂的数据类型。字符串是chars的数组,因此是一个复杂的数据类型。

Every variable that you create is actually a pointer on the value in your memory. For example:

您创建的每个变量实际上都是一个指向内存中值的指针。例如:

String s = new String("This is just a test");

the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory. When you call System.out.println(anyObject), the toString() method of that object is called. If it did not override toString from Object, it will print the pointer. For example:

变量“s”不包含字符串。这是一个指针。这个指针指向内存中的变量。当您调用System.out.println(anyObject)时,该对象的toString()方法被调用。如果它没有从对象覆盖toString,它将打印指针。例如:

public class Foo{
    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(f);
    }
}

>>>>
>>>>
>>>>Foo@330bedb4

Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.

“@”后面的一切都是指针。这只适用于复杂的数据类型。原始数据类型直接保存在它们的指针中。所以实际上没有指针,值是直接存储的。

For example:

例如:

int i = 123;

i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).

在这种情况下,我不存储指针。我将存储整数值123(在字节ofc中)。

Okay so lets come back to the == operator. It always compares the pointer and not the content saved at the pointer's position in the memory.

好,我们回到==运算符。它总是比较指针,而不是保存在内存中指针位置的内容。

Example:

例子:

String s1 = new String("Hallo");
String s2 = new String("Hallo");

System.out.println(s1 == s2);

>>>>> false

This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.

这两个字符串都有不同的指针。字符串。而equals(String other)则对内容进行比较。您可以将原始数据类型与“==”操作符进行比较,因为具有相同内容的两个不同对象的指针是相同的。

Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.

Null意味着指针是空的。默认情况下,一个空的原始数据类型为0(用于数字)。对于任何复杂对象来说,Null是不存在的。

Greetings

问候

#20


1  

For me the best check if a string has any meaningful content in Java is this one:

对于我来说,如果字符串在Java中有任何有意义的内容,最好的检查就是这个:

string != null && !string.trim().isEmpty()

First you check if the string is null to avoid NullPointerException and then you trim all space characters to avoid checking strings that only have whitespaces and finally you check if the trimmed string is not empty, i.e has length 0.

首先检查字符串是否为空,以避免NullPointerException,然后删除所有空格字符,以避免检查只具有whitespaces的字符串,最后检查修剪后的字符串是否为空。e长度为0。

#21


0  

I think that myString is not a string but an array of strings. Here is what you need to do:

我认为myString不是字符串而是字符串数组。以下是你需要做的:

String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
    //Do something
}

#22


0  

You can check string equal to null using this:

你可以用这个来检查字符串是否等于null:

String Test = null;
(Test+"").compareTo("null")

If the result is 0 then (Test+"") = "null".

如果结果是0,那么(Test+") = "null"。

#23


0  

I tried most of the examples given above for a null in an android app l was building and IT ALL FAILED. So l came up with a solution that worked anytime for me.

我尝试了上面给出的大多数例子,在android应用程序l上的一个空值,都失败了。所以我想出了一个可以随时为我工作的解决方案。

String test = null+"";
If(!test.equals("null"){
       //go ahead string is not null

}

So simply concatenate an empty string as l did above and test against "null" and it works fine. In fact no exception is thrown

所以简单地连接一个空字符串,就像我在上面做的那样,并对“null”进行测试,它可以正常工作。事实上,也没有抛出异常。

#24


0  

Exception may also help:

异常也可以帮助:

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}

#25


-5  

You have to check with null if(str != null).

如果(str != null),则必须检查null。

#1


197  

if (myString != null && !myString.isEmpty()) {
  // doSomething
}

As further comment, you should be aware of this term in the equals contract:

作为进一步的评论,你应该意识到这一术语在等于合同中:

From Object.equals(Object):

从Object.equals(对象):

For any non-null reference value x, x.equals(null) should return false.

对于任何非空引用值x, x.equals(null)应该返回false。

The way to compare with null is to use x == null and x != null.

与null比较的方法是使用x == null和x != null。

Moreover, x.field and x.method() throws NullPointerException if x == null.

此外,x。字段和x.method()在x == null时抛出NullPointerException。

#2


24  

If myString is null, then calling myString.equals(null) or myString.equals("") will fail with a NullPointerException. You cannot call any instance methods on a null variable.

如果myString是空的,那么调用myString.equals(null)或myString.equals(“”)将以NullPointerException失败。不能在空变量上调用任何实例方法。

Check for null first like this:

像这样检查null:

if (myString != null && !myString.equals("")) {
    //do something
}

This makes use of short-circuit evaluation to not attempt the .equals if myString fails the null check.

如果myString失败,则使用短路评估来不尝试。

#3


15  

Apache commons StringUtils.isNotEmpty is the best way to go.

Apache commons stringutil的。这是最好的方法。

#4


10  

If myString is in fact null, then any call to the reference will fail with a Null Pointer Exception (NPE). Since java 6, use #isEmpty instead of length check (in any case NEVER create a new empty String with the check).

如果myString实际上是空的,那么任何对引用的调用都将失败,只有一个空指针异常(NPE)。由于java 6,使用#isEmpty而不是长度检查(在任何情况下都不要用check创建一个新的空字符串)。

if (myString !=null &&  !myString.isEmpty()){
    doSomething();
}

Incidentally if comparing with String literals as you do, would reverse the statement so as not to have to have a null check, i.e,

顺便说一下,如果与字符串字面量比较,将会颠倒语句,这样就不必进行空检查,也就是说,

if (("some string to check").equals(myString)){
  doSomething();
} 

instead of :

而不是:

if (myString !=null &&  !myString.equals("some string to check")){
    doSomething();
}

#5


5  

If your string is null, calls like this should throw a NullReferenceException:

如果字符串为空,那么这样的调用应该抛出一个NullReferenceException:

myString.equals(null)

myString.equals(空)

But anyway, I think a method like this is what you want:

但无论如何,我认为这样的方法是你想要的:

public static class StringUtils
{
    public static bool isNullOrEmpty(String myString)
    {
         return myString == null || "".equals(myString);
    }
}

Then in your code, you can do things like this:

在你的代码中,你可以这样做:

if (!StringUtils.isNullOrEmpty(myString))
{
    doSomething();
}

#6


5  

You need to check that the myString object is null:

您需要检查myString对象是否为空:

if (myString != null) {
    doSomething
}

#7


4  

Try,

试,

myString!=null && myString.length()>0

#8


4  

 if (myString != null && myString.length() > 0) {

        // your magic here

 }

Incidently, if you are doing much string manipulation, there's a great Spring class with all sorts of useful methods:

如果你做了大量的字符串操作,那么有一个很棒的Spring类,它有各种各样有用的方法:

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html

#9


4  

I would encourage using an existing utility, or creating your own method:

我鼓励使用现有的实用工具,或者创建自己的方法:

public static boolean isEmpty(String string) {
    return string == null || string.length() == 0;
}

Then just use it when you need it:

那么当你需要的时候就用它:

if (! StringUtils.isEmpty(string)) {
  // do something
}

As noted above, the || and && operators short circuit. That means as soon as they can determine their value they stop. So if (string == null) is true, the length part does not need to be evaluated, as the expression would always be true. Likewise with &&, where if the left side is false, the expression is always false and need not be evaluated further.

如上所述,||和&&操作符短路。这意味着一旦他们能够确定他们的价值,他们就会停止。因此,如果(string == null)是正确的,那么长度部分不需要被计算,因为表达式总是正确的。同样的,如果左边是假的,表达式总是错误的,不需要进一步评估。

As an additional note, using length is generally a better idea than using .equals. The performance is slightly better (not much), and doesn't require object creation (though most compilers might optimize this out).

另外,使用长度通常比使用.equals更好。性能稍微好一点(不是很多),不需要对象创建(尽管大多数编译器可能会优化这个)。

#10


4  

Every time i have to deal with strings (almost every time) I stop and wonder which way is really the fastest way to check for an empty string. Of course the string.Length == 0 check should be the fastest since Length is a property and there shouldn't be any processing other than retrieving the value of the property. But then I ask myself, why is there a String.Empty? It should be faster to check for String.Empty than for length, I tell myself. Well i finnaly decided to test it out. I coded a small Windows Console app that tells me how long it takes to do a certain check for 10 million repitions. I checked 3 different strings: a NULL string, an Empty string, and a "" string. I used 5 different methods: String.IsNullOrEmpty(), str == null, str == null || str == String.Empty, str == null || str == "", str == null || str.length == 0. Below are the results:

每当我要处理字符串(几乎每次)时,我都会停下来,想知道哪种方法是检查空字符串的最快方法。当然,字符串。Length == 0检查应该是最快的,因为长度是一个属性,除了检索属性值之外,不应该有任何处理。然后我问自己,为什么会有一个字符串,空的?应该更快地检查字符串。我对自己说,空比长。我决定试一试。我编写了一个小的Windows控制台应用程序,它告诉我要花多长时间才能完成1000万次的检查。我检查了3个不同的字符串:空字符串、空字符串和“”字符串。我使用了5种不同的方法:String. isnullorempty (), str == null, str == null || str == String。空的,str == null || ||。下面的结果:

String.IsNullOrEmpty()
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds

str == null
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds

str == null || str == String.Empty
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds

str == null || str == ""
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds

str == null || str.length == 0
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds

According to these results, on average checking for str == null is the fastest, but might not always yield what we're looking for. if str = String.Empty or str = "", it results in false. Then you have 2 that are tied in second place: String.IsNullOrEmpty() and str == null || str.length == 0. Since String.IsNullOrEmpty() looks nicer and is easier (and faster) to write I would recommend using it over the other solution.

根据这些结果,对str == null的平均检查是最快的,但可能不会总是产生我们正在寻找的东西。如果字符串str =。空或str = "",结果为false。然后有两个并列在第二的位置:String.IsNullOrEmpty()和str == null || .length == 0。因为String.IsNullOrEmpty()看起来更好,而且更容易(而且更快),所以我建议在其他解决方案中使用它。

#11


4  

WORKING !!!!

工作! ! ! !

if (myString != null && !myString.isEmpty()) {
        return true;
}
else{
        return false;
}

#12


3  

I'd do something like this:

我会做这样的事情:

( myString != null && myString.length() > 0 )
    ? doSomething() : System.out.println("Non valid String");
  • Testing for null checks whether myString contains an instance of String.
  • 测试null检查myString是否包含字符串实例。
  • length() returns the length and is equivalent to equals("").
  • length()返回长度,相当于等于(“”)。
  • Checking if myString is null first will avoid a NullPointerException.
  • 检查myString是否为空首先将避免NullPointerException。

#13


3  

I been using StringUtil.isBlank(string)

我使用StringUtil.isBlank(字符串)

It tests if a string is blank: null, emtpy, or only whitespace.

它测试字符串是否为空:null、emtpy或只有空格。

So this one is the best so far

这是迄今为止最好的。

Here is the orignal method from the docs

这是来自文档的orignal方法。

/**
    * Tests if a string is blank: null, emtpy, or only whitespace (" ", \r\n, \t, etc)
    * @param string string to test
    * @return if string is blank
    */
    public static boolean isBlank(String string) {
        if (string == null || string.length() == 0)
            return true;

        int l = string.length();
        for (int i = 0; i < l; i++) {
            if (!StringUtil.isWhitespace(string.codePointAt(i)))
                return false;
        }
        return true;
    } 

#14


2  

This should work:

这应该工作:

if (myString != null && !myString.equals(""))
    doSomething
}

If not, then myString likely has a value that you are not expecting. Try printing it out like this:

如果没有,那么myString可能具有您不期望的值。试着这样打印:

System.out.println("+" + myString + "+");

Using the '+' symbols to surround the string will show you if there is extra whitespace in there that you're not accounting for.

使用“+”符号包围字符串将显示,如果有额外的空白,您没有考虑。

#15


2  

if(str.isEmpty() || str==null){ do whatever you want }

if(string . isempty () || | str==null){做你想做的任何事}

#16


1  

I had this problem in android and i use this way (Work for me):

我在android上有这个问题,我用这个方法(为我工作):

String test = null;
if(test == "null"){
// Do work
}

But in java code I use :

但在java代码中,我使用:

String test = null;
if(test == null){
// Do work
}

And :

和:

private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
    String strDate0 = BeanUtils.getProperty(arg0, strProperty);_logger.debug("strDate0 = " + strDate0);
    String strDate1 = BeanUtils.getProperty(arg1, strProperty);_logger.debug("strDate1 = " + strDate1);
    return compareDateStrings(strDate0, strDate1);
}

private Integer compareDateStrings(String strDate0, String strDate1) {
    int cmp = 0;
    if (isEmpty(strDate0)) {
        if (isNotEmpty(strDate1)) {
            cmp = -1;
        } else {
            cmp = 0;
        }
    } else if (isEmpty(strDate1)) {
        cmp = 1;
    } else {
        cmp = strDate0.compareTo(strDate1);
    }
    return cmp;
}

private boolean isEmpty(String str) {
    return str == null || str.isEmpty();
}
private boolean isNotEmpty(String str) {
    return !isEmpty(str);
}

#17


1  

I prefer to use:

我更喜欢使用:

if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
    // do something
}

Read StringUtils.isBlank() vs String.isEmpty().

读StringUtils.isBlank vs String.isEmpty()()。

#18


1  

In Android you can check this with utility method isEmpty from TextUtils,

在安卓系统中,你可以用效用方法从TextUtils检测到这个,

public static boolean isEmpty(CharSequence str) {
    return str == null || str.length() == 0;
}

isEmpty(CharSequence str) method check both condition, for null and length.

isEmpty(CharSequence str)方法检查这两个条件,为null和长度。

#19


1  

Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab. You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists. For example, there are all numbers, char, boolean etc. The normal data types or complex data types is everything else. A String is an array of chars, therefore a complex data type.

这就是数据类型在Java中的作用。(你得原谅我的英语,我是prob。不使用正确的vocab。你必须区分它们中的两个。基本数据类型和正常数据类型。基本数据类型几乎构成了所有存在的东西。例如,所有的数字、char、boolean等都是正常的数据类型或复杂的数据类型。字符串是chars的数组,因此是一个复杂的数据类型。

Every variable that you create is actually a pointer on the value in your memory. For example:

您创建的每个变量实际上都是一个指向内存中值的指针。例如:

String s = new String("This is just a test");

the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory. When you call System.out.println(anyObject), the toString() method of that object is called. If it did not override toString from Object, it will print the pointer. For example:

变量“s”不包含字符串。这是一个指针。这个指针指向内存中的变量。当您调用System.out.println(anyObject)时,该对象的toString()方法被调用。如果它没有从对象覆盖toString,它将打印指针。例如:

public class Foo{
    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(f);
    }
}

>>>>
>>>>
>>>>Foo@330bedb4

Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.

“@”后面的一切都是指针。这只适用于复杂的数据类型。原始数据类型直接保存在它们的指针中。所以实际上没有指针,值是直接存储的。

For example:

例如:

int i = 123;

i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).

在这种情况下,我不存储指针。我将存储整数值123(在字节ofc中)。

Okay so lets come back to the == operator. It always compares the pointer and not the content saved at the pointer's position in the memory.

好,我们回到==运算符。它总是比较指针,而不是保存在内存中指针位置的内容。

Example:

例子:

String s1 = new String("Hallo");
String s2 = new String("Hallo");

System.out.println(s1 == s2);

>>>>> false

This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.

这两个字符串都有不同的指针。字符串。而equals(String other)则对内容进行比较。您可以将原始数据类型与“==”操作符进行比较,因为具有相同内容的两个不同对象的指针是相同的。

Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.

Null意味着指针是空的。默认情况下,一个空的原始数据类型为0(用于数字)。对于任何复杂对象来说,Null是不存在的。

Greetings

问候

#20


1  

For me the best check if a string has any meaningful content in Java is this one:

对于我来说,如果字符串在Java中有任何有意义的内容,最好的检查就是这个:

string != null && !string.trim().isEmpty()

First you check if the string is null to avoid NullPointerException and then you trim all space characters to avoid checking strings that only have whitespaces and finally you check if the trimmed string is not empty, i.e has length 0.

首先检查字符串是否为空,以避免NullPointerException,然后删除所有空格字符,以避免检查只具有whitespaces的字符串,最后检查修剪后的字符串是否为空。e长度为0。

#21


0  

I think that myString is not a string but an array of strings. Here is what you need to do:

我认为myString不是字符串而是字符串数组。以下是你需要做的:

String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
    //Do something
}

#22


0  

You can check string equal to null using this:

你可以用这个来检查字符串是否等于null:

String Test = null;
(Test+"").compareTo("null")

If the result is 0 then (Test+"") = "null".

如果结果是0,那么(Test+") = "null"。

#23


0  

I tried most of the examples given above for a null in an android app l was building and IT ALL FAILED. So l came up with a solution that worked anytime for me.

我尝试了上面给出的大多数例子,在android应用程序l上的一个空值,都失败了。所以我想出了一个可以随时为我工作的解决方案。

String test = null+"";
If(!test.equals("null"){
       //go ahead string is not null

}

So simply concatenate an empty string as l did above and test against "null" and it works fine. In fact no exception is thrown

所以简单地连接一个空字符串,就像我在上面做的那样,并对“null”进行测试,它可以正常工作。事实上,也没有抛出异常。

#24


0  

Exception may also help:

异常也可以帮助:

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}

#25


-5  

You have to check with null if(str != null).

如果(str != null),则必须检查null。