Question

In java we can box and then widen. Why cant we widen and box? For ex:

 class WidenAndBox{
  static void go(Long x)  {   }
  public static void main(String [] args)
   {
    byte b=5;
    go(b);
   }
}

Compiler error

Was it helpful?

Solution

I'm not privy to the how the spec was written, but in general, you don't automatically cast between incompatible classes. Widening of primitives is a separate issue, and the Java widening rules were laid out long before autoboxing was added to the language. It's a tradeoff between the letting the compiler catch your mistakes and not irritating you with small details.

In the case of your example, if you had autoboxed a long you would be OK, or if you had made a function that took Number as a parameter, you would be OK too. You may think the compiler should help you along by realizing that a Byte could be easily unboxed and reboxed as a Long, but the folks that make the compiler don't agree, and I don't really either.

OTHER TIPS

It IS possible for the compiler to perform a boxing operation followed by a widening operation in order to match an invocation to a method. Lets take an example

 class BoxAndWiden {
   static void go(Object o) {
   Byte b2 = (Byte) o; // ok - it's a Byte object
   System.out.println(b2);
   }
    public static void main(String [] args) {
    byte b = 5;
    go(b); // can this byte turn into an Object ? 
    }
    }

This compiles (!), and produces the output:5 Let me show how it works behind the scene.when the JVM, got to the line that invokes the go() method:

  1. The byte b was boxed to a Byte.
  2. The Byte reference was widened to an Object (since Byte extends Object).
  3. The go() method got an Object reference that actually refers to a Byte object.
  4. The go() method cast the Object reference back to a Byte reference (re member, there was never an object of type Object in this scenario, only an object of type Byte!).
  5. The go() method printed the Byte's value.

But in your case.Why didn't the compiler try to use the box-then-widen logic when it tried to dealwith the WidenAndBox class?

if it tried to box first, the byte would have been converted to a Byte. Now we're back to trying to widen a Byte to a Long,and of course, the IS-A test fails.

I believe the main reason is performance. If you would allow an arbitrary combination of widening and (un)boxing, you would need to check for the existence of more possibly matching methods. Especially in a context with functions takes multiple small range primitive parameters, the amount of possible combinations could become quite large.

Cast it to a long.

Just cast it to a long type

 go( (long) b);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top