Results 1 to 2 of 2
  1. #1
    357mag is offline Member
    Join Date
    May 2010
    Posts
    18
    Rep Power
    0

    Default Why can't a byte hold 1?

    According to my book author, the following code does not work.
    Java Code:
    int i = 1;
    byte b = i;
    Sure enough, I tried it and it does not work. Yes an integer is a 32 bit type and a byte is an 8, but we're talking about the number 1 right? Why can't a byte hold the number 1 without using an explicit cast?

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default Re: Why can't a byte hold 1?

    You know that i has the value 1 and a 1 fits in a byte, and I know that, but the compiler doesn't know that; it is very near sighted, i.e. all it sees that you want to assign an int to a byte and that doesn't fit so it starts whining about it. Change the second line to:

    Java Code:
    byte b= (byte)i;
    and the compiler assumes that you know what you're doing. If you had assigned a literal value to byte b and that value fits in a byte [-128 ... 127] the compiler accepts the assignment.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Texas Hold'em Poker
    By JohnPringle83 in forum Java Gaming
    Replies: 0
    Last Post: 05-05-2011, 06:40 AM
  2. Read a bitmap byte by byte
    By cbr400aero in forum Java 2D
    Replies: 2
    Last Post: 10-19-2010, 12:42 AM
  3. Replies: 1
    Last Post: 04-21-2010, 03:28 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •