Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an efficient if/else in Java?

I'm trying to return a different value using a simple if/else to check for an even number in Java.

if (move % 2 == 0) {
    return "o";
} else {
    return "O";
}

I know in JavaScript you can use

if () : a ? b ;

Can this be used in Java?

like image 873
Aaron Avatar asked Mar 02 '26 10:03

Aaron


2 Answers

Yes, you can use the ternary operator in Java:

return (move % 2 == 0) ? "o" : "O";

Just don't expect it to be any faster than the if-else.

like image 106
NPE Avatar answered Mar 04 '26 23:03

NPE


Yes, you can use the conditional operator in Java:

return (move % 2 == 0) ? "o": "O";

It won't make your program any faster, but it's a little more concise and if you are familiar with the conditional operator, you will probably find it easier to read.

But conversely, if you don't know this operator it will be hard to guess what the code does.

like image 28
Mark Byers Avatar answered Mar 04 '26 22:03

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!