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 Types (Whole numbers)
2️⃣ Floating-Point Types (Decimal numbers)

🔹 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:

byte age = 25;
short year = 2025;
int population = 1400000;
long universeAge = 13800000000L;
System.out.println(age);
System.out.println(year);
System.out.println(population);
System.out.println(universeAge);


🔹 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:

float price = 9.99f;
double weight = 65.3456789;
System.out.println(price);
System.out.println(weight);


🔢 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:

int a = 10;
int b = 3;
System.out.println(a + b); // 13
System.out.println(a – b); // 7
System.out.println(a * b); // 30
System.out.println(a / b); // 3
System.out.println(a % b); // 1


🔍 Number Formatting (Math Methods)

Java includes built-in math functions:

System.out.println(Math.max(10, 20)); // 20
System.out.println(Math.min(10, 20)); // 10
System.out.println(Math.sqrt(16)); // 4.0
System.out.println(Math.abs(-50)); // 50
System.out.println(Math.random()); // Random number (0–1)

🎲 Generate Random Number (Useful Trick)

int randomNum = (int)(Math.random() * 100);
System.out.println(randomNum);

✔ Summary

Type Category Types
Integer Numbers byte, short, int, long
Decimal Numbers float, double
  • Use int for most whole numbers.

  • Use double for most decimal calculations.

  • Use suffix L for long and f for float.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *