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.
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.
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.
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.
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)
}
The ternary operator, so-called as it has 3 components:
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.