Is it possible to have IF statements without braces in Java, e.g:
if (x == y) z = x * y; else z = y - x;
It’s possible in PHP, and I’m not sure if I’m doing something wrong.
Clarification: Here’s my actual code that i’m using:
if (other instanceof Square) Square realOther = (Square) other; else Rectangle realOther = (Rectangle) other;
But i got errors like ‘Syntax token on realOther , delete this token’ and ‘realOther cannot be resolved’ among others.
What am I doing wrong?
Yes, you can follow an
ifstatement with a single statement without using curly braces (but do you really want to?), but your problem is more subtle. Try changing:to:
Some languages (like PHP, for example) treat any non-zero value as true and zero (or
NULL,null,nil, whatever) asfalse, so assignment operations in conditionals work. Java only allows boolean expressions (expressions that return or evaluate to a boolean) inside conditional statements. You’re seeing this error because the result of(x=y)is the value ofy, nottrueorfalse.You can see this in action with this simple example:
The first statement will cause compilation to fail because
1cannot be converted to a boolean.Edit: My guess on your updated example (which you should have put in the question and not as a new answer) is that you are trying to access
realOtherafter you assign it in those statements. This will not work as the scope ofrealOtheris limited to theif/elsestatement. You need to either move the declaration ofrealOtherabove yourifstatement (which would be useless in this case), or put more logic in yourifstatement):To assist further we would need to see more of your actual code.
Edit: Using the following code results in the same errors you are seeing (compiling with
gcj):Note that adding curly braces to that
if/elsestatement reduces the error to a warning about unused variables. Our own mmyers points out:Also note that my other example:
compiles without error.
Edit: But I think we have established (while this is an interesting dive into obscure edge cases) that whatever you are trying to do, you are not doing it correctly. So what are you actually trying to do?