Abby
Abby

Reputation: 89

Difference between returns a null value and an empty string?

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

Upvotes: 8

Views: 2082

Answers (3)

Nick Holt
Nick Holt

Reputation: 34321

From the JavaDoc:

Returns the value of a request parameter as a String, or null if the parameter does not exist.

What this means in reality is:

  • when the return value is null the HTML form didn't have an input with the parameter name in it
  • when the value is an empty String the HTML form did have an input with the parameter name in it but that no value was set.

Upvotes: 2

kornero
kornero

Reputation: 1069

If method returns empty string, it return an Object (reference on it) and you can work with it, when it returns null, then you can't work with it, because there is nothing to work with.

String s = "";
s.isEmpty(); // returns true

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

Return an empty string is better when you want to have more robust code, but if you return null, then null pointers will help you to find some sort of errors in your logic. May be working with empty strings is not appropriate, then null value will help you to find places where is no needed checks.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

A call of getParameter("adminNo") returns an empty String if the parameter called adminNo exists but has no value, and null is returned if there was no such parameter.

Upvotes: 4

Related Questions