if
Statements
The most basic way to test a condition in Java is by using an if
statement. The if
statement tests whether a condition is true or false and takes action only if the condition is true.
You use if
along with the condition to test, as in the following statement:
if (account < 0) { System.out.println("Account overdrawn; you need a bailout");}
The if
statement checks whether the account
variable is below 0 by using the less than operator <
. If it is, the block within the if
statement is run, displaying text.
The block only runs if the condition is true. In the preceding example, if the account
variable has a value of 0
or higher, the println
statement is ignored. Note that the condition you test must be surrounded by parentheses, ...
Get Sams Teach Yourself Java™ in 24 Hours, Sixth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.