Javatpoint Logo
Javatpoint Logo

Three-way operator | Ternary operator in Java

The one and only conditional operator that accepts three operands is the three-way operator in Java. Java programmers frequently use it as a one-line alternative to the if-then-else expression. The ternary operator can be used in place of if-else statements, and it can even be used to create switch statements with nested ternary operators. The conditional operator uses less space and aids in writing if-else statements as quickly as possible even if it adheres to the same algorithm as an if-else statement.

Syntax:

If operates similarly to an if-else statement in that Expression2 is performed if Expression1 seems to be true and Expression3 is then executed in the event that Expression1 is false.

Example:

n1 = 1;n2 = 2;result = (n1>n2) ? (n1*n2):(n1+n2)Since n1<n2, the second operation gets performed. That is,result = n1+n2 = 3The output will be 3.

Example 1:

ThreewayOperatorExpl.java

Output:

Three-way operator | Ternary operator in Java

Time Complexity is: O(1)

Auxiliary Space is: O(1)

Example 2:

ThreewayOperatorExpl1.java

Output:

Three-way operator | Ternary operator in Java

Time Complexity is : O(1)

Auxiliary Space is : O(1)







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA