+84 1649 660 740

Thursday, 4 September 2014

Check if a number is even or odd in Java

* Question: Write a program in Java to check if a number is even or odd?
* Answer 1: Using the modulus operator.
(1). Create project: CheckEvenOddModulus 
(2). Create package: com.webmobileaz
(3). com.webmobileaz => File: Numbers.java



package com.webmobileaz;

import java.util.Scanner;

public class Numbers {
 public boolean isEven(int number) {
  return (number % 2 == 0);
 }
}

class Main {
 public static void main(String []args) {
  Scanner scan = new Scanner(System.in);
  System.out.print("Input a number: ");
  int number = scan.nextInt();
  
  Numbers num = new Numbers();
  if(num.isEven(number)) {
   System.out.println(number + " is Even");
  } else {
   System.out.println(number + " is Odd");
  } 
 }
}

Download Project: CheckEvenOddModulus 

* Answer 2You can use the modulus operator, but that can be slow. If it's an integer, you can use Bitwise AND operator
(1). Create project: CheckEvenOddBitwise
(2). Create package: com.webmobileaz
(3). com.webmobileaz => File: Numbers.java


package com.webmobileaz;

import java.util.Scanner;

public class Numbers {
 public boolean isEven(int number) {
  return ((number & 1) == 0);
 }
}

class Main {
 public static void main(String []args) {
  Scanner scan = new Scanner(System.in);
  System.out.print("Input a number: ");
  int number = scan.nextInt();
  
  Numbers num = new Numbers();
  if(num.isEven(number)) {
   System.out.println(number + " is Even");
  } else {
   System.out.println(number + " is Odd");
  } 
 }
}

Download Project: CheckEvenOddBitwise

0 comments:

Post a Comment