Java Type Casting: Widening and Narrowing Explained

🚀 Starting My Java Learning Journey – Day 4 🔹 Topic: Type Casting in Java Sometimes in Java, we need to convert one data type into another. This process is called type casting. There are two types of type casting: 1️⃣ Widening Casting (Implicit Casting) ✅Converting a smaller data type to a larger data type ✅Done automatically by Java Example: Converting int to double class Main { public static void main(String[] args) { int num = 10; System.out.println("The integer value: " + num); double data = num; System.out.println("The double value: " + data); } } Output: The integer value: 10 The double value: 10.0 Conversion order: byte → short → int → long → float → double 2️⃣ Narrowing Casting (Explicit Casting) ✅Converting a larger data type to a smaller data type ✅ Must be done manual Example: Converting double to int class Main { public static void main(String[] args) { double num = 10.99; System.out.println("The double value: " + num); int data = (int) num; System.out.println("The integer value: " + data); } } Output: The double value: 10.99 The integer value: 10 💡 Key Point: Widening → Automatic conversion Narrowing → Manual conversion Understanding type casting helps in data conversion and efficient memory usage in Java programs. #Java #JavaLearning #Programming #BackendDevelopment #CodingJourney #TypeCasting

To view or add a comment, sign in

Explore content categories