Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check multiple string value are empty or blank at one shot using java

Tags:

java

string

I've scenario to validate given input param is empty or not, I've list of fields with datatype string and date - productId,productName,productType,productRating,productSellDate and productReturnDate

I want to check these input params are null or empty or blank for each field and if any one of the field is empty or blank or null - it should throw NullPointerException with field name.

Please find my code below - since I'm new to Java please apologize for the coding standard. I don't know how to get the field name which has empty or null when I throw NullPointerException

And I'm calling validate and validateDate for each string, is there any option to validate all these param in one go?

Please suggest if there is any better way of writing the below piece of code. Appreciated your help in advance! Thanks.

import java.util.Date;

public class Test {

    public static void main(String[] args) {
        String productId = "";
        String productName = "Apple";
        String productType = "Electronics";
        String productRating = "Good";
        Date productSellDate = new Date();
        Date productReturnDate = new Date();

        System.out.println(validate(productId));
        System.out.println(validate(productName));
        System.out.println(validate(productType));
        System.out.println(validate(productRating));

        System.out.println(validateDate(productSellDate));
        System.out.println(validateDate(productReturnDate));

    }


    private static String validate(String s) {
        if (s.isBlank() || s.isEmpty()) {
            throw new NullPointerException("input param is empty"); // how to get the string field name which is empty or null or blank
        } else {
            return "valid";
        }
    }


    private static String validateDate(Date d) {
        if (d == null) {
            throw new NullPointerException("sell or return date is empty"); // how to get the date field name which is empty or null or blank
        } else {
            return "date is valid";
        }
    }
}
like image 678
Dave Brady Avatar asked Mar 13 '26 17:03

Dave Brady


1 Answers

You can write it like this to take any number of input and throw if any one fo them are null or blank or empty

private static String validate(String... strings) {
    for (String s : strings) {
        if (s == null || s.isBlank() || s.isEmpty()) {
            throw new NullPointerException("input param is empty");
        }
    }
    return "valid";
}

and you can call it with any number of inputs

validate("1", "2", null, "");
like image 170
AmrDeveloper Avatar answered Mar 15 '26 06:03

AmrDeveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!