Technical help

 IF and SWITCH Statements: How and When to Use Them

If statements are the simplest and easiest control flow statements to handle. The block of code after and if statement executes if and only if all the conditions contained in the if clause are met. Writing an if statement is very simple:

if(boolean)
{

//Code here executes *if* boolean value is TRUE

}

His boolean can be a variable or a method that returns a boolean.

--OR--

if(boolean expression)
{

//Code here executes the *if* boolean expression is true

}

Also note that if the expressions CANNOT be followed by semicolons if the conditional code block they represent is to execute correctly.

There are multiple ways to write code that follows an if-statement. If you only need to execute one line of code under a certain condition, then you do not need to use brackets to surround that code.

if(boolean)
      System.out.print("hello world");
      //Since only one line of code needs executing, I need not use brackets
but if i am declaring variable on that line then this code will not work because for variable scope is required so it gives compilation error.

However, it is good convention to use brackets, as whenever an if statement's code block contains more than two lines of code, brackets become necessary.

Notice that to test if one number is equal to another, you must use TWO equals signs.

For example, let's say you are comparing two integers, x and y. You may write a program like this:
int x = 10, y = 4;
 
   if(x < y)
   {
      System.out.print(x + " is less than " + y);
   }
 
   if(x == y) //Notice TWO equals signs, means "if x IS EQUAL to y"
   {
      System.out.print(x + " is equal to " + y);
   }
 
   if(x > y)
   {
      System.out.print(x + " is greater than " + y);
   }



If statements also allow for multiple tests to be performed in one clause. This can be done by using conditional operators. The most common conditional operators are:
&& AND - both conditions must be true
|| OR - at least one of the conditions must be true
^ XOR - ONLY one of the conditions may be true

These operators are placed between the two statements they are meant to evaluate.

1 comment:

  1. Nice and good article. It helps in handling tricky if conditions. Thank you for article.

    ReplyDelete