• Notice regarding image hosts and attachments. See here.

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??????
 
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
 
Back
Top Bottom