Following program shows two different ways to test a number as odd/even without using modulus operator.
public class EvenOrOdd {
public static void main(String... args) {
//Testing, let's test both methods for positive and negative integers
System.out.println("Even or odd using division and bitwise operator");
for(int i= -1; i less then 2 i++){
isEvenOrOdd(i); //calling division operator method
isOddOrEven(i); //calling bitwise operator method
}
}
/* * Checking using division operator */
public static void isEvenOrOdd(int number){
int quotient = number/2;
if(quotient*2== number){
System.out.println("Using division operator: " + number + " is Even number");
}else{
System.out.println("Using division operator: " + number + " is Odd number");
}
}
/* * Using bitwise AND (&) operator to check if a number is * even or odd in Java */
public static void isOddOrEven(int number){
if((number & 1) == 0){
System.out.println("Using bitwise operator: " + number + " is Even number");
}else{
System.out.println("Using bitwise operator: " + number + " is Odd number");
}
}
}
I have read your blog its very attractive and impressive. I like it your blog.
ReplyDeleteJava Training in Chennai Java Training in Chennai | Core Java Training in Chennai | Java Training Institutes
Online Java Training Java Online Training | Java J2EE Online Training | JavaEE Training Institute in Chennai