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

    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 offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power

    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,

    Build a wall around Donald Trump; I'll pay for it.

Similar Threads

  1. Texas Hold'em Poker
    By JohnPringle83 in forum Java Gaming
    Replies: 0
    Last Post: 05-05-2011, 05:40 AM
  2. Read a bitmap byte by byte
    By cbr400aero in forum Java 2D
    Replies: 2
    Last Post: 10-18-2010, 11:42 PM
  3. Replies: 1
    Last Post: 04-21-2010, 02: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