String of isEmpty () and null and "" the difference

Code outcome

public class demo {
    public static void main(String[] args) {
        String a = new String();
        String b = "";
        String c = null;
        test(a);
        test(b);
        test(c);
    }

    private static void test(String str) {

        if (str == null) {
            System.out.println("null");
        }

        if (str.isEmpty()) {
            System.out.println("isEmpty");
        }

        if (str.equals("")) {
            System.out.println("");
        }
        System.out.println("------分割线------");
    }
}
7038163-694e0d2eade3046b.jpg
output.jpg

The results can be analyzed by running the program segment:

  • a memory space is allocated with a value of null, null is an absolute value;
  • b and allocated memory space is an empty string, a relatively null values;
  • c unallocated memory space and no value, a state of no value.

It is determined whether a variable is a String object using subjected == null compared to null, can not be used equals (), isEmpty (), "" Analyzing the like, because the air has not been instantiated objects.

For determination null String three methods may be employed, equals ( "") whether the content of the comparison target method is null; length () == 0 to determine whether the number of characters String null; isEmpty () method the number of characters is determined whether the String object to a null value (which is equivalent to the implementation principle length () == 0).

For strings of spaces, and null values ​​although the display time, are empty, but a space at run-time memory the string representation of the object inside the content (a space, and the number of characters is the number of spaces) at the output. Therefore, the use of length () is the number of spaces output using isEmpty () output is false, using equals ( "") is determined to false.

String for the + operator, if either operand is a String, the other operand is converted to a String. Special attention, null character string "XXXX" + Operation becomes "nullXXXX".

The difference between str! = Null and null! = Str of

str! = Null null pointer exception occurs, and null! = Str never practices do not appear null pointer exception, but also extreme programming recommendations. The purpose is to prevent errors.

As:
str.equals ( "123"); If you develop a good habit, should be written as "123" .equals (str); because even if str is empty, or returns false, but if the former will report null pointer abnormal.

The difference equals and ==

Guess you like

Origin blog.csdn.net/weixin_34319374/article/details/90931790