ZZZ
ZZZ

Reputation: 3754

data type of results of java arithmetic calculation

In java, I know the data type of the result of an arithmetic calculation depends on the data types of the numbers involved in the calculation. For example,

  1. int + int = int

  2. long/double=double

a. But I can't find any references which can give me all these rules. Could someone help me?

b. How to avoid over flow in arithmetic calculation? For example, the results of 2 long may not fit into a long anymore...

Thanks a lot.

Upvotes: 7

Views: 3754

Answers (4)

Bob Smith
Bob Smith

Reputation: 75

Answer to question A:

The type of operand with the "larger type"

enter image description here

Double is the "largest" type

Note: char and boolean cannot be used w/ arithmetic operator

Source: https://www.geeksforgeeks.org/type-conversion-java-examples/

Upvotes: 0

dMb
dMb

Reputation: 9337

a. These rules are called numeric promotion rules and are specified in Java Language Specification, §5.6.2 (currently).

b. There are two generally accepted method for dealing with overflows.

The first method, a post-check, where you do an operation, say addition and then check that the result is greater than either of the operands. For example:

int c = a + b;

if( c<a) {  // assuming a>=0 and b>=0
   // overflow happened
}

The second method, is a pre-check, where you basically try to avoid the overflow from happening in the first place. Example:

if( a > Integer.MAX_INTERGER - b ) {
   // overflow happened
}

Upvotes: 4

Guy Lerat
Guy Lerat

Reputation: 21

The result of an arithmetic operation on any two primitive integer operands will be at least an int -- even if the operands are bytes and short.

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198083

The specific section of the Java Language Specification that deals with these rules is section 4.

If you don't want values to overflow at all, use a BigInteger or some other arbitrary-precision arithmetic type.

For avoiding overflows in the general case, Guava (which I contribute to) provides methods like IntMath.checkedAdd(int, int) and LongMath.checkedMultiply(long, long), which throw exceptions on overflow. (Some of those are nontrivial to implement yourself, but these are all very exhaustively tested.) You can look at the source to see how they work, but most of them rely on cute bit-twiddling tricks to check for overflow efficiently.

Upvotes: 2

Related Questions