Reputation: 35
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;
}
Upvotes: 1
Views: 1159
Reputation: 322
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;
}
Upvotes: 1
Reputation: 7511
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.
Upvotes: 3