if ((x = y + z) > 0) ...Here the expression (x = y + z) > 0 first assigns to x the value of y + z and then tests the result to see if it is positive. We sometimes refer to the assignment as a side-effect of the evaluation of the condition. Side-effects in programming, like side-effects in taking pharmaceutical drugs, are usually undesirable. Generally speaking, we recommend that expressions involving side-effects be avoided. For the given example, if you later choose to eliminate the if statement, you may inadvertently also eliminate the assignment. Usually it is best to write code that may be a little longer than is necessary in order to make your intentions clear. The example here could be replaced by
x = y + z; if (x > 0)...
if (x < 0); System.out.println("Value is negative");will always print the message "Value is negative", no matter what value x actually has. The problem here is the semi-colon at the end of the first line. Using our indentation scheme, Java interprets the fragment as
if (x < 0) ; System.out.println("Value is negative");The extra semi-colon is considered to be an empty statement which is executed if x is negative. This terminates the if statement. No matter what value x has, the statement that prints the message is executed.
if (value < 0) System.out.println("Negative value made positive"); value = -value;The indentation indicates that both statements should be executed if the condition is true but the compiler ignores indentation. Without brace brackets surrounding the two indented statements, the second one is not part of the if statement. The fragment will make negative values positive but it will also cause positive values to be made negative.
if (n = 5) ...where n is of type int. Inside the parentheses is an assignment, an expression whose type is that of the variable on the left side of the assignment. In the example shown here, the type of the assignment expression is int because n is of type int. Java, of course, is expecting a boolean expression (like n == 5). Since the type that it finds is not what it wants, it complains.
int m; int n In.getlnt(); if (n > 0) m = 1; else if (n == 0) m = 2; System.out.println(m);will, during compilation, produce the error message "variable m may not have been initialized". The problem here is that m will not be given a value if n < 0. Unfortunately, sometimes the compiler is a bit over-zealous in flagging possible errors of this type. For example, the fragment
int m; int n Math.abs(In.getlnt()); if (n > 0) m = 1; else if (n == 0) m = 2; System.out.println(m);will still produce the same message even though it is now impossible for n to be negative. The easiest way to get past this problem is to initialize m to zero where we declare it (in the first line of the fragment).
if (...) if (...) statement1 else statement2 else statement3tracing statements should be inserted at each of the points at which <statement1>, <statement2>, <statement3> are shown.
if (DEBUG) ...
|