2

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));
    } 
Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
  • Feel free to accept my answer if it answer your question, or cemment it to ask more details otherwise – Kepotx Mar 22 '18 at 11:17

2 Answers2

4

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!

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
3

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

Kepotx
  • 1,095
  • 12
  • 26