In a code review, I got a comment which asked me why I initialized with a null instead of a ""
Reason #1
When you use String s = null it will create variable "s" on stack only and no object will exists on heap,but as soon as you declare things as like String s=""; what it will does is like it will create "" object on heap.As we know that Strings are immutable so whenever u wil assign new value to string varible everytime it will create new Object on heap...So I think String s=null is efficient than String s = "";
Reason #2
When we initialize a string as "",we are actually supressing a possible exception that will be automatically raised when we have it initialized to null. Yes Java has inbuilt exception handler for treating nulls - remember NUllPointerException (the buggy exception)...So if we have used this string somewhere on our webpage and it doesn't get inialized properly at runtime, if we had it initialized to null, java would shout "NullPointerException" if not we will have to work more towards catching this exception...
Reason #1
When you use String s = null it will create variable "s" on stack only and no object will exists on heap,but as soon as you declare things as like String s=""; what it will does is like it will create "" object on heap.As we know that Strings are immutable so whenever u wil assign new value to string varible everytime it will create new Object on heap...So I think String s=null is efficient than String s = "";
Reason #2
When we initialize a string as "",we are actually supressing a possible exception that will be automatically raised when we have it initialized to null. Yes Java has inbuilt exception handler for treating nulls - remember NUllPointerException (the buggy exception)...So if we have used this string somewhere on our webpage and it doesn't get inialized properly at runtime, if we had it initialized to null, java would shout "NullPointerException" if not we will have to work more towards catching this exception...
Comments