Java Type Casting Rules: Widening & Narrowing

⏳ Day 14 – 1 Minute Java Clarity – Type Casting in Java Converting one type to another… but Java has rules! 👀 📌 What is Type Casting? Assigning a value of one data type to another type. 👉 Java has 2 types of casting. 📌 1️⃣ Widening (Automatic) Small → Big type. Java does it automatically ✅ int num = 100; double result = num; System.out.println(result); // 100.0 ✔ No data loss ✔ JVM handles it automatically 📌 2️⃣ Narrowing (Manual) Big → Small type. You must do it explicitly ⚠️ double price = 99.99; int rounded = (int) price; System.out.println(rounded); // 99 ⚠️ Decimal part is lost — not rounded, just cut off! 💡 Real-time Example: Think of a payment system — price is 499.99 When you cast to int for processing → you get 499 That 0.99 is gone forever 😬 ⚠️ Interview Trap: byte b = (byte) 130; System.out.println(b); // -126 👉 byte range is -128 to 127 — 130 overflows and wraps around! 💡 Quick Summary ✔ Widening → automatic, safe, no data loss ✔ Narrowing → manual, risky, data loss possible ✔ Watch out for overflow in narrowing! 🔹 Next Topic → static keyword in Java Have you ever lost data because of narrowing casting? 👇 #Java #JavaProgramming #TypeCasting #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories