Firefly
Firefly

Reputation: 428

How does the Ternary Operator work in this piece of code?

I have a small piece of code of a function to set color that looks like this:

private Color color = Color.CYAN;

public void setColor(Color c) {
        color = c != null ?c :color;
        repaint();
    }

Does it means something like this?

color = c;
if (c != null) {
        color = c;
        } else {
        c = color;
}

I can't really wrap my head around this piece of code. Please enlighten me.

Upvotes: 1

Views: 53

Answers (1)

Kevin Anderson
Kevin Anderson

Reputation: 4592

It's more like

if (c != null) {
    color = c;
} else {
    color = color;
}

which, in turn, because color = color; essentially does nothing, is the same as:

if (c != null) {
    color = c;
}

Upvotes: 2

Related Questions