Below is my code.
String perfIdValtxt = "";
try {
while (resultsOfSecurityDetails.next()) {
String perfIdVal = resultsOfSecurityDetails.getString(1);
if (perfIdVal == null) {
perfIdValtxt = "";
} else {
perfIdValtxt = perfIdVal;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Wanted to use one condition here i.e.like
if(perfIdVal != null){
//code
}
perfIdValtxt is being already set up before if else hence I wanted to optimize. Any workaround on this?
CodePudding user response:
String perfIdValtxt = "";
try {
while (resultsOfSecurityDetails.next())
if (resultsOfSecurityDetails.getString(1) != null)
perfIdValtxt = resultsOfSecurityDetails.getString(1);
} catch (SQLException e) {
e.printStackTrace();
}
CodePudding user response:
you dont need the else clause if you assign directly the variable perfIdValtxt
String perfIdValtxt = "";
try {
while (resultsOfSecurityDetails.next()) {
perfIdValtxt = resultsOfSecurityDetails.getString(1);
if (perfIdValtxt == null) {
perfIdValtxt = "";
}
}
} catch (SQLException e) {
e.printStackTrace();
}
CodePudding user response:
Just simply check if it's null set empty string otherwise set resultsOfSecurityDetails.getString(1) into perfIdValtxt
String perfIdValtxt;
try {
while (resultsOfSecurityDetails.next()) {
perfIdValtxt = resultsOfSecurityDetails.getString(1) != null ? resultsOfSecurityDetails.getString(1): "";
}
} catch (SQLException e) {
e.printStackTrace();
}
CodePudding user response:
Because you want perfIdValtxt to be assigned to "" if condition didn't satisfy:
try {
while (resultsOfSecurityDetails.next())
perfIdValtxt=(resultsOfSecurityDetails.getString(1) != null)?resultsOfSecurityDetails.getString(1):"";
} catch (SQLException e) {
e.printStackTrace();
}
CodePudding user response:
A handy way
String perfIdValtxt = "";
try {
while (resultsOfSecurityDetails.next()) {
perfIdValtxt = Optional.ofNullable(resultsOfSecurityDetails.getString(1)).orElse("");
}
} catch (SQLException e) {
e.printStackTrace();
}