String = "" and string = NULL difference

Source: Internet
Author: User

In this case, the relationship between string str and string str=null, which is almost nothing in the code, but string str=null; A pointer to an empty reference.

While string str is only defined, string str=null is initialized more than string str.

But string str=null points to a null reference, there is no space in memory, no actual memory.

If a string method is called through STR, a null pointer exception is reported.

Creating a string in this way, by "", is saved to the string pool in the string class, where space is allocated in memory.

That is, string str=null is not instantiated, and string = "" is instantiated and "" can be considered an object.

We verify by small program:

String str1 = "";
String str2 = null;
System.out.println (Str1.length ());
System.out.println (Str2.length ());

You can see that the output is:

0
Exception in thread "main" java.lang.NullPointerException
At Com.mytest.StringTrap.main (stringtrap.java:15)

In summary, string str=null, although initialized, is not instantiated, and string = "" is already instantiated, the former does not exist in memory, and the latter is actually present.

String = "" and string = NULL difference

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.