xhtml
 

One Liners

If the "then" part or the "else" part of an if statement is a single statement which will fit on the same line as the test, then you can do that and leave out the brackets. For example:

if (n == 0)
{
   System.out.println("n is zero");
}
else
{
   System.out.println("n is nonzero");
}

can also be written in any of these three ways:

if (n == 0) System.out.println("n is zero");
else
{
   System.out.println("n is nonzero");
}



if (n == 0)
{
   System.out.println("n is zero");
}
else System.out.println("n is nonzero");



if (n == 0) System.out.println("n is zero");
else System.out.println("n is nonzero");

In fact, the multiple if convention we looked at earlier is an example, of this, where the else part of the first if is a single statement which happens to be another if. It is only the first line of the second if which fits on the else line, not the whole statement, but this doesn't cause any problems.


Back