### Table of Contents

Java FAQ: What are the *rules* about Java arithmetic (multiplication, division) involving mixed data types?

While working on a math problem in Java just a little while ago, I realized that I wasn’t comfortable with the Java mixed-type division rules. That is, I wondered if the result of this equation:

3 / 2

the same as the result of this equation:

3 / 2.0

or this equation:

3.0 / 2.0

## The answer

The short answer to this problem is this:

All values in an mixed arithmetic operations (+, −, *, /, %) are converted to double type before the arithmetic operation in performed.

I found that answer at this emory.edu url.

As a proof of that statement, here’s the source code for a sample Java arithmetic program:

public class Test1 { public static void main (String[] args) { System.out.println("3 / 2 = " + (3 / 2)); System.out.println("3 / 2.0 = " + (3 / 2.0)); System.out.println("3.0 / 2 = " + (3.0 / 2)); System.out.println("3.0 / 2.0 = " + (3.0 / 2.0)); } }

and here’s the output of that program:

3 / 2 = 1 # not a "mixed" equation 3 / 2.0 = 1.5 3.0 / 2 = 1.5 3.0 / 2.0 = 1.5

Notice that dividing an `int`

by an `int`

in the first example results in an `int`

, and that value isn’t what you might expect. So, as a general rule, it’s important to remember not to use two integer values like that when dividing numbers.

On a related note, this mathbits.com URL makes the following, general statement about Java arithmetic and mixed data types:

When an operation involves two data types, the smaller type is converted to the larger type.

## More Java division and arithmetic rules

The first URL I linked to above shares several other good rules. This first one is about `float`

and `double`

values:

All floating point values (

`float`

and`double`

) in an arithmetic operation (+, −, *, /) are converted to`double`

type before the arithmetic operation in performed.

This next rule is about using *integer* values in arithmetic operations:

All integer values (

`byte`

,`short`

and`int`

) in an arithmetic operations (+, −, *, /, %) are converted to`int`

type before the arithmetic operation in performed. However, if one of the values in an arithmetic operation (+, −, *, /, %) is`long`

, then all values are converted to`long`

type before the arithmetic operation in performed.

## Summary

In summary, if you wanted to see how to use Java `int`

, `double`

, `float`

, and other data types in mathematical operations, it’s helpful (and important) to understand these arithmetic rules.