0

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.

Austin Schaefer
  • 695
  • 5
  • 19
  • 1
    Search for "ternary operator" – B001ᛦ Jul 11 '19 at 08:13
  • 1
    Which construct in that statement don't you understand? The modulo (`%`) operator or the ternary (`? :`) operator? – JonK Jul 11 '19 at 08:15
  • 3
    Possible duplicate of [Ternary Operators Java](https://stackoverflow.com/questions/21219695/ternary-operators-java) – dbl Jul 11 '19 at 08:16

4 Answers4

2

It is basically an if elsestatement.

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==0then it is Even. If not, then it is Odd.

It is a one-liner to:

if(num%2==0) return "Even";
else return "Odd";
M.K
  • 1,464
  • 2
  • 24
  • 46
2

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 :

AndreiMos
  • 21
  • 2
1

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";
    }
  }
rahul
  • 880
  • 3
  • 14
  • 25
1

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.

Yevgen
  • 1,576
  • 1
  • 15
  • 17