Conditional operator '? :' is the shortcut of if-else statement, which assigns a value to a variable depending on specific condition is evaluated as only true or false. We use this operator when we need to evaluate a condition with only two possible values - true or false and returns the value of any data type depending on true or false condition. So, in the following example, condition is evaluated, if it is true the value1 is assigned to variable var, else value2 is assigned to variable var.
var v = (condition) ? value1 : value2;
is similar to
var v;
if(condition)
if(condition)
{ v = value1; }
else
{ v = value2; }
As I had the following example in the post If Else Statements, we can convert if-else statement there into the conditional operator '? :'
As I had the following example in the post If Else Statements, we can convert if-else statement there into the conditional operator '? :'
Class IfElse (IfElse.java)
public class IfElse { public static void main(String args[]) { int i = 10; if(i > 10) System.out.println("Greater"); else System.out.println("Less"); } }can be written as :
Class CondOperator1 (CondOperator1.java)
public class CondOperator1 { public static void main(String args[]) { int i = 10; String str = (i > 10) ? "Greater" : "Less"; System.out.println(str); } }Or you can write as following code :
Class CondOperator2 (CondOperator2.java)
public class CondOperator2 { public static void main(String args[]) { int i = 10; System.out.println((i > 10) ? "Greater" : "Less"); } }
No comments:
Post a Comment