aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Casting" Watch "Casting" New topic
Author

Casting

Ada Wang
Greenhorn

Joined: Aug 28, 2000
Posts: 23
Question: (Check all correct answers)
Which of these attempts to assign a value to a byte primitive variable is out of the byte range?
a. byte b=(byte)255;
b. byte b=(byte)128;
c. byte b=(byte)-128;
d. byte b=(byte)127;
I think none of them is a correct answer. After casting, (byte)255 and (byte)128 should be zero value, because they lost their higher bits. Correct?
Ada
Mapraputa Is
Leverager of our synergies
Sheriff

Joined: Aug 26, 2000
Posts: 10065
I think c and d are correct, since range for byte is -128 to 127.


Uncontrolled vocabularies
"I try my best to make *all* my posts nice, even when I feel upset" -- Philippe Maquet
Sachin Kombrabail
Greenhorn

Joined: Aug 28, 2000
Posts: 14

The result that you will get is
a. byte b=(byte)255; (value will be -1)
b. byte b=(byte)128; (value will be -128)
c. byte b=(byte)-128; (value will be -128)
d. byte b=(byte)127; (value will be 127)
So from this the answer is (a) & (b).

Sachin Kombrabail
Greenhorn

Joined: Aug 28, 2000
Posts: 14

The result that you will get is
a. byte b=(byte)255; (value will be -1)
b. byte b=(byte)128; (value will be -128)
c. byte b=(byte)-128; (value will be -128)
d. byte b=(byte)127; (value will be 127)
So from this the answer is (a) & (b).
The reason why this happens is given with examples in the JLS.
"The results for byte and short lose information about the sign and magnitude of the numeric values and also lose precision. The results can be understood by examining the low order bits of the minimum and maximum int. The minimum int is, in hexadecimal, 0x80000000, and the maximum int is 0x7fffffff. This explains the short results, which are the low 16 bits of these values, namely, 0x0000 and 0xffff; it explains the char results, which also are the low 16 bits of these values, namely, '\u0000' and '\uffff'; and it explains the byte results, which are the low 8 bits of these values, namely, 0x00 and 0xff."
 
 
subject: Casting
 
Threads others viewed
casting
casting
Primitive casting
byte literals
Downcasting to Byte
developer file tools

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture