0

So i was just wondering if there was actually a name for this if-statement:

public void checkEvenNumber(number) {
  return ((number % 2 == 0) ? true : false)
}

Or if it is just called an if-statement.

Jelloboy
  • 3
  • 3
  • 3
    Do you mean ternary operator? – mprabhat Nov 24 '14 at 20:09
  • It's a ternary. How it works is `?` is what you choose to do if `true` is returned. `:` is if the condition is false. Just make a note this won't work since you're returning a boolean in a void method. – Drew Kennedy Nov 24 '14 at 20:11
  • 1
    @mprabhat Just to be precise, this is not *the* ternary operator, but *a* ternary operator. It just happens that since Java doesn't have more ternary operators `condition ? option1 : option2` people tend to call it "ternary operator" instead of using its proper name which is "conditional operator". – Pshemo Nov 24 '14 at 20:27

5 Answers5

7

Yes. That's an example of a ternary operator.

JLS-15.25 Conditional Operator ? : describes it as,

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

It is called a terniary operator. However in this case, terniary operator isn't needed as the function it can be simplified to look like this:

public boolean isEvenNumber(int number) {
  return number % 2 == 0;
}

Please note that I changed the name of the function to match what it actually does.

C0D3LIC1OU5
  • 8,600
  • 2
  • 37
  • 47
0

You may also refer it as inline if statement

Here's a link for your reading up: http://en.wikipedia.org/wiki/%3F:

If you are familiar with how if-statements work in MS Excel, it shouldn't be too hard to understand.


By the way, your code should change to:

public void checkOddNumber(number) {
  return ((number % 2 != 0) ? true: false)
}
user3437460
  • 17,253
  • 15
  • 58
  • 106
0

The ternary operator, so-called as it has 3 components:

  1. The condition
  2. The expression returned if it's true
  3. The expression returned if it's false
Dexygen
  • 12,287
  • 13
  • 80
  • 147
0

that's a function (as i recognize it), you pass parameter(s) to it and it is passes it/them down to the function (where you do your stuff) and it returns only 1 variable.

bakriawad
  • 345
  • 2
  • 10