# Thread: How to test for an odd/even number

1. Member
Join Date
Mar 2009
Posts
45
Rep Power
0

## 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

2. Senior Member
Join Date
Feb 2009
Posts
312
Rep Power
12
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.

3. 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.

4. Member
Join Date
Aug 2007
Posts
17
Rep Power
0
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.

5. Member
Join Date
Mar 2009
Posts
45
Rep Power
0
I read up on % and decided to test for even in a if statement. Thanks all for the help!

6. 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:
Java Code:
`boolean isEven = (value % 2 == 0);`

Java Code:
`boolean isEven = (value % 2 == 0) ? true : false;`

7. 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.

8. 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. :)