This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes int -> byte , short , char Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "int -> byte , short , char" Watch "int -> byte , short , char" New topic
Author

int -> byte , short , char

ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3829
byte b = 23 ;

a literal ( should not be fraction ) is always int by default . But compiler automatically cast if the literal is in limit of byte . So above statement is perfect .

byte b1 = 4;
byte b2 = 6;
byte add = b1+b2;

why it doesn't work . the result will come 10 ( it is int .. i am agree ) & it is in limit of byte , do why not compiler automatically cast in this case .

help needed .
thanks .
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
The compiler doesn't cast it automatically, because b1 & b2 are variables, meaning they can vary at some time. So, the compiler is bothered. It is worried that problems might occur if the values of b1 and/or b2 changes at runtime, such that the sum of them will exceed the limits of byte.

If you can convince the compiler that the values of b1 & b2 will never change, the compiler will be happy and will keep quite.
You can convince the compiler by saying

[ January 06, 2005: Message edited by: Mani Ram ]

Mani
Quaerendo Invenietis
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3829
ultimate explanation .
thank you very much .
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3829
float f = 2.3;

why in this case compiler doesn't cast double to float implicitly . As 2.3 is in limit of float .

thanks .
 
I agree. Here's the link: http://zeroturnaround.com/jrebel/download
 
subject: int -> byte , short , char
 
Similar Threads
Byte Data Type
uranary + operator
char z =1; no single quotes OK?
casting
Narrowing Primitive Conversions