Skip to content
Preview · sample content · Explore all pages

Java variables and primitive types

Last updated: 28 Sept 20263 min read
tutorial
By AITrove Editorial

A Java variable has a declared type that determines its permitted values and operations.

Working model

Use integer types for counts. For this receipt, money is stored as an integer number of paise; the sample excludes currencies whose smallest unit differs. Floating-point values are unsuitable for exact decimal accounting.

Code

Java
long unitPricePaise = 129900L;
int quantity = 3;
long invoiceTotalPaise = Math.multiplyExact(unitPricePaise, quantity);
boolean eligibleForDispatch = quantity > 0;
System.out.println(invoiceTotalPaise);
System.out.println(eligibleForDispatch);

The output is 389700, followed by true. Math.multiplyExact reports overflow rather than silently wrapping. A long has a wider range than an int, but neither grows without a limit.

Cost and design choices

Primitive assignment copies a value. Reference assignment copies a reference; two variables can then identify the same mutable object. That distinction matters when a method changes a list it receives.

Range and initialization boundaries

int arithmetic can wrap without throwing. Widening the destination variable after an overflowing int calculation does not recover the lost value. Convert an operand before the calculation or use checked arithmetic when overflow should reject the operation.

Fields and array elements receive default values; local variables need a definite assignment before use. A default zero may also be a valid business value, so explicitly track absence instead of assuming an unassigned field will be obvious.

Connected lessons

Continue with Java operators and numeric promotion, Java Tutorial.

Common Mistakes

Local variables require initialization before use. Integer overflow is not automatically an exception for ordinary arithmetic. For financial systems, validate units, currency, and rounding rules explicitly.

java
variables-types
Storage details