The difference between a Java empty string and a null string

Source: Internet
Author: User
Tags java se

I've never figured out the difference between a string and a null string, and today the code has been nullpointerexception, and I haven't figured it out.

String s = null;
s = xxx.getstring ();
if (!s.isempty () && s! = null) {
System.out.println ("OK");
}

I haven't read it for a long while (refusing to taunt). So I looked at someone else's blog and wrote a note.

1. Differences

Null indicates that the reference to a string object is null, string a=null; A string variable A is declared, and the reference to variable a is empty. So a doesn't point to any memory space, nor does it open up any space in the heap.

An empty string indicates that the value of a string object reference is null, string a = "" declares a string variable a, and the value of variable A is null. And a points to the memory space of the empty string.

2. Determine how the string is empty

(1) if (s! = null && s.equals (""));

(2) if (s! = null && s.length () = = 0);

public int Length () {        return value.length;    }

(3) if (s! = null && s.isempty ());

Java SE 1.6 Adds the method, the underlying implementation is similar to 2.

Method of implementation:

public Boolean isEmpty () {        return value.length = = 0;    }

(4) if (s! = NULL && s = = "");

Note: Do not write the same as I do, two judgment logic is reversed, there may be a nullpointerexception exception.

The difference between a Java empty string and a null string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.