In Java, the difference between new String(), "", and null

In Java, the difference between new String(), "", and null

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String a = new String();
String b = "";
String c = null;
testString(a);
testString(b);
testString(c);

}

private void testString(String str){
if (str == null){
Log.e(“testNull”, “null”);
}
if (str.isEmpty()){
Log.e(“testNull”, “isEmpty”);
}
if (str.equals("")){
Log.e(“testNull”, “引号”);
}
Log.e(“testNull”, “----------------”);
}

Since I only play Android, I wrote an Android demo. The effect is the same~ The
log result is:
02-15 14:41:10.655 31875-31875/uding.testanimation E/testNull: isEmpty
02-15 14:41:10.655 31875-31875/uding.testanimation E/testNull: quotation mark
02 -15 14:41:10.655 31875-31875/uding.testanimation E/testNull: ----------------
02-15 14:41:10.655 31875-31875/uding.testanimation E /testNull: isEmpty
02-15 14:41:10.655 31875-31875/uding.testanimation E/testNull: quotation marks
02-15 14:41:10.655 31875-31875/uding.testanimation E/testNull: ------- ---------
02-15 14:41:10.655 31875-31875/uding.testanimation E/testNull: null

Then str reported a null pointer error. Here you can find that the effect of isEmpty and "" are the same.
Look at the source code of isEmpty again:
public boolean isEmpty() { return count == 0; } It means that as long as the number of text in the String is 0, it returns true, and the number of text in "" is 0.


To sum up:
    null is the "empty" of unallocated memory space ~
    isEmpty and quotation marks are the two "empty" relative to null (that is, they!= null), and they are all allocated memory (it seems to have almost the same meaning)

————————————————
Copyright statement: This article is the original article of the CSDN blogger "violet-jack", and it follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and This statement.
Original link: https://blog.csdn.net/violetjack0808/article/details/50668195

Guess you like

Origin blog.csdn.net/qq_41915623/article/details/102020977