Java Reference
In-Depth Information
false
true
if (condition){
}
FIGURE 2.7: The if construct.
in each other. Using the above trick and avoiding the else part altogether is preferred when
possible.
In general, it is not required to start a new block after an if statement. For example,
here is perfectly valid Java code.
if (z == x y)
System. out . println ( "Congratulations!" );
return ;
System. out . println ( "You need more practice" );
However, this code is not equivalent to the previous snippet of code and does not ac-
complish our goal. Since the braces are missing, the if statement is applied only to the
first statement that follows. Therefore, the return statement will always be executed (re-
gardless of whether z = x
y )andthelastlineofcodebecomesunreachable.Itisgood
software practice to always create a block after an if statement by typing opening and
closing braces. This will eliminate mistakes as shown above. Another common mistake by
novice programmers is to add a semicolon after an if statement. Consider the following
code snippet.
if (z == x y);
{ System. out . println ( "Congratulations!" );
return ;
System. out . println ( "You need more practice" );
The semicolon will terminate the if statement. The code will print Congratulations!
and exist the program regardless of the value of the condition inside the if statement.
Therefore, it is a good idea to put the opening brace at the same line as the if statement
to remind us that we should never put a semicolon after an if statement.
Always crate a new block after an if statement. Never put a semicolon after an
if statement.
Below is a listing of our program. Run it and make sure it works correctly. Remember
to run it several times. Note that testing a program that generates random numbers is a
little tricky. You can get different data every time you run the program.
import java . util . ;
public class Arithmetic {
public static void main(String [] args)
{
 
Search WWH ::




Custom Search