Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

type casting

 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1 byte a=9;
2 byte b=6;
3 byte c=(byte)(a+b);
4 float a=8.9f;
5 float b=9.6f;
6 float c=(float)a+b;
7 System.out.println(c);

Dear sir in the above code at line 3 that c=(byte)(a+b) here (byte)it is ok but why there is need to also enclose a+b in ()although at line 6 it is working fine and if i m making
like c=(byte)a+b
a compile time error that
possible loss of precision
found int
requered byte
although it is working at line 6

with regard
Arun kumar maalik
 
Aum Tao
Ranch Hand
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use the code tag while listing code .


When arithmetic operations are performed on byte variables as in the above case, they are first promoted to integers and then the operation takes place. Therefore, you'll need to cast the complete result if it is stored in a byte. If you use byte c = (byte)a + b; You are only casting a and not the complete result i.e. a + b. Hence, the compilation error.



In the above case, it doesnt matter if the result is casted as the variable c is float and thus can accomodate the result of the addition operation.
 
wise owen
Ranch Hand
Posts: 2023
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic