….
🔁 Java Type Casting – Convert Between Data Type
In Java, sometimes you’ll need to convert one data type to another — like changing an int
to a float
, or a double
to an int
.
This is called Type Casting, and it comes in two flavors:
Type | Description | Also Called |
---|---|---|
Widening Cast | Smaller to larger type (automatic) | Implicit casting |
Narrowing Cast | Larger to smaller type (manual) | Explicit casting |
Let’s explore both — GoNimbus style.
🔓 1. Widening Casting (Automatic / Safe)
✅ Java does this for you automatically when you assign a smaller type to a larger type — because there’s no data loss.
🔁 Order of Widening:
byte
→ short
→ int
→ long
→ float
→ double
Example:
public class WideningExample {
public static void main(String[] args) {
int num = 100;
double result = num; // int → double (automatic)
System.out.println("Result: " + result); // Output: 100.0
}
}
🧠 Why it works: A double
can easily hold an int
value without losing precision.
🔐 2. Narrowing Casting (Manual / Risky)
⛔ This must be done manually because you might lose data or precision when converting from a larger type to a smaller one.
Example:
public class NarrowingExample {
public static void main(String[] args) {
double price = 99.99;
int roundedPrice = (int) price; // double → int (manual)
System.out.println("Rounded: " + roundedPrice); // Output: 99
}
}
⚠️ The decimal .99
is cut off, not rounded — casting simply truncates the value.
🔎 Real-World Example: Invoice Round-Off
public class InvoiceDemo {
public static void main(String[] args) {
double billAmount = 1234.75;
int payable = (int) billAmount; // Remove decimals
System.out.println("Original Amount: ₹" + billAmount);
System.out.println("Payable Amount: ₹" + payable);
}
}
⚖️ Widening vs Narrowing – Quick Summary
Cast Type | From → To | Automatic? | Risk of Data Loss |
---|---|---|---|
Widening | int → double | ✅ Yes | ❌ No |
Narrowing | double → int | ❌ No | ✅ Yes |
💬 GoNimbus Pro Tips
✅ Use widening when possible — it’s safe
✅ Always test narrowing conversions for data loss
✅ When converting user inputs (like strings to numbers), use Integer.parseInt()
or Double.parseDouble()
✅ Avoid unnecessary casts to keep your code clean