• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Tim Cooke
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
Saloon Keepers:
  • Piet Souris
Bartenders:

Java program to check whether a number is even or odd

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wrote this Java program to check whether a number is even or odd using the modulo operator. Is this the correct and efficient approach, or is there a better way to implement this in Java?

class EvenOddCheck {
   public static void main(String[] args) {
       int num = 42;

       if (num % 2 == 0) {
           System.out.println(num + " is Even");
       } else {
           System.out.println(num + " is Odd");
       }
   }
}
 
Sheriff
Posts: 9090
670
Mac OS X Spring VI Editor BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look, I wrapped your code into code tags, and representation of it looks much better  ..use Code button when posting code.
 
Liutauras Vilda
Sheriff
Posts: 9090
670
Mac OS X Spring VI Editor BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yoga Vignesshwar Venkatsan wrote:Is this the correct... approach


Well, you could run your program though various inputs and verify output(s) with your own manual calculations in your head. See if you could arrive at some conclusions yourself first.

When testing, try to test not just what one would call 'habitual' inputs, but also some less expected, i.e. 1, 0; -3;

See what you get.

Yoga Vignesshwar Venkatsan wrote:Is this the... efficient approach


There is no definite answer to that. More like, is this efficient enough to your needs? Likely yes. There are some other ways of doing this, I think more efficient, but certainly less known and understood. i.e. use condition if ((num & 1) == 0). Try to research why.
 
Sheriff
Posts: 28536
114
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's efficient enough. Probably 99.999% of the time to run this code is required to run System.out and no amount of tinkering is going to reduce the remaining 0.001% noticeably.
 
reply
    Bookmark Topic Watch Topic
  • New Topic