₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,974 members, 8,424,379 topics. Date: Thursday, 11 June 2026 at 06:48 AM

Toggle theme

Checking If A Number Is Odd In Java - Programming - Nairaland

Nairaland ForumScience/TechnologyProgrammingChecking If A Number Is Odd In Java (1381 Views)

1 Reply (Go Down)

Checking If A Number Is Odd In Java by D34lw4p(op): 10:54pm On Jan 25, 2016
Have a look at the lines of code below and determine if they can be used to precisely identify if a given number is Odd?


public boolean oddOrNot(intnum) {
return num %2==1;
}


These lines seem correct but they will return incorrect results one of every four times (Statistically speaking). Consider a negative Odd number, the remainder of division with 2 will not be 1. So, the returned result will be false which is incorrect!

This can be fixed as follows:


public boolean oddOrNot(intnum) {
return (num &1) !=0;
}


Using this code, not only is the problem of negative odd numbers solved, but this code is also highly optimized.

Since, Arithmetic and Logical operations are much faster compared to division and multiplication, the results are achieved faster so in second snippet.


Join Our Programming Discussion Forum www.nct.com.ng
Re: Checking If A Number Is Odd In Java by Standing5(m): 11:00pm On Jan 25, 2016
If you use a modulus or absolute value to convert negetive No to positive then it will work fine.
Re: Checking If A Number Is Odd In Java by sinequanon: 5:30pm On Jan 26, 2016
What about:

public boolean oddOrNot(intnum) {
return (num |1) ==num;
}

It won't have to load the literal 0;
Re: Checking If A Number Is Odd In Java by Nobody: 1:21pm On Jan 29, 2016
 public static void checkNum(int Num){
 if(num%2 == 0){
 System.out.println("The number" +Num+ "is even"wink;
 }else{
 System.out.println("The number" +Num+ " is odd"wink;
 }
 }
 
Re: Checking If A Number Is Odd In Java by Fulaman198(m): 8:17pm On Jan 29, 2016
GetAvenue:

public static void checkNum(int Num){
if(num%2 == 0){
System.out.println("The number" +Num+ "is even"wink;
}else{
System.out.println("The number" +Num+ " is odd"wink;
}
}
That's how I would have done it personally.
1 Reply

Can An Array In Java Hold Multiple Types?Community Service | I Am To Teach Everything I Know In Java For Free!I Need Help In Java Programming.234

Matlab/simulink Specialist(in Benin City) Who Can Model A Differential RelayWhich Is The Best Bulk SMS Service Provider?Help On This Code