简体   繁体   中英

How does the ternary operator work

I don't understand this code;

Can someone write it proper so I can also understand.

public void deleteStudentsPersistence(Student student) {
        em.remove(em.contains(student) ? student : em.merge(student));
    } 

The operator you used there is called a ternary operator and it works almost the same way an if-else statement works. Consider the statement below:

int min = (a < b) ? a : b;

What this means is: Evaluate the value of (a < b) , if it's true, the value of min is a , otherwise, the value of min is b . It can be related to the if-else statement this way: If (a < b) is true: min = a; else: min is b.

Back to your question now....

em.remove(em.contains(student) ? student : em.merge(student));

This means if em.contains(student) is true, then perform em.remove(student) , however if it's false, then perform em.remove(em.merge(student)) .

PS:

Obviously, in many practical cases that involve giving a variable a value based on a two-way condition, this can be a subtle replacement for if-statement. There is great argument about the "more efficient" method as seen in this post but I personally prefer to use the ternary operator because of it's relatively short syntax length and readability.

I hope this helps.. Merry coding!

this is a ternary operator, called conditional operator. it could also be written this way:

public void deleteStudentsPersistence(Student student) {
        if (em.contains(student)){
        em.remove(student);
        } else{
        em.remove(em.merge(student));
        }
    } 

basically, it check if em contains the student before removing, otherwise it merge it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM