Reputation: 11
I was wondering why my variable would not return here:
public int getAge() {
int age;
if (currentMonth != birthMonth) {
if (currentMonth > birthMonth) {
age = currentYear - birthYear;
}
else {
age = currentYear - birthYear + 1;
}
}
if (currentMonth == birthMonth) {
if (currentDay >= birthDay) {
age = currentYear - birthYear;
}
else {
age = currentYear - birthYear + 1;
}
}
return age;
}
All variables such as currentMonth and birthMonth have been initialized, but I can't seem to get a return for the age.
Upvotes: 0
Views: 61
Reputation: 738
Be careful, you claimed that your variable was initialized on line 2 but that's not the case. The variable is declared here, but never initialized(outside of the if statements).
An IDE might tell you that age is unitialized, even if it's obvious that this function would run fine. The issue is that there's a possibility of it being uninitialized if both if statements weren't entered.
The solution in Erwin's answer is correct, you'll need to write an else instead of another if statement.
Upvotes: 2
Reputation: 31269
Although you have two mutually exclusive if
statements, that's not something the compiler can detect (it's not even allowed to do that according to the specification)
To make the compiler detect that the second block is always executed if the first one is not, rewrite your if
statements. Your code was:
if (currentMonth != birthMonth) {
// Block 1
}
if (currentMonth == birthMonth) {
// Block 2
}
Change this to:
if (currentMonth != birthMonth) {
// Block 1
} else {
// Block 2
}
Then the compiler will be able to detect that you're always initializing the variable age
.
Upvotes: 0
Reputation: 106430
If I don't enter any of those if
blocks, I don't have a satisfactory value for age
to be set to. Java sees this as a compile-time failure, since it can't guarantee that age
is going to be set by your program's execution flow.
Java isn't going to look at the conditional branches to see if they'll fire; it'll look at the conditional branches to see if there's a possibility that it won't. This is why your variable will not be initialized.
If you used an else
statement instead, since your condition only has two possible cases, then Java would be able to guarantee that a value for age
would be set via its execution flow.
public int getAge() {
int age;
if(currentMonth != birthMonth) {
if(currentMonth > birthMonth) {
age = currentYear - birthYear;
} else {
age = currentYear - birthYear + 1;
}
} else {
if(currentDay >= birthDay) {
age = currentYear - birthYear;
} else {
age = currentYear - birthYear + 1;
}
}
return age;
}
Upvotes: 0