Here is the code that I used for the byte version:
When I compiled that code it was 449 bytes for MyTest.class according to Windows 10.
Here is the code I used for the int version:
When I compiled that code it was 447 bytes for MyTest.class according to Windows 10.
I would have suspected that the byte version would be smaller. Which leads me to the following questions:
I realize that we are talking about only two bytes right now, but depending on your program/project this could end up to be many more bytes and most embedded systems are limited to how much storage space and memory that they can use.
there also may be something with that literal 100...I think literals are ints by default, so there may need to be some extra stuff needed to compare an int with a byte.
Never mind whether it is generally accepted or not, the only thing that matters is what the Java® Language Specification (=JLS) says.
Pete Letkeman wrote:It is generally accepted the variables of type byte are smaller then variables of type int.
. . . and the Java® Virtual Machine Specification; both those links tell you how many bits each primitive integral type occupies. As Fred says, it doesn't actually say that an int occupies four bytes in primary memory.
The JLS wrote:The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively . . .
Unfortunately many things which stand to reason turn out to be false. Fortunately there is a straightforward way to inspect a little program like yours. But first I shall see if I can guess some of the things going on. Start by considering that arithmetic is by default done on ints. Your line 3 makes me suspicious:-
I think that it would then stand to reason . . .
Watch this space
Use the javap program to inspect the bytecode:-The first code block was with a byte and the second with an int.
And we can see my guesses were wrong; the compiler perceived that you were using the byte for arithmetic, etc., and converted it to an int on spec. The one difference is that the i++; statement is one line (22) using an int and (?)five lines (22‑26) using a byte. Line 25 is obviously an implicit cast. If you use a hex editor on the two versions of the .class files you can see more. Note that one version one has two lines more than the other (30 as against 28) and that is your two‑byte difference.
It all goes to show you how you can guess what the compiler does and be miles out.