DEV Community

Vigneshwaralingam
Vigneshwaralingam

Posted on

πŸ•Day 11 Java learning :

Great! Here's a clean, focused Day 11 Java learning note for you β€” about Data Type Conversion. I’ll cover:

  • βœ… What it is
  • ❓ Why we need it
  • πŸ• When we use it
  • πŸ”§ How to use it
  • πŸ”„ All conversion paths (byte β†’ short β†’ int β†’ long β†’ float β†’ double, etc.)

You can directly use this for your daily log or even turn it into a blog/PDF later!


πŸ“˜ Day 11 β€” Java Data Type Conversion


πŸ”Ή What is Data Type Conversion in Java?

Data Type Conversion means converting one data type into another.

Java supports:

  • βœ… Widening Conversion β†’ done automatically
  • βœ… Narrowing Conversion β†’ needs manual casting

❓ Why Do We Need It?

  • To store values in compatible types
  • To perform operations between different data types
  • To avoid errors during assignment or calculations
  • To support method overloading, user input, etc.

πŸ• When Do We Use It?

  • During mathematical operations
  • While assigning variables of different types
  • When reading input (like from Scanner)
  • In functions/methods that require specific types

πŸ”§ How to Use It?

1. Widening Conversion (Automatic)

No cast needed β€” Java does it for you.

byte b = 10;
short s = b;   // byte β†’ short
int i = s;     // short β†’ int
long l = i;    // int β†’ long
float f = l;   // long β†’ float
double d = f;  // float β†’ double

System.out.println(d);  // Output: 10.0
Enter fullscreen mode Exit fullscreen mode

2. Narrowing Conversion (Manual)

You must cast manually. Risk of data loss.

double d = 99.99;
float f = (float) d;
long l = (long) f;
int i = (int) l;
short s = (short) i;
byte b = (byte) s;

System.out.println(b);  // Output: May lose precision
Enter fullscreen mode Exit fullscreen mode

πŸ”„ Full Widening Conversion Chart

From To
byte short, int, long, float, double
short int, long, float, double
int long, float, double
long float, double
float double
char int, long, float, double

βœ… All above conversions are automatic (widening).


πŸ”„ Full Narrowing Conversion Chart

From To Needs Casting?
double float, long, int, short, byte βœ… Yes
float long, int, short, byte βœ… Yes
long int, short, byte βœ… Yes
int short, byte βœ… Yes
short byte βœ… Yes
int char βœ… Yes

βœ… Final Tip:

Always prefer widening conversion when possible.

Use narrowing only when needed, and expect data loss or overflow.


Top comments (0)