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:


if statement:
The syntax of the if statement in java is:

    if (testexpression)
{
// code
}
If the body of an if .... else statement has only one statement, you do not need to use brackets {}.
The if statement evaluates the test expression inside the parenthesis().
If the test expression is evaluated to true, statement inside the body of if statement is executed.
If the test expression is evaluated to false, statement inside the body of if statement is not executed.

Comments

Popular posts from this blog

Introduction on OOPs