Contents

## Java Primitive Types

Consider the following Java primitive types and take note of the type’s size, e.g., 8-bit. For this post, we can ignore `boolean`

, and `char`

as they are not numeric types.

[wp_ad_camp_1]

Keyword | Type | Example |
---|---|---|

boolean | true or false | true |

byte | 8-bit integral value | 123 |

short | 16-bit integral value | 123 |

int | 32-bit integral value | 32-bit integral value |

long | 64-bit integral value | 123 |

float | 32-bit floating-point value | 123.45f |

double | 64-bit floating-point value | 123.456 |

char | 16-bit Unicode value | 'a' |

Given the following table of Java primitive types, Java follows when applying operators to data types.

- If two values have different data types, Java will automatically promote one of the values

to the larger of the two data types. - If one of the values is integral and the other is floating-point, Java will automatically

promote the integral value to the floating-point value’s data type. - Smaller data types, namely
`byte`

,`short`

, and`char`

, are first promoted to`int`

any time

they’re used with a Java binary arithmetic operator, even if neither of the operands is

`int`

. - After all promotion has occurred and the operands have the same data type, the resulting

value will have the same data type as its promoted operands.

## Rule 1 Examples:

[wp_ad_camp_2]

1 2 3 4 |
int x = 1; long y = 33; // The result of x * y is of type long |

1 2 3 4 5 |
float y = 14f; double x = 12.3; // The result of x * y is of type double |

## Rule 2 Examples:

1 2 3 4 |
int y = 3; double x = 11.3; // The result of x * y is of type double |

## Rule 3 Examples:

1 2 3 4 |
byte y = 3; short x = 1; int f = y * x; short g = y * x; // Type mismatch: cannot convert from int to short |

## Rule 4 Examples:

Rule 4 simple means the result of an arithmetic operation will have the same type as the type all operands promoted to. It is based on the first three rules.

[wp_ad_camp_3]