Invalid java syntax using ternary operator

127 Views Asked by At

I am implementing a stack using queues. My pop() function originally looked like:

public void pop(){
    queue1.isEmpty() ? queue2.poll() : queue1.poll();
}

This did not compile. What is wrong with this definition?

2

There are 2 best solutions below

0
On BEST ANSWER

You need to assign (or return) the Object you're polling. Something like

public void pop(){
    Object obj = queue1.isEmpty() ? queue2.poll() : queue1.poll();
}

or (what I think you really want) - something like

public Object pop(){
    return queue1.isEmpty() ? queue2.poll() : queue1.poll();
}

See also JLS-15.25. Conditional Operator ? :.

0
On

The conditional operator only works in an expression context. A statement is not an expression. In your case you need to use an if statement:

public void pop(){
    if (queue1.isEmpty()) {
        queue2.poll();
    } else {
        queue1.poll();
    }
}

If you are concerned about performance, then don't be. There is absolutely no performance penalty for using an if statement.