This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes type casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "type casting" Watch "type casting" New topic

type casting

Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
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

Joined: Feb 14, 2006
Posts: 210
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.

SCJP 1.4 85%
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
15.18.2 Additive Operators (+ and -) for Numeric Types

5.6 Numeric Promotions
I agree. Here's the link:
subject: type casting