You can use an initializer only in a declaration.
Recall that a declaration does the following:
int x ;Here's a declaration with an initializer.
int x = 10 ;We used a literal 10 of type int. However, we can now use any int expression.
In fact, we could even use a double expression or types that Java knows how to handle. (For example, Java chops off or truncates the value to make an int).
Generally speaking, you should initialize a variable with an expression that has the same type as the variable. Thus, you should initialize an int variable with an int expression, a boolean variable with a boolean expression, etc.
int x = 10, y, z = x + 2 ;In particular, we can initialize z with the evaluation x + 2 since x was declared before z. A variable, foo, is declared before another variable, bar, if foo appears to the left of bar in the same declaration, or foo appears in a different declaration on some previous line (within a scope---we'll have to explain scope later on).
On the other hand, the following is illegal.
int x = z + 2, y, z = 10 ;x is initialized to the evaluation of z + 2, but z isn't declared until the end of the line. Java processes declarations line by line, left to right. Thus, it sees x being declared, then y, then z. It doesn't see z at the time x is being initialized, so there's an error.