10x Blogs Directory

Friday, March 6, 2009

if - Statements

  • if Statements are Decision control structures
    -Java statements that allows us to select and execute specific blocks of code while skipping other sections
  • Types:
    -if-statement
    -if-else-statement
    -If-else if-statement
  • if-statement
    -specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true.
  • if-statement has the form:if( boolean_expression )statement; or if( boolean_expression ){ statement1; statement2; }
    -where,
  • boolean_expression is either a boolean expression or boolean variable.
  • Eg -
  • int grade = 68;
  • if( grade > 60 )
  • System.out.println("Congratulations!");


Coding Guidelines

  • The boolean_expression part of a statement should evaluate to a boolean value. That means that the execution of the condition should either result to a value of true or a false.
  • Indent the statements inside the if-block.
    For example,
    if( boolean_expression )

{ //statement1;

//statement2;
}

if-else statement

  • if-else statement
    -used when we want to execute a certain statement if a condition is true, and a different statement if the condition is false.
  • if-else statement has the form:

if( boolean_expression )

{ statement1;

statement2; . . . }

else

{ statement3;

statement4; . . .}

  • Example:

int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");
else
System.out.println("Sorry you failed");

Coding Guidelines

  • To avoid confusion, always place the statement or statements of an if or if-else block inside brackets {}.
  • You can have nested if-else blocks. This means that you can have other if-else blocks inside another if-else block.
  • For example,
    if( boolean_expression ){

if( boolean_expression )

{ //some statements here }
}
else{ //some statements here
}


if-else-else if statement

  • The statement in the else-clause of an if-else block can be another if-else structures.
  • This cascading of structures allows us to make more complex selections.
  • The statement has the form:

if( boolean_expression1 )

statement1;

else if( boolean_expression2 )

statement2;

else statement3;

  • Example


int grade = 68;
if( grade > 90 ){
System.out.println("Very good!");
}
else if( grade > 60 ){
System.out.println("Very good!");
}
else{
System.out.println("Sorry you failed");
}

Common Errors

  • The condition inside the if-statement does not evaluate to a boolean value. For example,

//WRONG

int number = 0;

if( number )

{ //some statements here }

The variable number does not hold a boolean value

  • Writing elseif instead of else if.

    Using = instead of == for comparison.

For example,

//WRONG

int number = 0;

if( number = 0 )

{ //some statements here }

This should be written as,

//CORRECT

int number = 0;

if( number == 0 )

{ //some statements here}

No comments:

Post a Comment