The problem is that the + operator in Java is overloaded. It can mean either string concatenation or numeric addition. What is going on is that some of the + operations are being treated as string concatenations rather that numerical additions.
You need to either add a set of parentheses around the expression,
System.out.println("result="+((44334*(220*220))+ (81744*220) + 39416));
or use a temporary variable.
int res = (44334*(220*220))+ (81744*220) + 39416;
System.out.println("result="+res);
"The rules" that Java uses to determine the meaning of + are roughly as follows:
- If the type of the left OR right operand is String, then the
+ means string concatenation.
- If the types of both the left AND right operands are primitive numeric types or numeric wrapper types, then the
+ means a numeric addition.
- Otherwise this is a compilation error.
The other problem here is that 2163788696 is greater than the largest int value - 2147483647. So to get the right answer (without overflow), you need to tell Java to use long arithmetic; e.g.
System.out.println("result=" + ((44334L * (220 * 220)) + (81744 * 220) + 39416));
If you don't then result will be a negative number ... in this example.
You could also use BigInteger, but it is a bit cumbersome, and long will do just fine here.