how to check if the variable is null?
10,858
you can use .equals("")
or .isEmpty()
check check if the variable is null
Related videos on Youtube
Author by
Víťa Dvořák
Updated on June 04, 2022Comments
-
Víťa Dvořák almost 2 years
I know this doesnt work but how can I know if the user added even one char?
public class Program import java.util.Scanner; { public static void main(String[] args) { Scanner a = new Scanner(System.in); String b = a.nextLine(); //I know this doesnt work but how can I know if the user added even one char? if (b!=null){ System.out.println(b); } } }
-
Fildor over 6 yearsYou can check String.length ... and String.isEmpty() is equivalent to checking length for 0.
-
Andy Turner over 6 years
b.isEmpty()
.nextLine()
never returns null. -
Fildor over 6 yearsMind that Whitespaces count for length. So if you actually want to check for "Non-Whitespace characters" then there is a little more effort. See also: stackoverflow.com/a/3247081/982149
-
-
Andy Turner over 6 yearsThe
b != null
is redundant. -
Sync over 6 yearsWhy you'd even suggest
equals("")
whenString
hasisEmpty()
is beyond me. -
useless'MJ over 6 yearsbecause you can use
equals("")
also as it is from parent calssObject
but you are right , better to useisEmpty()
because ,see The main benefit of"".equals()
is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried aboutb
being null (or are otherwise checking for it), I would definitely use.isEmpty()
; it shows exactly what you're checking, you care whether or notb
is empty, not whether it equals the empty string -
Sync over 6 yearsYour answer advocates
.equals("")
not"".equals(s)
. It also did not include the advantages of using"".equals(s)
. Are you expecting this to come naturally to the readers who read your answer but not the comments? I still stand by that this is a bad answer. -
useless'MJ over 6 yearsi am not telling you the advantages am telling you how many ways we can check..so
.equals()
is also one of them