Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boxing and Widening

Tags:

java

boxing

What is the difference between these two. I know Boxing is converting primitive values to reference. What is widening. Also what should be the sequence first boxing should be done or widening should be done?

like image 661
Sumithra Avatar asked Oct 22 '10 09:10

Sumithra


2 Answers

  1. Widening wins over boxing and var-args
  2. Boxing wins over var-args
  3. Widening of reference variable depends on inheritance(so, Integer cannot be widened to Long. But, Integer widened to Number).
  4. Widen and boxing is not possible
  5. Boxing and widening is possible
  6. var-args can be combined with either boxing or widening
like image 143
nisha Avatar answered Oct 16 '22 02:10

nisha


Widening is transforming a variable in another with a wider type.
Widening can be done with primitive or reference types.

For example :

String -> Object
int -> long

As the JLS states :

a boxing conversion (§5.1.7) [is] optionally followed by a widening reference conversion


Resources :

  • JLS - Widening Primitive Conversion
  • JLS - Widening Reference Conversions
like image 37
Colin Hebert Avatar answered Oct 16 '22 00:10

Colin Hebert