ETOVE ETOVE - 1 month ago 11
Java Question

Unreachable Statement in my Public Boolean Method

So I'm trying to create an isValid method that verifies if a certain date is real or not (i.e. 3/31/2016 is valid, 2/29/2001 is valid since it's a leap year, 2/30/2016 is not valid)

Here is my method public boolean isValid()

`

{
//January
if (month == 1 && day <= 31) {
return true;
}
else {
return false;
}

//February
if (month == 2 && day <= 28) {
return true;
}
else {
if ((((year % 4) == 0) && ((year % 100) != 0)) || ((year % 400) == 0)) {
if (day == 29) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}

//March
if (month == 3 && day <= 31) {
return true;
}
else {
return false;
}

//April
if (month == 4 && day <= 30) {
return true;
}
else {
return false;
}

//May
if (month == 5 && day <= 31) {
return true;
}
else {
return false;
}

//June
if (month == 6 && day <= 30) {
return true;
}
else {
return false;
}

//July
if (month == 7 && day <= 31) {
return true;
}
else {
return false;
}

//August
if (month == 8 && day <= 31) {
return true;
}
else {
return false;
}

//September
if (month == 9 && day <= 30) {
return true;
}
else {
return false;
}

//October
if (month == 10 && day <= 31) {
return true;
}
else {
return false;
}

//November
if (month == 11 && day <= 30) {
return true;
}
else {
return false;
}

//December
if (month == 12 && day <= 31) {
return true;
}
else {
return false;

}

}


`

Now, when I compile, it says there are unreachable statements essentially wherever it says "if". Could somebody please help? I've already tried the 'if (true) {return}' method and I can't find anything else helpful.

Answer

In your first if statement, it returns regardless of outcome, meaning all the following if statements will never be reached as if your first condition is not met it will return, and if it is, it also returns.

A fix for this is to remove all your else return false paths and string all if statements in an else if chain and then return false at the end of that.

e.g.

if(){
    ...
}else if(){
    ...
}
return false;