This question I found on my class work and I got confused
I haven't tried anything
public static String evenOrOdd(int num) {
return num%2==0?"Even":"Odd";
}
The code runs fine; I just wanna know how it works.
This question I found on my class work and I got confused
I haven't tried anything
public static String evenOrOdd(int num) {
return num%2==0?"Even":"Odd";
}
The code runs fine; I just wanna know how it works.
It is basically an if else
statement.
If the condition is true, it will return the first option. If not (if it is false), it will return the second:
num%2==0?"Even":"Odd";
If num%2==0
then it is Even
. If not, then it is Odd
.
It is a one-liner to:
if(num%2==0) return "Even";
else return "Odd";
Ternary operator is just like if else
statement.
if (num % 2 == 0) {
return "Even";
} else {
return "Odd";
}
If the part before ?
mark is true
then you will get the result before :
.
If false
then after :
look for ternary operator above code is short form of
public static String evenOrOdd(int num) {
if(num%2==0){
return "even";
}else{
return "Odd";
}
}
This is called a ternary operator and its logic works as follows
a question ? positive answer : negative answer
or, using more formal terms
boolean expression ? return value for true : return value for false
So, your question is about num % 2 == 0
which means if a remainder for the num
divided by two is zero. If this is the case – it's an even number, if not – it's an odd number, and that is why a corresponding string value is returned.