Java Numbers
✅ Java Numbers
Numbers in Java are stored using numeric data types. You can use numbers to perform calculations, store values, and work with mathematical expressions.
Java supports two main categories of number types:
🔹 1️⃣ Integer Number Types
These store whole numbers (no decimals).
| Type | Size | Range Example |
|---|---|---|
byte |
1 byte | -128 to 127 |
short |
2 bytes | -32,768 to 32,767 |
int |
4 bytes | -2,147,483,648 to 2,147,483,647 |
long |
8 bytes | Very large values (use L) |
📌 Example:
🔹 2️⃣ Floating-Point (Decimal) Types
These store decimal values.
| Type | Size | Precision |
|---|---|---|
float |
4 bytes | 6–7 decimal digits (use f) |
double |
8 bytes | 15 decimal digits (default for decimals) |
📌 Example:
🔢 Numeric Operations
Java supports arithmetic with numbers:
| Operator | Meaning | Example |
|---|---|---|
+ |
Addition | x + y |
- |
Subtraction | x - y |
* |
Multiplication | x * y |
/ |
Division | x / y |
% |
Modulus (Remainder) | x % y |
📌 Example:
🔍 Number Formatting (Math Methods)
Java includes built-in math functions:
🎲 Generate Random Number (Useful Trick)
✔ Summary
| Type Category | Types |
|---|---|
| Integer Numbers | byte, short, int, long |
| Decimal Numbers | float, double |
-
Use
intfor most whole numbers. -
Use
doublefor most decimal calculations. -
Use suffix
Lfor long andffor float.
