It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on byte Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on byte" Watch "Question on byte" New topic

Question on byte

Chitra AP
Ranch Hand

Joined: May 25, 2005
Posts: 42
for (byte bv = 0; bv < (byte)255; bv++) {

When I execute this block of within the main(), it is not printing anything. Please let me know the reason for it.

I thought it will narrow the value and print from 1 to 127.

Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
The loop never enters because the condition 0 < (byte)255 is not met.
Try this:
and you will see that it is always less than zero (the initial value).

Here's something related:

Tony Morris
Java Q&A (FAQ, Trivia)
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
255 is outside the range of byte. The int representation of 255 is:


When cast to a byte you end up with -1 so your loop is
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 812
just wanted to know

how can we know that 11111111 is equlant to -1 do u calculate..?

and will bv<125 give error ? i think now retuns boolen value...
and comparsion b/w byte and int is ablsolutely fine ...i m right ?

Thanks and Regards, Amit Taneja
Philip Heller
Ranch Hand

Joined: Oct 24, 2000
Posts: 119
Amit wrote:

"how can we know that 11111111 is equlant to -1 do u calculate..?"

For bytes, shorts, ints, and longs, negative numbers are represented using 2's-complement notation. To take the negative of a number, invert all the bits and then add 1. (Don't worry if there's overflow.) So to take the negative of 1, start with


Then invert all bits:


And add 1:


Note that if you invert all these bits and add 1, you've taken the negative of -1, and you're back at +1. There's an animated illustration that lets you play with this mechanism in Chapter 2 of "Ground-Up Java".

And you're right that bv<125 is ok.

Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 812
so u have written the book java groundup..
and thats y naming it...
any way...
thanx and goodluck for ur book

is there is some pdf version available or any part of it u give for publicity we can atleast get some info about book and to review the book
[ June 05, 2005: Message edited by: amit taneja ]
I agree. Here's the link:
subject: Question on byte
It's not a secret anymore!