Easier Way of Writing Null or Empty

Easier way of writing null or empty?

Yes, there's the String.IsNullOrEmpty helper method for exactly this already:

if (String.IsNullOrEmpty(myString)) {
...
}

Easiest way to check for null and empty string on a TypeScript number

You can simply use typeof. It will check undefined, null, 0 and "" also.

if(typeof RetailPrice!='undefined' && RetailPrice){
return this.RetailPrice;
}

Best way to verify string is empty or null

Haven't seen any fully-native solutions, so here's one:

return str == null || str.chars().allMatch(Character::isWhitespace);

Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):

return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);

Or, to be really optimal (but hecka ugly):

int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;

One thing I like to do:

Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}

...

notBlank(myStr).orElse("some default")

Easiest way to check if property is null or empty in java

Write a method isNullOrEmpty(String):

static boolean isNullOrEmpty(String s) {
return s == null || s.trim().isEmpty()
// Or return s == null || s.isBlank(); in Java 11+
}

So you can write:

return isNullOrEmpty(account.getAccesskeyid())
|| isNullOrEmpty(account.getAccount())
/* etc */;

I consider this preferable to doing something that involves constructing streams or lists, because it's just simple: it's using very basic language features that are easily understandable by even a novice programmer.

In addition, it avoids evaluating all of the fields (e.g. passing String... ss to isNullOrEmpty, and then doing something on the array) because it short-circuits, in that it will stop as soon as it finds the first null or empty string.

It also does not require creation of any objects (like the implicit array, or a List in the case of Arrays.asList(...)) that are simply artefacts of invoking the method: trim() does potentially create objects, but this is "useful" work, insofar as this is necessary to evaluate the condition.

Easiest way to check if string is null or empty

Yup:

passwordNotEmpty = not not password

or shorter:

passwordNotEmpty = !!password

Is there any way to check for string either it is null or blank?

.Net has provided default function for this purpose you should use like this.

if (string.IsNullOrEmpty("any string"))
{
}

Difference between null and empty () Java String

"" is an actual string, albeit an empty one.

null, however, means that the String variable points to nothing.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) returns false because "" does not equal null, obviously.

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

and so on.

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()


If the difference you are wondering about is == versus equals, it's this:

== compares references, like if I went

String a = new String("");
String b = new String("");
System.out.println(a==b);

That would output false because I allocated two different objects, and a and b point to different objects.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

Be warned, though, that Java does have a special case for Strings.

String a = "abc";
String b = "abc";
System.out.println(a==b);

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

Best way to check for empty or null value

The expression stringexpression = '' yields:

TRUE   .. for '' (or for any string consisting of only spaces with the data type char(n))

NULL   .. for NULL

FALSE .. for anything else

So to check for: "stringexpression is either NULL or empty":

(stringexpression = '') IS NOT FALSE

Or the reverse approach (may be easier to read):

(stringexpression <> '') IS NOT TRUE

Works for any character type including char(n). The manual about comparison operators.

Or use your original expression without trim(), which is costly noise for char(n) (see below), or incorrect for other character types: strings consisting of only spaces would pass as empty string.

coalesce(stringexpression, '') = ''

But the expressions at the top are faster.

Asserting the opposite is even simpler: "stringexpression is neither NULL nor empty":

stringexpression <> ''

About char(n)

This is about the data type char(n), short for: character(n). (char / character are short for char(1) / character(1).) Its use is discouraged in Postgres:

In most situations text or character varying should be used instead.

Do not confuse char(n) with other, useful, character types varchar(n), varchar, text or "char" (with double-quotes).

In char(n) an empty string is not different from any other string consisting of only spaces. All of these are folded to n spaces in char(n) per definition of the type. It follows logically that the above expressions work for char(n) as well - just as much as these (which wouldn't work for other character types):

coalesce(stringexpression, '  ') = '  '
coalesce(stringexpression, '') = ' '

Demo

Empty string equals any string of spaces when cast to char(n):

SELECT ''::char(5) = ''::char(5)     AS eq1
, ''::char(5) = ' '::char(5) AS eq2
, ''::char(5) = ' '::char(5) AS eq3;

Result:

 eq1 | eq2 | eq3
----+-----+----
t | t | t

Test for "null or empty string" with char(n):

SELECT stringexpression 
, stringexpression = '' AS base_test
, (stringexpression = '') IS NOT FALSE AS test1
, (stringexpression <> '') IS NOT TRUE AS test2
, coalesce(stringexpression, '') = '' AS coalesce1
, coalesce(stringexpression, ' ') = ' ' AS coalesce2
, coalesce(stringexpression, '') = ' ' AS coalesce3
FROM (
VALUES
('foo'::char(5))
, ('')
, (' ') -- not different from '' in char(n)
, (NULL)
) sub(stringexpression);

Result:


stringexpression | base_test | test1 | test2 | coalesce1 | coalesce2 | coalesce3
------------------+-----------+-------+-------+-----------+-----------+-----------
foo | f | f | f | f | f | f
| t | t | t | t | t | t
| t | t | t | t | t | t
null | null | t | t | t | t | t

Test for "null or empty string" with text:

SELECT stringexpression 
, stringexpression = '' AS base_test
, (stringexpression = '') IS NOT FALSE AS test1
, (stringexpression <> '') IS NOT TRUE AS test2
, coalesce(stringexpression, '') = '' AS coalesce1
, coalesce(stringexpression, ' ') = ' ' AS coalesce2
, coalesce(stringexpression, '') = ' ' AS coalesce3
FROM (
VALUES
('foo'::text)
, ('')
, (' ') -- different from '' in a sane character types
, (NULL)
) sub(stringexpression);

Result:


stringexpression | base_test | test1 | test2 | coalesce1 | coalesce2 | coalesce3
------------------+-----------+-------+-------+-----------+-----------+-----------
foo | f | f | f | f | f | f
| t | t | t | t | f | f
| f | f | f | f | f | f
null | null | t | t | t | t | f

db<>fiddle here

Old sqlfiddle

Related:

  • Any downsides of using data type "text" for storing strings?

Better way to check variable for null or empty string?

// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}


Related Topics



Leave a reply



Submit