Colorado State University

CS160: Foundations in Programming: Summer 2016


If Statement 101


Variations

If Statement Variations

Examples

If statement

Form:
	if ( < condition > ) { < statements > }
The condition is a boolean expression and the statements includes anything that you want to execute.
Example:
int examScore = 70;

    if (examScore >= 70) { // no semicolon here!!!
        System.out.println("You passed the exam!");
    }
Is there any difference between the previous example and the next example?
int examScore = 70;

    if (examScore > 69) { // no semicolon here!!!
        System.out.println("You passed the exam!");
    }
Consider this code, are curly braces required?
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your age: ");
int age = keyboard.nextInt();
if (age == 21)
   System.out.println("You are 21 years old!");

if (age != 21) 
   System.out.println("You are NOT 21 years old!");

keyboard.close();

If - else statement

Form
        if ( < condition > ) { < statements > } 
        else { < statements > }
Examples
if (age == 21)
    System.out.println("You are 21 years old!");
else
    System.out.println("You are NOT 21 years old!");
Or very similarly:
if (age >= 21) 
    System.out.println("You are at least 21 years old!");
else
    System.out.println("You are less than 21 years old!");

If - else if - else statement

Form:
        if ( < condition1 > ) { < statements > } 
        else if ( < condition > ) { < statements > }
	else { < statements > }
Examples:
Does the following code cover all possible scores?
if (examScore == 100) 
    System.out.println("Excellent exam score, congratulations!");
else if (examScore == 0)
    System.out.println("Have you actually been attending this class?");
else if (examScore >= 70)
    System.out.println("Looks like you will be passing the class.");
else if (examScore < 69)
    System.out.println("You need a better score on the next exam!");
Here's code that covers all the bases
if (examScore == 100) 
    System.out.println("Excellent exam score, congratulations!");
else if (examScore >= 90)
    System.out.println("Excellent job, you received an A on the exam!");
else if (examScore >= 80)
    System.out.println("Nice job, you received a B on the exam.");
else if (examScore >= 70)
    System.out.println("Passing grade, you received a C on the exam.");
else if (examScore >= 60)
    System.out.println("Please study more next time!");
else 
    System.out.println("Not the outcome you want!");

© 2016 CS160 Colorado State University. All Rights Reserved.