I understand that every time I type the string literal \"\", the same String object is referenced in the string pool.
But why doesn\'t the String API in
For those claiming "" and String.Empty are interchangeable or that "" is better, you are very wrong.
Each time you do something like myVariable = ""; you are creating an instance of an object. If Java's String object had an EMPTY public constant, there would only be 1 instance of the object ""
E.g: -
String.EMPTY = ""; //Simply demonstrating. I realize this is invalid syntax
myVar0 = String.EMPTY;
myVar1 = String.EMPTY;
myVar2 = String.EMPTY;
myVar3 = String.EMPTY;
myVar4 = String.EMPTY;
myVar5 = String.EMPTY;
myVar6 = String.EMPTY;
myVar7 = String.EMPTY;
myVar8 = String.EMPTY;
myVar9 = String.EMPTY;
10 (11 including String.EMPTY) Pointers to 1 object
Or: -
myVar0 = "";
myVar1 = "";
myVar2 = "";
myVar3 = "";
myVar4 = "";
myVar5 = "";
myVar6 = "";
myVar7 = "";
myVar8 = "";
myVar9 = "";
10 pointers to 10 objects
This is inefficient and throughout a large application, can be significant.
Perhaps the Java compiler or run-time is efficient enough to automatically point all instances of "" to the same instance, but it might not and takes additional processing to make that determination.