Tuesday, 28 August 2012

Top 10 Tricks To Fool Your Java Professor

Trick #2

This week's trick will teach you how to find loopholes in existing programs for this you need to have deep understanding about how the underlying code works and how the Platform on which the code is running works.

Let me explain you this with an help of an example:-

Let us consider the simple and very basic example, our challenge is to write code which will tell us whether the given number is odd or not, so lets give a name to this program
ODD OR NOT
when given this challenge most people write this code:

If one can catch the flaw in this code then h/she is a Java Expert


public class OddOrNot
{
 static boolean isOdd(int no){
  return (no % 2) == 1;
 }
 public static void main(String[] arge){
  System.out.println(isOdd(7));
 }
}

Sadly if you are not the one, then i suggest you to read further


There are 2 flaw's in this code 
  1. Performance penalty (Mod operations are always less preferable)
  2. Code fails as soon as you pass a negative odd number 
Now you know the flaw, then you should be keen to know what best solution can be written for this type of challenges, stay connected....


why code fails ?
This is because, the java's truncating integer division operator[JLS 15.17.2], it implies that when the remainder operation returns a non zero result, it has the same sign as its left operand.  

So now you know the hidden flaw of the above written code, yes it return -1 as soon as you enter any negative odd number.

So, What is the best way to solve this challenge?
USE Bit-Wise-And (&), If you can use bit-wise-and (&) instead of mod (%) operation then always prefer bit-wise-and (&) operation, to increase performance of your application.

public class OddOrNot
{
  static boolean isOdd( int no ){
   return ( no & 1 ) == 1;
  }
  public static void main( String[] arge ){
   System.out.println( isOdd( -7 ) );
  }
}

Working
 If you convert any odd decimal number to its binary equivalent than you will get answer as pattern xxx1 i.e. any odd number ends with 1 and any even number ends with 0 so when we do 1 & 1 = 1 and when we do 0 & 1 = 0


This time you have learned another technique to impress your Boss, friends, professor etc.

Wait for the next trick #3
happy coding