Type casting in Java

 

✅ What is Type Casting?

Type Casting in Java is the process of converting a value from one data type to another.

Java has two types of type casting:

  1. Widening (Implicit) Casting – small → large type

  2. Narrowing (Explicit) Casting – large → small type


🔹 1. Widening Type Casting (Automatic)

Definition: Converting a smaller data type to a larger one.
👉 Safe conversion – done automatically by Java.

🔸 Example:


public class WideningExample { public static void main(String[] args) { int a = 10; double b = a; // int → double System.out.println("int value: " + a); System.out.println("double value: " + b); } }

Output:


int value: 10 double value: 10.0

✅ Widening Order:

byteshortintlongfloatdouble


🔹 2. Narrowing Type Casting (Manual)

Definition: Converting a larger data type to a smaller one.
👉 Not safe automatically, so explicit casting is required.

🔸 Example:


public class NarrowingExample { public static void main(String[] args) { double a = 9.78; int b = (int) a; // double → int System.out.println("double value: " + a); System.out.println("int value: " + b); } }

Output:


double value: 9.78 int value: 9

⚠️ Decimal part is lost during narrowing.


🔸 Example with Character


public class CharCasting { public static void main(String[] args) { char c = 'A'; int ascii = c; // char → int (widening) System.out.println("ASCII of A is: " + ascii); int n = 66; char ch = (char) n; // int → char (narrowing) System.out.println("Character of 66 is: " + ch); } }

🔹 Summary Table

Type    Conversion Example    Casting Needed?
Widening    int → double    ❌ No
Narrowing    double → int    ✅ Yes
Char to Int        'A' → 65    ❌ No
Int to Char    65 → 'A'    ✅ Yes

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism