Reputation: 21
String phone = rs.getString("CCU_PHONE");
System.out.println("phone" + phone);
I am getting value for phone from a database and it is null
hence it is not printing the value.
How do I handle the null
and print the value in System.out
?
Upvotes: 2
Views: 3486
Reputation: 4314
You can check if string is blank or not before printing...
String phone = rs.getString("CCU_PHONE");
if(phone == null || "".equals(phone)) {
// this will cover null and string of zero length.
System.out.println("Phone is null or empty.");
} else {
// if string is not blank or null.
System.out.println("phone" + phone);
}
PS : you can use StringUtils#isBlank() also, which will check null, zero length as well as blank spaced string also.
Upvotes: 0
Reputation: 140
Reason: Whenever you try to access a variable whose value is null
, it will always result into a NullPointerException
which will abruptly stop the execution, so, it is always recommended that you should check for null
before trying to access the value.
Upvotes: 0
Reputation: 1599
First you need to check if your string is null or empty and based on that you can use if else to print
if (phone!= null && !phone.isEmpty()) {
System.out.println("phone" + phone);
}
else
{
System.out.println("phonenull");
}
Upvotes: 0
Reputation: 35557
You can use
System.out.println("phone" +((phone!=null)?phone:" number not found !"));
Upvotes: 3
Reputation: 8197
Check for NULL
before you print,
String phone = rs.getString("CCU_PHONE");
if (phone == null || phone.isEmpty())
{
System.out.println("NULL");
}
else
{
System.out.println("phone" + phone);
}
Upvotes: 0
Reputation: 863
Try writing yor database query like this,here if the field value is null it will print the whatever value that you specified as second paramater within the braces
For Oracle
select nvl(CCU_PHONE,'null') from tablename
For Mysql
select ifnull(CCU_PHONE,'null') from tablename
Upvotes: 1