Java Type Casting

 Type casting in Java refers to converting a value of one data type to another. This is often necessary when you're working with different types of variables or objects in your program. Java supports two types of casting:

  1. Implicit Casting (Widening Conversion): This is when you convert a smaller data type into a larger one, as it can be done automatically by the Java compiler without loss of information. For example:
int numInt = 100; double numDouble = numInt; // Implicit casting from int to double
System.out.println(numDouble); // Output: 100.0

  1. Explicit Casting (Narrowing Conversion): This is when you convert a larger data type into a smaller one, which may result in loss of data. It requires explicit declaration and is done by placing the type in parentheses before the value. For example:
double numDouble = 100.55; int numInt = (int) numDouble; // Explicit casting from double to int System.out.println(numInt); // Output: 100

Here are a few more examples demonstrating different types of casting:


// Widening Conversion (Implicit Casting) int intValue = 100; long longValue = intValue; // Implicit casting from int to long float floatValue = longValue; // Implicit casting from long to float double doubleValue = floatValue; // Implicit casting from float to double // Narrowing Conversion (Explicit Casting) double doubleNum = 100.55; int intNum = (int) doubleNum; // Explicit casting from double to int short shortNum = (short) intNum; // Explicit casting from int to short byte byteNum = (byte) shortNum; // Explicit casting from short to byte

Remember, when narrowing conversions are performed, there is a risk of losing data or precision, so be cautious when using explicit casting.

Previous Post Next Post

Welcome, New Friend!

We're excited to have you here for the first time!

Enjoy your colorful journey with us!

Welcome Back!

Great to see you Again

If you like the content share to help someone

Thanks

Contact Form