Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Wrapper casting question

 
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have question about the following

int x = (int)new Double(2); // line 1
Double x = 1; // line 2

I understand that line 2 gives a compiler error that int cannot be assigned to Double.
I know the reason is because I cannot
widen and then box, I can only box and widen
So 1 of type int can be boxed to Integer and then widened to Object, it
can't be assigned to Double in any case.

Line one also gives a compiler error that Double cannot be casted to int.For line 1 I dont get the reasoning though.

Please help me understand the reason for compiler error in line 1.

Thanks,
Megha
 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As we know you can box and widen, so the reverse allowed operation should be Downcast and unbox.



You yourself mentioned that you cant widen and then box.
So aren't you trying to do the reverse of it?
 
megha joshi
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Swarna,

You are right..


As we know you can box and widen, so the reverse allowed operation should be Downcast and unbox.



In 1 I cannot downcast Double to Integer, as Wrappers cant be casted to other wrappers. So I think that is why it gives compiler error.

thanks,
Megha
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,



Line 1 and Line 2, compile file

BTW, good question and reasoning.

"We must stick to rules, they only can come to our rescue"

Thanks,
 
permaculture is giving a gift to your future self. After reading this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic