Example :If (radius >= 0)
{
area = radius * radius * PI;
System.out.println(“The area for the circle of radius “+ radius
+ “ is “ + area);
}
* When radius is bigger than 0 (>= 0) then the statement inside the block is executed.
* Statements which are going to be executed are marked with curly brackets. ( { … } ).
* Blocks aren’t needed when only one statement after “If”.
Example :
int number = Integer.parseInt(intString);
if (number % 2 == 0)
System.out.println(number + “ is even.”);
If (number % 2 != 0)
System.out.println(number + “ is odd.”);
If-else Statements
* “If” statement executes only one block when its condition is true.
* If-else statement is needed when executing blocks for both values (True or False).
* If-else statement is needed when executing blocks for both values (True or False).
Example:if (radius >= 0)
{
area = radius * radius * PI;
System.out.println(“The area for the circle of radius “ + radius +
“ is “ + area;
}
else
{
System.out.println(“Negative input”);
}
{
area = radius * radius * PI;
System.out.println(“The area for the circle of radius “ + radius +
“ is “ + area;
}
else
{
System.out.println(“Negative input”);
}
* If radius >= 0 is true then area is going to be calculated.
If false then “Negative Input” is going to be appear into console.
If false then “Negative Input” is going to be appear into console.
* Curly block in “else” can be deleted because it has only 1 statement.
Example :if (number % 2 == 0)
{
System.out.println(number + “ is even. “);
}
else
{
System.out.println(number + “ is odd. “);
}
* It is more efficient to write “number % 2 == 0” as “if” parameter’s because it is executed only once a time.
Switch-case statement
* “if” or “if-else” executes the block by its condition which are true or false.
* Switch-case executes block by its status.
* Switch-case is easier to understand than nested-if and usually be used for multiple-conditions.
* Switch-case executes block by its status.
* Switch-case is easier to understand than nested-if and usually be used for multiple-conditions.
* Switch-expression has to be in char, byte, short, or int and put inside parentheses (…).
* Value1, … , to valueN has to be in a same data type as Switch-expression
and can not be in mathematic expression like 1+x.
* If case is found then execution is started from the beginning of the statements
inside the case to the break statement.
* Break is optional in Switch-case statement.
* Default case is optional and it should be executed when no one of the cases apply .
* Cases are checked sequentially.
* Cases should be listed and default is placed at the last of it.
* Switch-case without break will execute the next case after the case.
* Default case is optional and it should be executed when no one of the cases apply .
* Cases are checked sequentially.
* Cases should be listed and default is placed at the last of it.
* Switch-case without break will execute the next case after the case.