1-line IF statements in java
A statement not-belonging to the block may be included in it later by mistake (I add new statements to the block, so I need to add braces, but because of indentation or similar visual effects I also include a statement that should be left out of the block). Question: When reviewing code, I prefer to read statements that explicitly demonstrate that a fork in code execution may occur: When scanning hundreds of lines of the nonindented version, it is not obvious that a conditional may or may not occur:
1-line IF statements in java
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.
Yes, you can follow an if statement with a single statement without using curly braces (but do you really want to?), but your problem is more subtle. Try changing:
Some languages (like PHP, for example) treat any non-zero value as true and zero (or NULL , null , nil , whatever) as false , 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 of y , not true or false .
You can see this in action with this simple example:
if (1) System.out.println("It's true"); if (true) System.out.println("It's true");
The first statement will cause compilation to fail because 1 cannot 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 realOther after you assign it in those statements. This will not work as the scope of realOther is limited to the if / else statement. You need to either move the declaration of realOther above your if statement (which would be useless in this case), or put more logic in your if statement):
if (other instanceof Square) ((Square) other).doSomething(); else ((Rectangle) other).doSomethingElse();
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 ):
public class Test < public static void Main(String [] args) < Object other = new Square(); if (other instanceof Square) Square realOther = (Square) other; else Rectangle realOther = (Rectangle) other; return; >> class Rectangle < public Rectangle() < >public void doSomethingElse() < System.out.println("Something"); >> class Square < public Square() < >public void doSomething() < System.out.println("Something"); >>
Note that adding curly braces to that if / else statement reduces the error to a warning about unused variables. Our own mmyers points out:
http://java.sun.com/docs/books/jls/third_edition/html/statements.html says: «Every local variable declaration statement is immediately contained by a block.» The ones in the if statement don’t have braces around them, therefore they aren’t in a block.
Also note that my other example:
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?
The following code is legal:
int x = 5; int y = 2; int z = 0; if (x == y) z = x * y; else z = y - x;
As Sean Bright mentioned, your problem is that you are trying to test a non-boolean expression. You should be using the == operator instead of the = operator in your if clause.
Another thing to mention is that it is considered, by many, bad practice to skip using the curly braces in an if-then-else statement. It can lead to errors down the road, such as adding another statement to the body of the if or else code blocks. It’s the type of bug that might be a pain to figure out.
This isn’t really an issue when using an if-else statement, because Java will catch this as a syntactic error ( else statement without a preceding if ). However, consider the following if statement:
Now, suppose later on you need to do more things if x == y . You could easily do the following without realizing the error.
if (x == y) z = y * x; w = x * y - 5;
Of course, the second statement w = x * y — 5 will be executed regardless of the outcome of the if statement test. If you had curly braces to begin with, you would have avoided the problem.
Always consult the Code Conventions for the JavaTM Programming Language:
Specifically, see Chapter 7, Section 4:
Note: if statements always use braces <>. Avoid the following error-prone form:
if (condition) //AVOID! THIS OMITS THE BRACES <>! statement;
If you want a one liner if that is an expression you can use the terniary operator
final int myVal = predicate ? consequent : alternative;
which is roughly the same as
final int myVal; if(predicate) myVal = consequent; else myVal = alternative;
Short form for Java if statement, Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, . Using the conditional operator you can rewrite the above example in a single line like this:
What’s Java standard for single line if statement?
Which of the below format is JAVA standard for a single line IF-Statement? Please provide me the JAVA reference as well to support the argument. Thanks.
if (counter == 10) response.redirect("www.google.com");
From the old Java Code Conventions, it is the second.
Exact piece of the document: 7. Statements. 7.4 if, if-else, if-else-if-else Statements (page 12):
The if-else class of statements should have the following form
if (condition) < statements; >if (condition) < statements; >else < statements; >if (condition) < statements; >else if (condition) < statements; >else if (condition)
Note: if statements always use braces <> . Avoid the following error-prone form:
if (condition) //AVOID! THIS OMITS THE BRACES <>! statement;
After that and since the Java Code Conventions are really old (since 1997), this falls into a personal matter/taste due to code readability. IMO the second is just fine.
As per the Java Code Conventions (http://www.oracle.com/technetwork/java/codeconventions-150003.pdf, Chapter 7.4):
if statements always use braces <>. Avoid the following error-prone form:
if (condition) //AVOID! THIS OMITS THE BRACES <>! statement;
Conditional — 1-line IF statements in java, Secondary problem, Java is strongly typed. Even if it might allow syntax like you are saying, right after this if statement, it has to have an absolute final type for realOther. Your if statement would completely break java’s brain because it wouldn’t know if realOther was supposed to be treated as a rectangle …
When to use single-line if statements?
When reviewing code, I prefer to read if statements that explicitly demonstrate that a fork in code execution may occur:
When scanning hundreds of lines of the nonindented version, it is not obvious that a conditional may or may not occur:
boom += 1; baz = getBaz(boom); if (isFoo(baz)) runBar(); boing = boom + baz;
So when is it considered all right to single-line if statements? I’m willing to put up with it if the conditional is on a die(), return, or exception, because in those cases at least the current method ends.
if (isFoo(baz)) die("No more foo!");
Are there any other «good» uses for single-line if statements? How strictly should the practice be avoided? Note that I am explicitly asking about the lack of an indented line to indicate that a condition may or may not occur, I am not asking about the use of braces. Although I would appreciate all opinions in the comments, answers should address objective reasoning, such as maintainability or extensibility of code.
This is not a dupe of Single statement if block — braces or no because this question does not ask about braces. This is not a dupe of Single Line Statements & Good Practices because that question does not address the crux of this question: the ability to determine that some lines of code may or may not be run, thus leading to divergent code paths.
The only time to use a single-line if statement is when you have a lot of them and you can format your code to make it very clear what is happening. Anything else is not clear and will lead to errors.
is terrible. When mixed in with other code, it does not clearly show the conditional statement, and some people will confuse the following line as a badly-indented conditional. This applies to all statements, especially if they are die(), return or throw. It has nothing to do with the running of the code, its all about the readability.
if (a) do_a(); if (b) do_b(); if (c) do_c();
this is much better than putting the conditionals on the next line as its clearer what is intended, there is no scope for confusion.
I always prefer the version with braces.
- If I don’t always use the braces, then I may forget to put them when there is more than one statement in the block.
- IDEs used by other team members can reformat the code automatically to move the statement to the new line, thus making it much more error prone in the future.
- Merging the code across the branches is more error prone if the if statement is a conflicting spot. The probability for error is even higher if the person doing the merge is not completely familiar with the merged changes.
- A statement not-belonging to the block may be included in it later by mistake (I add new statements to the block, so I need to add braces, but because of indentation or similar visual effects I also include a statement that should be left out of the block).
I would propose an alternative answer. I prefer single liners when the condition inside is really a single line and is relatively isolated from the rest of the conditions.
One great example is:
public void DoSomething(int something) < // Notice how easily we can state in one line that we should exit the method if our int is 0. if(something == 0) return; CallAnotherMethodHere(something); >
A bad example(in my opinion) would be what @gbjbaanb mentioned:
if (a) do_a(); if (b) do_b(); if (c) do_c();
To me, this is a switch statement and should be written as such:
Much more readable IMHO and more efficient as variable needs to be evaluated only once VS running through all the if statements although gains are negligible.
Ways to simplify an if-statement in Java, So the basic idea is that the if statement happens when either of the conditions is true (In my case, both conditions cannot be true at the same time). However, once inside the if statement, there is a point where if the first condition is true, print «Thank» and execute Task Alpha and Beta. If the second condition is …