Thursday, 26 April 2018

Core Java: Conditional Control Statements

Syntax
Example
Flowchart
// if-then
if ( booleanExpression ) {
   true-block ;
}
if (mark >= 50) {
   System.out.println("Congratulation!");
   System.out.println("Keep it up!");
}
// if-then-else
if ( booleanExpression ) {
   true-block ;
} else {
   false-block ;
}
if (mark >= 50) {
   System.out.println("Congratulation!");
   System.out.println("Keep it up!");
} else {
   System.out.println("Try Harder!");
}

// nested-if
if ( booleanExpr-1 ) {
   block-1 ;
} else if ( booleanExpr-2 ) {
   block-2 ;
} else if ( booleanExpr-3 ) {
   block-3 ;
} else if ( booleanExpr-4 ) {
   ......
} else {
   elseBlock ;
}
if (mark >= 80) {
   System.out.println("A");
} else if (mark >= 70) {
   System.out.println("B");
} else if (mark >= 60) {
   System.out.println("C");
} else if (mark >= 50) {
   System.out.println("D");
} else {
   System.out.println("F");
}
  

// switch-case-default
switch ( selector ) {
   case value-1:
      block-1; break;
   case value-2:
      block-2; break;
   case value-3:
      block-3; break;
   ......
   case value-n:
      block-n; break;
   default:
      default-block;
}
char oper; int num1, num2, result;
......
switch (oper) {
   case '+': 
      result = num1 + num2; break;
   case '-': 
      result = num1 - num2; break;
   case '*': 
      result = num1 * num2; break;
   case '/': 
      result = num1 / num2; break;
   default:
      System.err.println("Unknown operator);
}



Braces: You could omit the braces { }, if there is only one statement inside the block. However, I recommend that you keep the braces to improve the readability of your program. 
For example,
 
if (mark >= 50)
   System.out.println("PASS");   // Only one statement, can omit { } but NOT recommended
else {                           // More than one statements, need { }
   System.out.println("FAIL");
   System.out.println("Try Harder!");
}


switch-case-default
 
"switch-case" is an alternative to the "nested-if". In a switch-case statement, a break statement is needed for each of the cases. If break is missing, execution will flow through the following case. You can use an int, byte, short, or char variable as the case-selector, but NOT long, float, double and boolean. (JDK 1.7 supports String as the case-selector).

Conditional Operator (? :)
 
A conditional operator is a ternary (3-operand) operator, in the form of booleanExpr ? trueExpr : falseExpr. Depending on the booleanExpr, it evaluates and returns the value of trueExpr or falseExpr.
 
Syntax
Example
booleanExpr ? trueExpr : falseExpr


System.out.println((mark >= 50) ? "PASS" : "FAIL");
max = (a > b) ? a : b;   // RHS returns a or b
abs = (a > 0) ? a : -a;  // RHS returns a or -a

No comments:

Post a Comment

Please write your view and suggestion....