You are on page 1of 7

28/03/2011

Control Flow Statements


Dr. Alberto Mndez Torreblanca

The if-then and if-then-else Statements


The if-then statement is the most basic of all the control flow statements. The basic format of an if statement is as follows:
If It is True

if (booleanExpression) { System.out.println("Inside if statement"); }


The expression in parentheses must evaluate to a boolean true or false result.

28/03/2011

The if-then and if-then-else Statements


If It is True

if (x > 3) { System.out.println("x is greater than 3"); } If It is False else { System.out.println("x is not greater than 3"); }

The if-then and if-then-else Statements


if (x > 3) { y = 2; } z += 8; a = y + x;

28/03/2011

The if-then and if-then-else Statements


if (x > 3) y = 2; z += 8; a = y + x;

The if-then and if-then-else Statements


int y = 5; int x = 2; if ( (x > 3) && (y < 2) ){ System.out.print("true"); }

28/03/2011

The if-then and if-then-else Statements

boolean boo = false; if (boo = true) { System.out.println(True); }

The if-then and if-then-else Statements


int x = 3; if (x = 5) { System.out.println(True); }

28/03/2011

The if-then and if-then-else Statements


if (result >=0) if (result > 0) System.out.println("positive"); else System.out.println("negative");

The if-then and if-then-else Statements


if (result >=0) if (result > 0) System.out.println("positive"); else System.out.println("negative");

28/03/2011

The if-then and if-then-else Statements


class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } }

The if-then and if-then-else Statements


int x = 3; if(x == 1) { System.out.println("x equals 1"); } else if(x == 2) { System.out.println("x equals 2"); } else if(x == 3) { System.out.println("x equals 3"); } else { System.out.println("No idea what x is"); }

28/03/2011

The if-then and if-then-else Statements


int x = 3; if(x == 1) { System.out.println("x equals 1"); } else if(x == 2) { System.out.println("x equals 2"); } else if(x == 3) { System.out.println("x equals 3"); } else { System.out.println("No idea what x is"); }

You might also like