JAVA Tutorial



TYPE CASTING IN JAVA


Type Casting in Java

Type casting in Java refers to converting one data type to another. This is commonly used when dealing with variables of different types in expressions. Java provides two types of casting: implicit casting (widening) and explicit casting (narrowing).

Why Use Type Casting?

  • Allow operations between different data types
  • Ensure type compatibility in expressions
  • Enhance flexibility in dealing with numbers or objects

Types of Type Casting

  • Implicit Casting (Widening) โ†’ Automatically done by Java when converting a smaller type to a larger type.
  • Explicit Casting (Narrowing) โ†’ Required when converting a larger type to a smaller type, usually involving a cast operator.

๐Ÿงช Examples

// Implicit Casting (Widening)
int intNum = 100;
double doubleNum = intNum;  // No need for explicit casting

// Explicit Casting (Narrowing)
double doubleVal = 9.78;
int intVal = (int) doubleVal;  // Explicitly casting double to int

// Example of type casting with loss of data:
System.out.println("Implicit Casting: " + doubleNum); // Output: 100.0
System.out.println("Explicit Casting: " + intVal);   // Output: 9
  

๐Ÿ“š Explanation

  • Implicit Casting: This happens automatically when a smaller type is assigned to a larger type (like an int to double). No loss of data occurs here.
  • Explicit Casting: This is done manually using the cast operator ((int)), typically when a larger data type is assigned to a smaller one (like double to int). However, explicit casting may result in a loss of data, such as truncating decimal places.

โš ๏ธ Important Notes

  • When performing explicit casting, be aware of potential data loss.
  • Use implicit casting when working with compatible types to avoid unnecessary code.
  • Explicit casting can lead to unexpected results (e.g., truncating decimals), so use with caution.

Tip: Always check the range of the target data type to avoid overflow or underflow issues when narrowing types.

๐Ÿ“ฑ Responsive Tip

When viewing code examples on mobile devices, ensure that the code blocks are scrollable horizontally. This prevents layout breaking on smaller screens.

โœ… Conclusion

Type casting is essential for handling different data types in Java. Understanding when and how to use both implicit and explicit casting ensures you can work with variables of various types without causing errors or data loss.

Practice Task: Create a Java program that uses both implicit and explicit casting. Try to handle a situation where explicit casting results in data loss.


๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review