[JAVA] Reference ternary operator

Hello. It is a trip to the vocational school world (self-proclaimed).

Recently, the reputation of the ternary operator is not good around me (?), So I would like to take this opportunity to tell you about the wonderfulness of the ternary operator.

What is a ternary operator in the first place?

As the name implies, a ternary operator is an operator consisting of three terms (expressions).

I have no body or lid, so I will explain it in more depth.

First, the ternary operator has the following format.

<Conditional expression> ? <Conditional expressionがtrueの場合の式> : <Conditional expressionがfalseの場合の式>

There may be symbols that you are not familiar with when writing programs here. Yes, it's the "? " Mark. This is called the ** conditional operator **, and it has the role of branching the process to the two items that follow "? " Depending on the conditional expression.

This makes it possible to dramatically refresh the processing described in the if statement. For example, suppose there is a scene where you want to switch the bool (Boolean) type variable flag alternately between true and false as follows.

if(flag)
{//If flag is true, set to false

	flag = false;
}
else
{//If flag is true, set to false

	flag = true;
}

It seems that it was long. However, if this is described using the ternary operator, it becomes like this.

flag ? false : true;

The processing that seemed to be so long is so refreshing! There was such a wonderful thing! It must be fine tomorrow!

I would like to say that, but it is not always so easy. Please see the following code.

int num = flag ? flag2 ? flag4 ? 1 : 2 : flag5 ? 3 : 4 : flag3 ? flag6 ? 5 : 6 : flag7 ? 7 : 8; 

How is it? Even with the convenient ternary operator, if you use it incorrectly, the readability will drop to the ground.

There is absolutely no such thing in the world. It's the same in programming. If you make a mistake in using useful tools, you will be back in the Stone Age. And it is none other than you reading this article who thinks about how to use the tool.

Think about where to use it and have a good development life.

Recommended Posts

Reference ternary operator
About the ternary operator
Is the ternary operator evil?
Kotlin has no ternary operator (conditional operator)
Java basic learning content 3 (operator / ternary operator)
How to write a ternary operator
Bocchi operator (&.)
How do you write the ternary operator (? :)
Self-assignment operator
Assignment to multiple variables with the ternary operator
Ruby conditional branch. if, conditional operator (ternary operator), unless, case
How much ternary operator is allowed in Java