Friday, January 25, 2013

The IF Statement


if(condition) {
    statement 1;
    statement 2;
    statement n;
}
The if statement allows you to conditionally perform some commands. It allows you side-step the main flow of your code. If you remember the flowcharting symbols, when you see the diamond shape, it means you have a fork in the road. When a condition is met, you either go left or right. That is what the if statement does. It allows you to test for conditions. When the condition is true, you go to the beginning of the if block (the opening curly brace) and begin executing all the statements there until all the statements are exhausted. When you have reached the end of the block (the closing curly brace), then there are no more commands to execute. The flow of control will resume immediately after the end of the curly brace.
The condition in the if statement can be written as expressions that will evaluate to either true or false. This is the most common use you will have of the if statement. On some occassions, you may see the condition written as the literals true or false -- this is rare, but it will still be a legal code.

A possible gotcha on the if statement

int i = 0;
if(i = 1) {
    System.out.println("but i is equal to one");
}
If you have coded in C before, you might fall into this gotcha. Do not worry though, Java will not allow you to make a mess like this. This will be caught by the compiler.
The reason that the gotcha code above is not legal is because i = 1 is not a boolean expression. It is an assignment operation. Java requires that the condition evaluate to either true or false.

Nested if statements

You can put an if statement inside another if statement. You can in fact nest them up pretty deeply. While there is no set limit on how deep you can nest if statements, practical considerations and code readability should knock some sense into your code.
From my experience, whenever I am treading dangerously deep into a web of if-else-if-else … I usually take a step back and look if there are other ways of going about routing the program flow. It could be a design or analysis problem already and that using the if-else statement is not the right tool to solve the problem at hand.





Call me and you will get the knowledge and skills you need instantly.

For inquiries contact me on my mobile number or email me at inquiry@eglobiotraining.com. View my multiply site http://erwinglobio.multiply.com
Prof. Erwin M. Globio, MSIT
Senior IT Lecturer
Far Eastern University
Email Address: inquiry@eglobiotraining.com
Skype: erwinglobio
Call Now:
SMART: 09393741359
SUN: 09323956678

No comments:

Post a Comment