The simplest
conditional statement is the simple if statement. An if statement
defines a code block (the if block) and a conditional (or Boolean)
statement. The code block executes
once only if the condition evaluates to true. If it’s not true, Java skips over the if block and executes the first statement following
the if block. The schematic
to the right illustrates the flow of execution of a simple if statement. As an
example, let’s consider a program that prompts the user to enter a decimal
value. If the value entered is less
than zero, the program will display the message “You entered a negative
value.” Before terminating, the
program will display the message “Done.”
Here’s what the code would look like: import java.util.Scanner; public class Conditionals1 { public
static void main(String[] args) { Scanner
s = new Scanner(System.in); System.out.print(“Enter a number: “); double
num = s.nextDouble(); //
execute block only if num is negative if
(num < 0.0) { System.out.println(“You entered a negative value.”); } // the following statement
will execute regardless of the // value entered System.out.println(“Done.”); } } |