int -> short (OK) ; short -> byte (not ok ) Why?..
Prasad Ballari
Ranch Hand
Joined: Sep 23, 2000
Posts: 149
posted
0
Hi, As 32 bits int can be implicitly narrowed to 16 bits short,why its not possible to have 16 bits implicit conversion to 8 bits byte. ex: short s= 24 //OK : 16 bits <- 32 bits byte b=s; //NOT OK WHY?? : 8 bits <- 16 bits Prasad Ballari.
------------------
asim wagan
Ranch Hand
Joined: Nov 14, 2000
Posts: 62
posted
0
<html><body> Listen Prasad there is a difference between primitve reference conversion and a constant values conversion. Here is your ex: <code> short s= 24 //OK : 16 bits <- 32 bits A conversion from constant byte b=s; //NOT OK WHY?? : 8 bits <- 16 bits A conversion from primitive refernce or variable Here is the code that shows an integer type implicitly converted to byte: public class narrow{ public static void main(String args[]){ byte b=24; System.out.println(b); } } </code> see how it works </body></html>
Paul Anilprem
Enthuware Software Support
Ranch Hand
Hi Prasad, if you assign 24 to a byte or short variable, this will work as long as the range of a short or a byte can cover the value. For example an byte b = 300 won't work. Compiler will detect, that he can't put 300 in a byte....
[B]Originally posted by Prasad Ballari:
[/B]
When you assign 24 to s, the compiler will know that 24 will never change during the runtime, its an integral literal.... But if you assign s to a byte b, compiler can never be sure, if s will always fit in the byte. That's the reason why he complains. If you change to everything is okay... hope that helps as always correct me if i'm wrong Oliver
Sahir Shah
Ranch Hand
Joined: Nov 05, 2000
Posts: 158
posted
0
Hi guys, There is no such thing as implicit narrowing conversion. You cannot implicitly convert an int to a short nor can you convert a short to a byte. Regarding what Oliver Grass posted : final int s = 2; byte b = s; is OK because s is a CONSTANT and the value can fit into a byte. It is the same as. byte b = 2; However you may not use a long , float or double here. Rgds Sahir
....
subject: int -> short (OK) ; short -> byte (not ok ) Why?..