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....