Conditional Operators
Conditional Operators-->
Conditional Operators return one value if condition is true and returns another value if condition is false. This operator is also called ternary operator.
Syntax:
class ConditionalDemo {
public static void main(String []args) {
int value1 = 1;
int value2 = 2;
int result;
boolean somecondition = true;
result = somecondition?value1:value2;
System.out.println(result);
}
}
The syntax of ternary operator is testCondition?expression1:expression2;
The testCondition is a boolean expression that results in either true or false.
If the condition is:
true: expression1 (before the colon) is executed.
false: expression2 (before the colon) is executed.
The ternary operator takes 3 operands (condition, expression1 and expression2). Hence the name ternary operator.
import java.util.Scanner;
class ConditionalDemo {
public static void main(String []args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the age: ");
int a = sc.nextInt();
if(a>18){
System.out.println("You are eligible for voting");
}else{
System.out.println("You are not eligible for voting");
}
}
}
Output:
The syntax of the if statement in java is:
Comments
Post a Comment