Difference between returns null and empty string?

Suppose you have an input field named "adminNo". What is the difference when you call the getParameter ("adminNo") method, returns a null value and when it returns an empty string ""?

+8
java servlets
source share
3 answers

The call getParameter("adminNo") returns an empty String if the adminNo parameter exists, but does not matter, and null returned if there was no such parameter.

+3
source share

From JavaDoc :

Returns the value of the query parameter as String or null if the parameter does not exist.

In reality, this means:

  • when the return value is null , there was no input in the HTML form with the parameter name in it
  • when the value is an empty String , the HTML form had an input with the parameter name in it, but this value was not set.
+2
source share

If the method returns an empty string, it returns an object (a reference to it), and you can work with it when it returns null, then you cannot work with it because there is nothing to work with it.

 String s = ""; s.isEmpty(); // returns true String s = null; s.isEmpty(); // throws null pointer exception. 

It is better to return an empty string if you want to have more reliable code, but if you return zero, then null pointers will help you find some errors in your logic. Perhaps working with empty lines is not suitable, then a zero value will help you find places where there are no necessary checks.

0
source share

All Articles