Sunday, October 28, 2018

Do you know - Series - 4: Boxing and Unboxing - Integer assignment and comparison

We know about boxing and unboxing in Java. It is about automatic conversion of primitive type value into its Wrapper Object equivalent type value and viz.

Below is the simple example to understand this.

      int a = getCustomerNumber(); //getCustomerNumber() returns an int
      Integer aObj = a; //boxing

      Integer bObj = getAccountNumber(); //getAccountNumber() returns an Integer
      int b = bObj; //unBoxing

      if(a == bObj) {
            System.out.println("a and bObj are equal");
      } else {
           System.out.println("a and bObj are not equal");
      }

The above code will work fine if the method getAccountNumber() returns an Integer value. But, the problem starts when this getAccountNumber() method returns a null value. When it returns null you could see a NullPointerException in line where we have "int b = bObj;". The reason is that we are trying to set 'null' into a primitive type.

The simplest solution to fix this is change the type of b into Integer or you may need to check for the 'null' value from the getAccountNumber() and then assign proper 'int' value to 'b'.

Now, the corrected statement will be

Integer b = bObj;


Great! We fixed the issue.

Now, when you try to run again and you would notice the same exception, but in line where we have the if() condition. Again, the reason is comparing 'null' with primitive type variable 'a'. Now, to fix this you may suggest to change the type of 'a' into 'Integer' or simply typecast 'a' into Integer within the if() condition as below.

if((Integer)a == bObj)


Excellent! We fixed the second issue!

But, things are not settled down still. If you notice the 'if()' condition we have  '==' to compare reference types. Definitely, this is not the right way to compare references, right?

Lets change the condition with if(((Integer)a).equals(bObj)) .

Finally, we are able to run the code. The final version of code section is given below.

      int a = getCustomerNumber(); //getCustomerNumber() returns an int
      Integer aObj = a; //boxing

      Integer bObj = getAccountNumber(); //getAccountNumber() returns an Integer
      Integer b = bObj;

      if(((Integer)a).equals(bObj)) {
            System.out.println("a and bObj are equal");
      } else {
           System.out.println("a and bObj are not equal");
      }


We now understand that things look simple externally, but they come with some complexities internally...


No comments:

Post a Comment

Do you know - Series - 4: Boxing and Unboxing - Integer assignment and comparison

We know about boxing and unboxing in Java. It is about automatic conversion of primitive type value into its Wrapper Object equivalent type...