Java has one special type of operator that is known as ternary operator.The symbol to which we can assign as ternary operator is ‘?’.That’s right,you all have used it into c/c++.It behaves same here also.We can say that its easy to use instead of if/else statement.When we use if/else statement ,there is mainly two possibilities of  required output.Ternary operator uses one single line of code to derive right answer.

So it’s better to use ternary operator when there are mainly two possibilities.






Syntax

Expression? Statement_1 : Statement_2



Here we will write the main condition instead of expression.From that expression there is two possibilities which points to either Statement_1 or statement_2.


Example of syntax

k=i>0? i : -i 

Here our condition is i>0.For value of i ,it can be true or false.If condition become true then first statement will execute and if condition is false then second statement will execute.By considering that condition we have to arrange our statement_1 and statement_2.


Click here for — If/else guide in java


Lets execute one simple example that can give you better idea about ternary operator.

Problem–>> Execute a program that finds the absolute value of any integer number using ternary operator.

Code–>>


class ternary{
public static void main(String args[])
{
int i=10;
int k;
k=i>0?i:-i;
System.out.println(“The absolute value of “+i+” is “+k);
i=-10;
k=i>0?i:-i;
System.out.println(“The absolute value of “+i+” is “+k);
}
}

Output–>> 

The absolute value of 10 is 10

The absolute value of -10 is 10


Logic–>> First we have created a main class which is by default public and is named as ‘ternary’.Inside main function we have declared a integer variable and initialized it’s value to 10.Now we have to find its absolute value .You know that absolute value of any positive integer number is positive and negative integer number is also positive.So we have written condition that describe that is it positive?.If yes, then it will execute first statement.Here we can see that value is 10 so it is positive and it will execute first statement.Now we have changed value to negative again it checks the condition and execute second statement because condition is false so.The value of statement 1 or statement2 goes inside the third variable and it prints the result.

By jigar

Leave a Reply

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