On the difference between null and "" in Java

Source: Internet
Author: User
Tags gettext

In Java, we usually have to initialize a string when we first recognize it as "", or do not give him a value so that he defaults to null.

First we say that the two symbols are different, the difference is that NULL is not the meaning, and "" This refers to the existence of a blank. If we create an object that assigns a value to null then it means that only one variable name is created in the heap, and there is no

The stack creates space for it, and if an object is assigned a value of "" then it is not only creating the variable name in the pair, but also opening up a blank space in the stack.

As for what I did after creating the variable null when to create "", this is like in the next code:

public Boolean verification () {
String a = T1.gettext ();
String B = T2.gettext ();
String C = T3.gettext ();
String d = t4.gettext ();
String error = "";
if (A.matches ("[a-za-z\\u4e00-\\u9fa5]{2,9}")!=true) {
Error + = "Name Please enter 2-9 Chinese or English letters \ n";
System.out.println (a);
}
if (C.matches ("[\\u4e00-\\u9fa5]{1}")!=true) {
error+= "Gender please use a Chinese description \ n";
}
if (B.matches ("[0-9]{2}")!=true) {
error+= "name is two digits \ n";
}
if (D.matches ("(13|15|18) [0-9]{9}")!=true) {
error+= "Phone number is 13 or 15 or 18 starts with 11 digits \ n";
}
if (Error.length () ==0) {
Joptionpane.showmessagedialog (NULL, "add success");
return true;

}
else{
Joptionpane.showmessagedialog (null, error);
return false;
}

}

If we assign the initial value of the error to null, then we will have a null pointer error in the next call to Error.length (), where we can only assign it as "".

And in some just receive output, do not need to call the string method of the place can be directly without assignment, directly let it default to null.

On the difference between null and "" in Java

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.