Ternary Operators In Java Example

Chapter: Operators Last Updated: 15-07-2016 14:07:16 UTC

Program:

            /* ............... START ............... */
                
public class JavaTernaryOperatorExample {
	public static void main(String args[]) {
		int i, k;
		i = 10;
		k = i < 0 ? -i : i; // get absolute value of i
		System.out.print("Absolute value of ");
		System.out.println(i + " is " + k);
		i = -10;
		k = i < 0 ? -i : i; // get absolute value of i
		System.out.print("Absolute value of ");
		System.out.println(i + " is " + k);
	}
}
                /* ............... END ............... */
        

Output

Absolute value of 10 is 10
Absolute value of -10 is 10

Notes:

  • Ternary Operators commonly referred to as the conditional operator
  • eg : minVal = (a < b) ? a : b
  • Java ternary operator let's you assign a value to a variable based on a boolean expression either a boolean field, or a statement that evaluates to a boolean result.

Tags

Ternary Operators, Java

Similar Programs Chapter Last Updated
Java Left Shift Operator Operators 04-09-2018
Java Addition Operator Operators 18-05-2017
Java Right Shift Operator Operators 13-12-2016
Prefix Operator In Java Example Operators 19-06-2016
Logical Operators In Java Example Operators 17-06-2016
Operator Precedence In Java Examples Operators 17-06-2016
Relational Operators In Java Example Operators 11-06-2016
Modulus Operators In Java Example Operators 15-07-2016
Increment And Decrement In Java Example Operators 15-07-2016
Boolean Operator In Java Example Operators 15-07-2016
Bitwise Operator In Java Example Operators 16-06-2017
Assignment Operation In Java Example Operators 06-04-2016
Arithmetic Operation In Java Example Operators 11-06-2016

1