Java Programming Tutorial Index

Java Fundamentals

The Java Conditional Operator selects one of two expressions for evaluation, which is based on the value of the first operands. It is also called ternary operator because it takes three arguments.



The conditional operator is used to handling simple situations in a line.

Syntax:

expression1 ? expression2:expression3;

The above syntax means that if the value given in Expression1 is true, then Expression2 will be evaluated; otherwise, expression3 will be evaluated.

Example:

val == 0 ? you are right:you are not right;

Program to Show Conditional Operator Works

Example:

public class condiop {
 public static void main(String[] args) {
  String out;
  int  a = 6, b = 12;
  out = a==b ? "Yes":"No";
  System.out.println("Ans: "+out);
 }
}

Output:

Ans: No

In the above example, the condition given in expression1 is false because the value of a is not equal to the value of b.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram