• Post Reply Bookmark Topic Watch Topic
  • New Topic

Boxing int-Literal  RSS feed

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

can someone explain the reason why the compiler allows rows 12-14?
I expected that the comiler behaves in the 2nd block like in the first block.
Whats the logic in this behaviour?

Thanks Tillux

 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can someone explain the reason why the compiler allows rows 12-14?


This is not a boxing issue. The same errors would occur even if the declarations were primitives.

In the second block, the expression to be assign are compile time constants, and hence, the compiler can determine that the cast can occur implicitedly.

Henry
 
Till Stoschus
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Henry,

but when..... why does the compiler doesnt cast implicit ...

Long d4 = 33; //Compiler error


but

long d3 = 33; //ok

is ok?

Till
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but when..... why does the compiler doesnt cast implicit ...


This is opinion only -- there are many who will disagree with me, so take with a grain of salt.... In my opinion, it is broken.

There is a difference between an implicit cast, which is what happens when an int is assigned to a long, and one that allows an int to be assigned to a short (because it is a compile time constant). The second case seems to work with autoboxing, while the first doesn't.

This is probably all defined in the specifications, but IMO, I think this should be made consistent.

Henry
 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Till Stoschus wrote:
but when..... why does the compiler doesnt cast implicit ...
Long d4 = 33; //Compiler error
but
long d3 = 33; //ok

Hi Till,

The first statement doesn't work because it needs Widening (to long) and then Boxing (to Long), which is not allowed,
whereas the second statement, needs only widening (to long). You also can name it implicit cast.

I hope I could help
Bob
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use 33L (always use capital L; 33l may be mistaken for 331), 33f and 33d to indicate you want to use long, float and double instead of int.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!