Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 465
System.out.println(i);
return i;
}

System.out.println(myObject.go((byte)128));

Here,byte maximum range is 127.i thought it would display error.how come it takes -128 value.Can anyone please explain the rule for me.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by Shiva Mohan:
System.out.println(i);
return i;
}

System.out.println(myObject.go((byte)128));

Here,byte maximum range is 127.i thought it would display error.how come it takes -128 value.Can anyone please explain the rule for me.

You are casting 128 to a byte before you send it to the method.
Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 465
128 byte value is 1000 0000.How come -128.Still don't understand......
Karol Kisielewski
Greenhorn

Joined: Jun 28, 2006
Posts: 8
Originally posted by Shiva Mohan:
System.out.println(i);
return i;
}

System.out.println(myObject.go((byte)128));

Here,byte maximum range is 127.i thought it would display error.how come it takes -128 value.Can anyone please explain the rule for me.

There is nothing strange with this. The int literal (which is 32 bits long) is explicite casting to byte (8 bit):
128 = 00000000 00000000 00000000 10000000
casting to byte truncate 24 highest bits and gives:
10000000=-128

Compiler allows for this bacause it trust you and know that you know what you are doing
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
128 is an int literal. Its bit representation is

00000000 00000000 00000000 10000000

When it's cast to a byte, its bit representation is

10000000

This is a negative number because the sign bit is 1.

To find out what negative number it is, flip the bits and add 1.

01111111
00000001

10000000

So the number is -128.
Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 465
Thankyou very much karol and keith.