how to check if the variable is null?

10,858

you can use .equals("") or .isEmpty()

check check if the variable is null

Share:
10,858

Related videos on Youtube

Víťa Dvořák
Author by

Víťa Dvořák

Updated on June 04, 2022

Comments

  • Víťa Dvořák
    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
      Fildor over 6 years
      You can check String.length ... and String.isEmpty() is equivalent to checking length for 0.
    • Andy Turner
      Andy Turner over 6 years
      b.isEmpty(). nextLine() never returns null.
    • Fildor
      Fildor over 6 years
      Mind 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
    Andy Turner over 6 years
    The b != null is redundant.
  • Sync
    Sync over 6 years
    Why you'd even suggest equals("") when String has isEmpty() is beyond me.
  • useless'MJ
    useless'MJ over 6 years
    because you can use equals("") also as it is from parent calss Object but you are right , better to use isEmpty() 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 about b being null (or are otherwise checking for it), I would definitely use .isEmpty(); it shows exactly what you're checking, you care whether or not b is empty, not whether it equals the empty string
  • Sync
    Sync over 6 years
    Your 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
    useless'MJ over 6 years
    i am not telling you the advantages am telling you how many ways we can check..so .equals() is also one of them