Search code examples
javaif-statementwhitespaceis-empty

Check whitespaces and isempty


I am looking for a if statement to check if the input String is empty or is only made up of whitespace and if not continue with the next input. Below is my code so far which gives an error when I input a whitespace.

    name = name.trim().substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
    if(name != null && !name.isEmpty() && name.contains(" ")) {
        System.out.println("One");
    } else {
        System.out.println("Two");
    }

Solution

  • I would write this as the following.

    name = name == null ? "" : name.trim();
    if(name.isEmpty()) {
        System.out.println("Null, empty, or white space only name received");
    } else {
        System.out.println("Name with at least length one received");
        name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
    }