Paul Paul - 4 months ago 9
Java Question

Variable declaration not allowed. But there is no scope overlap

When I fill an array of characters I get an error.

List<Character> letters = new ArrayList<>();
int i = 0;
if (i == 0) {
Character str = 'a';
letters.add(str);
} else if (i == 1)
Character str = 'b'; //Variable declaration not allowed here
letters.add(str);
}


Why does this error message appear? Cases i==0 and i==1 are mutually
exclusive. Why compiler doesn't allow me to decare str the second time?

Answer

Scope in not overlapping, this is correct. You are forgetting an opening curly bracket at else if line. This is just a typo that looks like

} else if (i == 1){ fixes a problem.

Your situation is distinctly different from JAVA Variable declaration not allowed here