primitive_types - matthew9510/Studies GitHub Wiki

Java Primitive types

The language java has EIGHT built in data types

I personally like to think of them as storage containers for specific data types to store.

Types

Non-Arithmetic types:

  • boolean, Default value: False
    • Boolean type store values that are either true or false.
  • char, Default value: '\u0000'
    • The character type whose values are 16-bit Unicode characters
    • A common error is to use double quotes rather than single quotes around a character literal, as in myChar = "x", yielding a compiler error.
    • Similarly, a common error is to forget the quotes around a character literal, as in myChar = x, usually yielding a compiler error (may not if x is a variable, leading to a logic error).
Check out this Ascii Table

Ascii Table

Arithmetic types:

integral types (whole number) types:
  • byte, Default value: 0
  • short, Default value: 0
  • int, Default value: 0
  • long, Default value: 0L
floating-point (decimal number) types:
  • float, Default value: 0.0f
  • double, Default value: 0.0d

Integer data types

Primitive Type Table

BE CAREFUL

Compilers may not detect overflow in calculations and thus not generate a warning; the program simply runs incorrectly.

A common source of overflow involves intermediate calculations.

Given int variables num1, num2, num3 each with values near 1 billion, (num1 + num2 + num3) / 3 will encounter overflow in the numerator, which will reach about 3 billion (max int is around 2 billion). Even though the final result after dividing by 3 would have been only 1 billion.

Dividing earlier can sometimes solve the problem, as in (num1 / 3) + (num2 / 3) + (num3 / 3), but programmers should pay careful attention to possible implicit type conversions.