About Question enthuware.ocajp.i.v7.2.1332 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
strauberry
Posts: 4
Joined: Wed Nov 19, 2014 3:22 am
Contact:

About Question enthuware.ocajp.i.v7.2.1332 :

Post by strauberry »

Hi,

I have a question regarding the narrowing conversion of primitive numeric data types in the context of the provided question: In my Java book I've read that a conversion from a "big" to a "small" data type cuts of leading bits. This might cause a change of the sign, e.g.:

The value of an integer might be
01001010011101111000011001010111 (32 bit)

A conversion to a short might simply delete the first 16 bits, resulting in
1000011001010111 (16 bit)

For the short value, now the first bit is 1, which means the value is negative...

But I cannot apply this approach on the "correct" answer of the given question: in this line b = (byte) i; I would assume that the trailing bits of the integer i are removed, so the sign information gets lost.

Where is my mistake?

Thank you!

admin
Site Admin
Posts: 10066
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.1332 :

Post by admin »

I am not sure what the book says but as per JLS section 5.1.3:
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.
Not sure why you think the trailing bits will be removed.

Now, in the given question, you will remove the first 24 bits of the given integer ( 11111111111111111111111110000000 ) and you will get 10000000. Since it is a byte, the first digit is for sign, and therefore 10000000 is a negative number whose value is also -128 in decimal.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 241 guests