Results 1 to 5 of 5
  1. #1
    learnjava1974 is offline Member
    Join Date
    Jul 2011
    Posts
    1
    Rep Power
    0

    Post Doubt in Unboxing error

    Got a code from Complete Reference

    class UnBoxingError
    {
    public static void main(String s[])
    {
    Integer iOb=1000;
    int i=iOb.byte.value();
    System.out.println(i);
    }
    }

    The output is -24. I am not clear about how come we are getting -24? In the book it written that we are getting garbage value. But there should be some reason of getting this value -24.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,891
    Rep Power
    25

    Default

    For those who like bits and bytes:
    Java Code:
        
         int ix = 1000;
         System.out.println("1000=" + Integer.toHexString(ix)); // 1000=3e8
         ix  = -24;
         System.out.println("-24=" + Integer.toHexString(ix)); //-24=ffffffe8
    Notice the rightmost two nibbles(1 byte): e8

  4. #4
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Think of it as if it wraps, and when a value goes over, it goes to the minimum value. 128 is greater than a bytes maximum value, so it 'wraps around' to -126. 1000 'wraps around' multiple times, and ends up at -24. It's not exactly what happens, and Norm's example is more complete, but it's an easy way to think of it when you're trying to figure out what happens when a numeric value goes over the maximum of its type.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

Similar Threads

  1. Best Practice wrt Boxing / Unboxing
    By johnnyforeigner in forum Advanced Java
    Replies: 2
    Last Post: 06-05-2011, 01:10 PM
  2. a doubt
    By Thia in forum New To Java
    Replies: 13
    Last Post: 11-24-2009, 03:26 AM
  3. have doubt
    By ras_pari in forum Advanced Java
    Replies: 3
    Last Post: 10-01-2009, 10:51 AM
  4. doubt
    By Chris555 in forum Networking
    Replies: 0
    Last Post: 08-05-2009, 03:58 PM
  5. Doubt
    By winkodes in forum Enterprise JavaBeans (EJB)
    Replies: 2
    Last Post: 12-20-2008, 09:34 PM

Posting Permissions

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