How to use the ternary operator? (Java)

As a beginner, when exposed to a large amount of mature code, there will always be doubts. What's this? How come I haven't seen it. This thing is commonplace. So today, let's take a look at what the ternary operator is and how to use it?

First of all, the meaning of the ternary operator is to use it as a judgment statement

Similar to an if-else statement

Therefore, the only thing that bothers us is his usage.

First of all, we assume a condition, for example: Have I learned Java? Set a variable, if the variable is 1, it means I have learned it, and if the variable is 0, it means I have not learned it.

Then we can first use an if-else statement to write

String 学会Java = null;
//...
//...
if (value==0){
    学会Java = "学会了!";
}else{
    学会Java = "还没学会";
}

So how do you express it with the ternary operator? First we need to understand his syntax:

Key points: Syntax (syntax)

Judgment condition? Result 1: Result 2

string 学会Java = (value==1) ? "学会了!" : "还没学会";
//我们不难看出学会Java等于的是后边冒号两边的东西,而后面的条件则是Java=后面接的满足条件的情况

That is, when our value is equal to 1, learn Java = "learned", otherwise it means not yet learned.

Alright, that's it for the ternary operator, and that's the end of co-learning time for today!

Guess you like

Origin blog.csdn.net/Harvery_/article/details/125127968