Java ternary operator
In this chapter you will learn:
- How to use the ternary ? Operator
- Syntax for Java ternary operator
- Example - Java ternary operator
- Example - obtain the absolute value of a variable.
Description
The ?
operator is a ternary (three-way) operator.
Java ternary operator is basically a short form of simple if statement.
Syntax
The ?
has this general form:
expression1 ? expression2 : expression3
expression1
can be any expression that evaluates to a boolean
value.
If expression1
is true
, then expression2
is evaluated.
Otherwise, expression3
is evaluated.
The expression evaluated is the result of the ?
operation.
Both expression2
and expression3
are required to return the same type,
which can't be void.
Example
Here is an example of ?
operator:
public class Main {
public static void main(String[] argv) {
int denom = 10;
int num = 4;//from w ww. j a v a2 s . co m
double ratio;
ratio = denom == 0 ? 0 : num / denom;
System.out.println("ratio = " + ratio);
}
}
The output:
Example 2
Here is another program that demonstrates the ?
operator.
It uses it to obtain the absolute value of a variable.
public class Main {
public static void main(String args[]) {
int i, k;/*w w w.j a v a 2 s. c o m*/
i = 10;
k = i < 0 ? -i : i;
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i;
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
The output generated by the program is shown here:
Next chapter...
What you will learn in the next chapter:
- What is Java If Statement
- Syntax for Java If Statement
- Example - for Java If Statement
- Example - If statement and comparison operators
- Example - If statement and single boolean variable