• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A cast question

 
Grady Jamyson
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My JDK version is 1.4.2_04
I saw a book said :
byte b = 27;
the compiler would put it in the cast automatically into
byte b = (byte) 27;
but if I tried
byte b = 128;
the compiler complianed : possible loss of precision
but if I tried byte b = (byte) 128; is ok.

my question is if the compiler would cast automatically,
why I got error when I tried byte b = 128;
thanks a lot.
 
C. Nimo
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
128 is just a bit too big for byte, so you will lose precision (and the data) by doing what you set out to do.
Now, The compiler will not complain if you're explicitly asking it to cast, because then all the responsibility is on you.
Nimo.
 
Grady Jamyson
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I understand what you said.
But my question is why the compiler did the cast when byte b = 7;
is that because 7 is smaller than 127?
 
C. Nimo
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
AFAIK - yes. 7 is safe, the compiler knows that beforehand, do there's no problem with that. It would have been different if you were to assign an int variable and not a literal.
Nimo.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From section 5.2 Assignment Conversion of the JSL:
a narrowing primitive conversion may be used if all of the following conditions are satisfied:
  • The expression is a constant expression of type byte, short, char or int.
  • The type of the variable is byte, short, or char.
  • The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

  • [ April 29, 2004: Message edited by: Dirk Schreckmann ]
     
    Grady Jamyson
    Ranch Hand
    Posts: 42
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you so muck.
    Very clear.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic