Java if condition for empty validations - java

I'm new to java and i want to do a condition check and return a message
PersonalDetails Request: It holds the value for all the below infos
getID();
getName();
getDesignation();
getHomeAddress();
getOfficeAddress();
getEmailID();
getMobile();
getHomePhone();
getOfficePhone();
i want to check all values for empty then return message.
Like "Your ID,Name, Mobile cannot be empty" if i pass empty values to ID, Name, Mobile
Below is the sample snippet which has to do the check for all PersonalDetails Request
public static String checkValue(PersonalDetails Request) {
String str="Your ";
if(request.getID().isEmpty())
{
str="ID,";
}
if(request.getName().isEmpty())
{
str="Name";
}
if(request.getDesignation().isEmpty())
{
str="Designation";
}
if(request.HomeAddress.isEmpty())
{
str="Address";
}
str+= "cannot be empty"
return str;
}
Is this right or any other easy approach will address the issue
Thanks in advance

No if the string contains null then it will through a null pointer exception.
You first need to check it for null then for Empty.
Can we rely on String.isEmpty for checking null condition on a String in Java?

There are multiple suggestions for your code:
Use camel-case for variables, methods etc. in your code. For example parameter should be named as PersonalDetails request and not PersonalDetails Request. These are standard coding conventions. Also getter/setter should follow the rules, check HomeAddress which seems to miss it.
Use StringBuilder class as it performs better specially in case of appending while in a loop.
You need to check for null before performing any operation else you will be facing a NullPointerException. You can also read about Optional in Java 8.
The code can be improved like:
public static String checkValue(PersonalDetails request) {
if(null == request ) {
//Throw exception or log/return message as per your need.
}
int some_appropriate_size = 50; // You need to decide about some_appropriate_size so that it starts with enough capacity for the full content we are going to append.
StringBuilder stringBuilder = new StringBuilder(some_appropriate_size);
stringBuilder.append("Your ");
if(null!= request.getID() && request.getID().isEmpty())
{
stringBuilder.append("ID,");
}
if(null!= request.getName() && request.getName().isEmpty())
{
stringBuilder.append("Name");
}
if(null!= request.getDesignation() &&request.getDesignation().isEmpty())
{
stringBuilder.append("Designation");
}
if(null!= request.getHomeAddress() && request.getHomeAddress().isEmpty())
{
stringBuilder.append("Address");
}
stringBuilder.append( "cannot be empty");
return stringBuilder.toString();
}

Your condition is correct but you forget to concat string in each if. If don't concate it will not have existing value but new value only.
public static String checkValue(PersonalDetails Request) {
String str="Your ";
if(request.getID().isEmpty())
{
str= str + "ID,";
}
if(request.getName().isEmpty())
{
str= str + "Name";
}
if(request.getDesignation().isEmpty())
{
str= str + "Designation";
}
if(request.HomeAddress.isEmpty())
{
str= str + "Address";
}
str+= "cannot be empty"
return str;
}
My suggestion will be to use StringBuilder to get better performance.

Here it's better to check not only isEmpty. It's better to check null, " " or "-" as well.
Before you check isEmpty or "-" or " ", make sure to check null to avoid getting NullPointerException

Related

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

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";
}
}
}
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, "");
You may consider it just a minor improvement over the solution that you have got. It certainly isn’t a one-shot validation of all the variables. My idea is to do validation and assignment of each in the same line. For example:
String productId = validate("", "productId");
String productName = validate("Apple", "productName");
Result:
Exception in thread "main" java.lang.NullPointerException: productId
The message mentions that the productId is blank/empty.
This obviously requires validate() to return the validated object in the case where it doesn’t throw.
private static String validate(String s, String message) {
if (s == null || s.isBlank()) {
throw new NullPointerException(message);
} else {
return s;
}
}
We don’t need isEmpty() as an explicit condition since isBlank() also returns true for the completely empty string. Whether you want to check for null, you know best yourself.
For non-String variables simply use the built-in Objects.requireNonNull():
LocalDate productSellDate = Objects.requireNonNull(
LocalDate.now(ZoneId.systemDefault()), "productSellDate");
LocalDate productReturnDate = Objects.requireNonNull(
LocalDate.now(ZoneId.systemDefault()), "productReturnDate");
LocalDate is a class from java.time, the modern Java date and time API that I recommend for all of your date work. A LocalDate is a date without time of day. If you need the time too, find some other class from the same API.

Java - What does it mean by writing return ""; in a method?

I am a Java beginner. When reading a block of Java code, I came across a method which includes a if condition and return "";
Just wondering what does return ""; means…
The example code is below:
public String parse(String d, String u) {
if (d.isEmpty() || u.isEmpty()){
return "";
}
...
}
Could someone explain further to me please? Thank you
I'm just doing to break this down line by line for you.
public String parse(String d, String u)
This line declares a new method which:
Is called parse
Returns a string
Takes two strings as inputs
If youre wondering specifically about the fact that the keyword return is used then you can look at this answer I found from a quick google search.
if (d.isEmpty() || u.isEmpty())
This line checks if the input d is empty OR (expressed by '||') input u is empty. Essentially checking if either of the inputs are empty.
return "";
If the above if statement is met, return""; will be run. This means the method will return an empty String.
I can only guess what is at the end of the method you've posted but to help you further I've whipped up a quick example.
public String parse(String d, String u) {
if (d.isEmpty() || u.isEmpty()){
return "";
} else {
return "not empty";
}
}
public static void main(String[] args)
{
String d = "hi";
String u = ""; //empty
String result = parse(d, u);
System.out.println(result);
String d = "hi";
String u = "bye"
result = parse(d, u);
System.out.println(result);
}
The output we get in the console is:
empty
not empty
This is probably a check before starting parsing those string, you dont want to parse empty strings cause it probably has to do with the parsing mechenism, so it start from checking validation of the arguments, and return empty String if it invalid

How to avoid many if-else statements

I have a class like this..
Class A {
public void someNullCheckingMethod(Student stu) {
if (stu.getName() != null) {
String name = stu.getName();
} else {
// get name from other source(its something like
// fallback)
}
if (stu.getId() != null) {
String id = stu.getId();
} else {
// get id from other source(its something like
// fallback)
}
if (stu.getAddress() != null) {
String address = stu.getAddress();
} else {
// get address from other source(its something like
// fallback)
}
if (stu.getCity() != null) {
String city = stu.getCity();
} else {
// get city from other source(its something like
// fallback)
}
if (stu.getGender() != null) {
String gender = stu.getGender();
} else {
// get gender from other source(its something like
// fallback))
}
}
}
is there a way to avoid too many if statements? As you can see here I am checking null condition for each property but i don't want many checks to get desired result just want to reduce if conditions as well as want to get same desired result whatever I will get by putting all these if conditions.
Since you don't provide any context there's a few things you can do based on some assumptions.
Assumption one:
if the values are initialized as null
String name;
// or
String name = null;
Then you can just assign the values and ignore if the fields are null or not since the class members are null already.
String name = stu.getName(); // String name = "Some Name" OR null, depending on return value of method
Assumption two:
If you just want to avoid the if statements you can go with ternary operators
String name = stu.getName() != null ? stu.getName() : null; // Or some other default value
There are a few other methods that pops into my mind as well but without more context they are a bit useless at this point.
You could at least reduce the "verbosity" with Optional.
String name;
if (stu.getName() != null) {
name = stu.getName();
} else {
name = "default"
}
Would become
String name = Optional.ofNullable(stu.getName()).orElse("default");
Th choice is yours to return an Optional directly from the POJO Student for any value that could be null.
This would give a cleaner solution :
String name = stu.getName().orElse("default");
If getName looks like :
public Optional<String> getName(){
return Optional.ofNullable(name);
}
If using an external library is an option, then you should take a look at Dozer or MapStruct.

java for loop that runs list executes only once

The for loop in the code below only executes once. I was looking at similiar questions but those have something that breaks it like editing the list in the loop while I dont.
public String getProfileList(JSONObject obj, String uuid) {
JSONObject profile = (JSONObject) obj.get("profiles");
#SuppressWarnings("unchecked")
ArrayList<String> list = new ArrayList<String>(profile.keySet());
System.out.println(list);
for (String object: list) {
System.out.println(object);
String isUUID = (String) ((JSONObject) profile.get(object)).get("mpm-data:uuid");
System.out.println(object + " == " + isUUID);
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}
}
System.out.println("no profile found.");
return null;
}
This code outputs this:
[5fb4acd48e7d422eabecd82e32fb03c6, 44d01181eae635d31f2cefe5e1f75cd4,e0e96e422659dfdc1ad16d53a37ee618, a3ae7136f900457290e99bd657db0385]
5fb4acd48e7d422eabecd82e32fb03c6
5fb4acd48e7d422eabecd82e32fb03c6 == null
For your console output you can see that isUUID is null. This means that when you attempt to call its method equals there is actually no object to call it to and you should be getting a NullPointerException. That's why it is best to do equals assertions with the part you know will not be null on the left side:
uuid.equals(isUUID) would be better.
Notice that if you do an equals assertion with a variable and a static string then it is best to do it like so:
"myCompareString".equals(myVariable), since "myCompareString" can never be null whereas myVariable can.
if (isUUID.equals(uuid)) will throw a nullPointerException when isuuid is null.
You should check if the data is right, and handle the exception.
And you can use StringUtils.equals(String str1, String str2) in commons-lang.jar, then you don't need to handle the null yourself, see http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html
System.out.println(object + " == " + isUUID);
Code prints
5fb4acd48e7d422eabecd82e32fb03c6 == null and next statement you are using in if condition .If isUUID is null it should throw null pointer exception.Can you please check this point
if (isUUID.equals(uuid)) {
System.out.println("TRUE");
return object;
}

Why isn't my return statement being recognized?

It says it must return a string. But it already is. Then it says that it must have a return statement. But there is one there.
public String description() {
String description = "";
if (description != null)
return description;
}
because if description is null then that return statement is never executed.
your code must be modfied to some thing like this
public String description() {
String description = "";
if (description != null){
return description;
}else{
return null;
}
}
I know that description is not equal to null but the compiler complains because if that if block is never executed then the method will not have a return statement, hence you need to have one outside it too.
To answer your question the reason you get the error the you must have a return statement is that having the return statement within a conditional branch means that there is a possibility that it will not execute. Since this method requires a return type you must include an else condition to return a value so all branches are covered.
Since Java performs a "pseudo compilation" it doesn't know that "description" is clearly not null until it runtime.
I just saw that you are wanting the method to do nothing in the event "description" is null. In this case I would recommend throwing an exception:
#SuppressWarnings("unused")
public String description() throws ValidationException {
String description = "";
if (description == null){
throw new ValidationException("Some Error Message");
}
return description;
}

Categories

Resources