Conditional Operators in Java

The conditional operator is used to make decisions in java programming. If the conditional expression returns true, then the program will take the main path, otherwise the program will execute in the alternate path.

Syntax 

expression1 ? expression2 : expression3

In the above code, the expression1 is evaluated first.

If the expression 1 returns true as an output, then it will evaluate the expression2. The outcome of the conditional operator is the output of expression2.

If the expression 1 returns false as an output, then it will evaluate the expression3. The outcome of the conditional operator is the output of expression3.

Example

a==0 ? "main path" : "alternate path"


Program using Conditional Operator

package com.yawintutor;

public class ConditionalOperator {
	public static void main(String[] args) {
		int a = 6;
		int b = 2;
		int c = 3;

		System.out.println("a value is " + a);
		System.out.println("b value is " + b);
		System.out.println("c value is " + c);
		
		int d = 0; 
		d = (a == 6 ? b : c);
		System.out.println("\n(a == 6) condition returns true.  value of b is assigned " + d);

		int e = 0; 
		e = (a == 5 ? b : c);
		System.out.println("\n(a == 5) condition returns false. value of c is assigned " + e);

	}
}

Output

a value is 6
b value is 2
c value is 3

(a == 6) condition returns true.  value of b is assigned 2

(a == 5) condition returns false. value of c is assigned 3

In the above example first conditional operator returns with true, second conditional operator returns with false which takes alternate path.



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *