Title: if statement basics
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

If Statement Basics

Control Constructs

In the section we will cover if-then-else java statements.

if - then -else constructs:


if  (boolean_expression)
    statement;

// Anywhere we indicate statement;, we can also have more than one statment
// if we use braces.  In effect an opening brace followed by many statements
// and closed by an ending brace is treated like one "fat" statement

if (boolean_expression)
  {
     statement;
     statement;
  }

if (boolean_expression)
    statement;
 else
    statement;

if (boolean_expression)
    statement;
else  if (boolean_expression)
         statement;
else  if (boolean_expression)
         statement;
else statement;


More Concrete example

A boolean_expression must evaluate to a boolean, and a statement can be any legal java statement. Also as mentioned above, a statment can consist of multiple statements if surrounded by braces.


// More concrete example:
if (a == 1)
{
   x = x+1;
   y = y*2;
}
else
   z = 10;


// Other examples of expressions:
if (x != 10)
   Some Statement

if (x < 10)
   Some Statement

if (x <= 10)
   Some Statement

if (x > 10)
   Some Statement

if (x >= 10)


1. Basic IF Statement Program
2. ***Simple If statements .... use nextInt to read number and test with if
3. ***Demo operators ==, !=, <, >, <=, >=

Programs created on the video:


import java.util.Scanner;


public class IfExamples {


    public static void main(String[] args) {
        // if ( boolean_expression)
        //    statement
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter an integer: ");
        int x = keyboard.nextInt();
        int y;

        if (x == 10) {
            System.out.println("The value of x is 10");
            y = x;
            System.out.println(" y is now equal to 10");
        }
        else
            System.out.println("The value of x is NOT 10");

        if (x != 10)
            System.out.println("The value of x is NOT 10");
        else
            System.out.println("The value of x is 10");

        if (x >= 1)
            System.out.println(" The value is greater than or equal to 1");

        if ( x <= 5)
            System.out.println(" The values is less than or equal to 5");

        if ( x > 1)
            System.out.println(" The value is greater than 1");

        if ( x < 5)
            System.out.println(" The values is less than 5");


    }

}



Last Modified: July 19, 2013 2:39 PM