wood burning stoves*
The moose likes Beginning Java and the fly likes A cast question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A cast question" Watch "A cast question" New topic
Author

A cast question

Grady Jamyson
Ranch Hand

Joined: Aug 04, 2002
Posts: 42
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

Joined: Mar 23, 2004
Posts: 82
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

Joined: Aug 04, 2002
Posts: 42
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

Joined: Mar 23, 2004
Posts: 82
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

Joined: Dec 10, 2001
Posts: 7023
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 ]

    [How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
    Grady Jamyson
    Ranch Hand

    Joined: Aug 04, 2002
    Posts: 42
    Thank you so muck.
    Very clear.
     
    It is sorta covered in the JavaRanch Style Guide.
     
    subject: A cast question