Should a java method accepting long value accept a Integer object?

2.2k Views Asked by At

I have a method that accepts a long primitive value and do some processing based on it. It was originally int and changed later. The code where this method is actually called was calling this method with Integer, which was ok earlier becouse of java Autoboxing and Unboxing.

But after this has been changed to long, my code doesn't show any compile time error while building as i expected. Now if i change it to int instead of Integer, it shows compile time error but not with Integer.

Why is this happening ?

EDIT :

class ABC {
   public Customer customerExists(long cid) throws Exception {
   ...
   }
}

class XYZ {
    public void method() {
       Integer customerId = null;
       ...
       customerExists(customerId);
       ...
    }
}

This should be a compile time error according to me but its not.

Java Version - openjdk version "1.8.0_31" OpenJDK Runtime Environment (build 1.8.0_31-b13) OpenJDK 64-Bit Server VM (build 25.31-b07, mixed mode)

2

There are 2 best solutions below

0
On BEST ANSWER

There are two factors that play role here: Autoboxing and Widening Primitive Conversion.

Autoboxing, or in this case, auto-unboxing, will do implicit conversion between Integer and int.

thanks to this, you can do for example

Integer x = 3;
int y = x;

Second, java will automatically do the Widening Primitive Conversion when required to the bigger type in following cases:

  • method parameter
  • arithmetic operations.

Let's show some examples.

Let's say we have public void testMethod(long x) we can call it as follows:

 testMethod(2);

2, which is integer, will be implicitly mapped to long. same thing will happen in arithmetic operations, for example:

Short s = 1;
int x = s + 1;

Short will be unboxed to short and then implicitly casted to int (because 1 is int)

Also note that:

Short s = 1;
short s2 = s + 1;

will not compile, as s+1 is already int.

If you want to read about it more, check here:

https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

2
On

you can test some changes, to improve your code, look at this piece of code :

class ABC {
   public Customer customerExists(Number cid) throws Exception {
   ...
   if( cid instanceof Integer) {
     cid.intValue().....
   }


   }
}

class XYZ {
    public void method() {
       Integer customerId = null;
       ...
       customerExists(customerId);
       ...
    }
}

so you can pass whatever kind of number, take a look at this class to convert in any type number that you need. ( number class