When to use NULL and when to use an empty string?

1)
It depends on the domain you are working on. NULL means absence of value (i.e. there is no value), while empty string means there is a string value of zero length.
For example, say you have a table to store a person' data and it contains a Gender column. You can save the values as 'Male' or 'Female'. If the user is able to choose not to provide the gender data, you should save that as NULL (i.e. user did not provide the value) and not empty string (since there is no gender with value '').

2)A null value means no memory is assigned to object only a reference is created in stack . So a null value is memory efficient . Also a null value will throw a null pointer exception if we by mistake use the reference , on the other hand if we initialize with an empty string we might not know about this error early.

We can use empty string if required for the code else we should initialize string with null.

Comments

Popular posts from this blog

How to resolve session timeout issue in JAVA

Blog gives you enthusiasm,zeal

How to encode HTML in JAVA (Remove HTML from your text)