Ternary Operator Example in Java
A bit about the Ternary operator..The ternary operator is ?: This operator as said before works like if-else. If the condition is true then you can store a particular value in the variable if false some other value can be stored. An example will make you understand it clear.
boolean myFlag= (isTrue==true? true: false);
The syntax is,
value1 and value2 both should be of the same value type. In this case, if expression (condition) is satisfied then value1 is stored in value else value2 is stored. The above statement is much similar to.
I think you might have understood it. So let's walk into the example.
public static void main(String args)
Scanner s=new Scanner(System.in);
String st=(n>0? n+">0":n+"<0");
ExplanationUser gives an int value and that is stored in
n>0, then the value of st will become n+">0". Consider if
n=8, then st will become 8>0
n<0, then the value of st will become
n=-8, then st will become
-8<0. As the user gave 8 is input, this statement is not reached.