Question about casting

Soldato
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
Just playing around with casting to see the effect it has if you don't do it properly!

For example 123456789^2 = 15241578750190521

The following code produces the result -1757895751

Code:
public class Order {
	public int int1 = 123456789;
	public int int2 = 123456789;
	public long long1 = 0;
	public void calculateTotal(){
[B]		long long1 = (long)(int1*int2);[/B]
		System.out.println("Result: " + long1);
	}
}

Where as this produces the correct result

Code:
public class Order {
	public int int1 = 123456789;
	public int int2 = 123456789;
	public long long1 = 0;
	public void calculateTotal(){
[B]		long long1 = (long)int1*int2;[/B]
		System.out.println("Result: " + long1);
	}
}

Question is why does the first one produce an incorrect result, I would have thought casting the result of (int1*int2) would produce exactly the same thing as (long)int1*int2??????
 
Associate
Joined
15 May 2006
Posts
224
Hi,

In the first example the (int * int) will result in an integer being produced. The resulting number will be too large to hold in an int so the error will appear (turned to a negative number by the left-most bit being set). Casting to a long will have no effect on the outcome (it's the erroneous number produced ny the calculation that's being cast).

In the second case the first int is cast to a long so the datatypes in the multiplication are "long * int" which will result in a long being produced. As the long can hold the number produced without overflowing the correct answer will be seen.

I think that's about right.....

Jim
 
Soldato
OP
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
Hmm yeah that makes sense, I did come up with a similar answer myself about half an hour after posting (all apart from "turned to a negative number by the left-most bit being set").

So the following lines would also produce the same [correct] result?

Code:
[B]long long1 = int1*(long)int2;[/B]

Code:
[B]long long1 = (long)int1*(long)int2;[/B]

Actually, CAN you cast the second variable or would that produce a syntax error, hmmmm
 
Associate
Joined
28 Jun 2005
Posts
895
They should both give the correct result (i.e. no overflow) and both are fine. You can cast any primitive where ever it is in an expression
 
Back
Top Bottom