Home > Net >  In Java, is an operation put in brackets () is treated as integer operation ? even though we typecas
In Java, is an operation put in brackets () is treated as integer operation ? even though we typecas

Time:09-10

int[] A = {1000000007,1000000007,1000000007};

This overflows

System.out.println("Bracket mul: " (long) (A[0]*A[0]));

Output:

Bracket mul: -371520463

This doesnt - multiplication without brackets

System.out.println("Integer Multiplication: "  (long) A[0]*A[0]);

Output:

Integer Multiplication: 1000000014000000049

I know how to make use of these now, but want to understand if typecasting is applied to first value and then operation is performed if brackets are not there ?

and if brackets are there, it is treated as integer literal operation, correct me if I am wrong

CodePudding user response:

Here

(long) (A[0]*A[0])

you're doing a multiplication between integers and then casting the (already overflowed) result to long.

Here

(long) A[0]*A[0]

which is read as

((long)A[0]) * A[0]

you're casting the first operand to long, so the operation will be between longs (because the second operand will be promoted to long as well) and the result will be a long and won't overflow.

CodePudding user response:

Because when you multiply two integers intint, memory allocated for result will be the size of int, since your numbers are large their product is overflowing and overflown result is stored in the memory. Which is later typecasted to float but when you do floatint, the memory allocated for the result will be the size of float, hence you get the correct result.

  • Related