# How to test for an odd/even number

• 04-14-2010, 08:01 PM
counterfox
How to test for an odd/even number
Hi I'm very new to java just trying to answer some learning questions from college. (not allowed to use jpb in the question)

It asks that a very basic program takes in from args[] two command line arguements, then tests them to see if their odd or even. I'm just wondering is there any pre made methods that I could use that tests if an integer is odd or even. I haven't wrote any of the program yet just wondering about any pre made methods.

If not I was thinking of taking the string arguements from args[] and using Integer.parseint() to turn them into integers. Then divide them by an odd or even number and see if the answer has a decimal point or not to show if its odd or even (might completely fail, thats all i thought off at the moment)

Thanks for all help in advance
• 04-14-2010, 08:07 PM
StormyWaters
As far as I know there is no pre-made method for determing whether or not a number is even or odd, however it is very simple and you are on the right track.

I would suggest you read up on the "%" operator.
• 04-14-2010, 08:20 PM
Eranga
There is no specific pre-defined way to do that. Use the simple logic, with the array length/size. Check the mod value for validation.
• 04-14-2010, 09:17 PM
orion_mcl
Hi. I'm sure there's not a pre made method to check if a number is odd or even. And if you don't want to use the "if" statement you can also user the "?" operator. Check this out :)

value=Integer.parseInt(.......//HERE GOES THE INPUT
boolean isEven=(value%2==0)?true:false;

I hope you can find this useful. Bye.
• 04-14-2010, 11:43 PM
counterfox
I read up on % and decided to test for even in a if statement. Thanks all for the help!
• 04-15-2010, 12:11 AM
Fubarable
Quote:

Originally Posted by orion_mcl
Hi. I'm sure there's not a pre made method to check if a number is odd or even. And if you don't want to use the "if" statement you can also user the "?" operator. Check this out :)

value=Integer.parseInt(.......//HERE GOES THE INPUT
boolean isEven=(value%2==0)?true:false;

I hope you can find this useful. Bye.

Isn't using the ternary operator a bit overkill? What does it add here but unnecessary complexity?

See for yourself, which is cleaner?

A:
Code:

`boolean isEven = (value % 2 == 0);`

vs. B (your example):
Code:

`boolean isEven = (value % 2 == 0) ? true : false;`
• 04-15-2010, 03:51 AM
Eranga
I agreed with Fubarable. Unnecessary complexities make trouble all the time. Small code segments like this is okay, but with the huge applications, it's very difficult to track those things. And also there is no huge difference in performance wise in two ways above.
• 04-15-2010, 03:52 AM
Eranga
Quote:

Originally Posted by counterfox
I read up on % and decided to test for even in a if statement. Thanks all for the help!

You are welcome. :)