Sub topic 15
Choosing a Primitive Type
Java has eight primitive types. A primitive type is a built-in type for a single simple value, such as a number or a true-or-false answer. Choosing the right type helps your program hold the values it needs and avoid surprises.
Start with two questions:
- What kind of value do I need?
- What values might it have, both now and later?
A count of books, a temperature, and an answer to a yes-or-no question need different kinds of values.
Start with the kind of value
| Your value | Usually choose | Example |
|---|---|---|
| A whole-number count | `int` | Number of books |
| A whole number that may be very large | `long` | Population across many years |
| A measurement with a fractional part | `double` | Room temperature |
| One simple character | `char` | A size label such as `'M'` |
| A yes-or-no answer | `boolean` | Whether an item is available |
These are starting points, not rules for every situation. In particular, money needs extra care, and not every character fits in one char.
Choosing a whole-number type
Java offers four primitive types for whole numbers. Each has a fixed range: the smallest through largest value it can hold.
| Type | Range | When to consider it |
|---|---|---|
| `byte` | -128 to 127 | A small range required by a file format or another part of a program |
| `short` | -32,768 to 32,767 | A small range required by a specific format |
| `int` | -2,147,483,648 to 2,147,483,647 | Most whole-number counts |
| `long` | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | Counts or totals that may not fit in `int` |
Choose int for a count unless you have a reason to choose another type. For example, the number of seats in a classroom fits easily in an int.
Choose long when the value could grow beyond the range of int. For example, a count of events collected by a busy service over many years might need long. Put L after a large long value, as in 5_000_000_000L. The underscores make the number easier to read; they do not change its value.
Do not choose byte or short just because today’s value is small. An int is often easier to work with, and the count may grow. Smaller types can be useful when a format requires them or when a large collection of numbers must use less memory.
Think about results, not just inputs
A type must hold the result of a calculation as well as its starting values. For example, two counts may each fit in an int, while their total does not.
If a whole-number result goes past its type’s range, overflow can occur: the result wraps around instead of being the expected number. Choosing a long for the result alone is not always enough. The calculation itself must use the larger type.
For example, in 2_000_000_000L + 2_000_000_000, the L makes the first value a long, so Java performs the addition as a long calculation. The result is 4,000,000,000.
If even long is too small, Java provides BigInteger for larger whole numbers. It is not a primitive type.
Choosing a type for measurements
Use double for most measurements that can have a fractional part, such as a temperature or a distance. Use float when you have a specific reason, such as storing a very large collection of measurements with lower memory use.
| Type | Approximate precision | Example |
|---|---|---|
| `float` | About 7 meaningful decimal digits | `20.5f` |
| `double` | About 15 to 16 meaningful decimal digits | `20.5` |
Precision here means how many digits a type can keep meaningfully in a value. A double can keep more detail than a float. The f after 20.5f tells Java that the value is a float.
Both types have a limit: they cannot represent every decimal fraction exactly. For example, 0.1 is only an approximation when stored as a double. Small differences can appear in calculations.
What about money?
Money often needs exact decimal results. A double is usually a poor choice for those calculations because of its approximations.
For simple amounts with two decimal places, one option is to store a whole number of cents in an int or long. For example, 1,299 cents represents $12.99. Choose a type large enough for the biggest amount and total you expect.
For calculations that need other decimal places or careful rounding, consider BigDecimal. It is a Java type for decimal calculations, but it is not primitive. Currencies and business rules can require different numbers of decimal places, so decide on those rules before choosing how to store an amount.
Choosing between `char` and text
Use char for one value such as the size label 'M' or the digit character '7'. A digit character is text, not the number used for arithmetic.
Java stores a char as one UTF-16 code unit, which is one small piece of a Unicode text value. Unicode is a standard for representing characters from many writing systems. Some Unicode characters need two UTF-16 code units, so not every character fits in one char.
Use String for text such as a name, a sentence, or a character that needs more than one code unit. A String is a reference type, not a primitive type: its variable refers to a text object rather than holding a primitive value.
Choosing `boolean`
Use boolean when there are exactly two possible answers: true and false.
For example, inStock can say whether an item is available. A boolean makes the purpose clearer than a number such as 0 or 1.
If you need more than two states, a boolean alone is not enough. For example, an order could be waiting, shipped, or canceled. Do not force those three states into one true-or-false value.
Worked example: an order
Suppose a shop sells an item for $12.99. An order contains three items. The program needs a quantity, a price, a total, a size label, and an availability answer.
Save this program as OrderExample.java, then compile and run it.
class OrderExample {
public static void main(String[] args) {
int quantity = 3;
long unitPriceCents = 1299L;
long totalCents = Math.multiplyExact(unitPriceCents, quantity);
char size = 'M';
boolean inStock = quantity > 0;
System.out.println("Quantity: " + quantity);
System.out.println("Unit price in cents: " + unitPriceCents);
System.out.println("Total in cents: " + totalCents);
System.out.println("Size: " + size);
System.out.println("In stock: " + inStock);
}
}The total printed is 3897 cents. Here is why each choice fits:
quantityis anintbecause the expected count is a whole number within its range.unitPriceCentsandtotalCentsarelongvalues. Storing cents keeps this example’s money calculation in whole numbers, andlonggives the total more room to grow.sizeis acharbecause'M'is one simple label.inStockis aboolean. The testquantity > 0producestruefor this order.
Math.multiplyExact multiplies the two numbers and checks for overflow. If the result cannot fit in a long, the program reports an error instead of silently wrapping around. This does not make long unlimited; it makes a too-large result easier to notice.
A final check
Before you settle on a type, ask:
- Can it hold the smallest and largest values I expect?
- Can it hold the largest result of my calculations?
- Do I need an exact amount, or is an approximation acceptable?
- Does the value describe a number, text, or a yes-or-no answer?
When the answer is uncertain, write down the assumptions. A count that fits today may not fit after the program has been used for years.
Exercise
A program stores the total number of views across many videos. The total may exceed 2,147,483,647. Should it use int or long?
Show answer
Use long, because the total may exceed the largest value an int can hold. Make sure the calculation also uses long.
Exercise
A program stores a room temperature with a fractional part. A close approximation is acceptable. What primitive type is a good default?
Show answer
Use double. It holds fractional values and generally keeps more precision than float.
Exercise
A shop stores prices in cents and needs an exact total. Why is a whole-number type a better starting choice than double?
Show answer
Whole-number cents avoid the decimal approximations of double. Choose int or long based on the largest amount and total, and check for overflow.