Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Fundamental Programming S...
  5. Type Conversion and Casting in Java

Type Conversion and Casting in Java

Type Conversion is the process of converting one data type into another.

  • In Java, this is especially important when performing operations between different types (like int and float).

Two Types of Type Conversion in Java:

  • Implicit Conversion
  • Explicit Conversion

1.) Implicit Conversion:

Automatically done by the Java compiler when converting a smaller type to a larger type.

Syntax:

dataType2 var = var1; // var1 is of smaller type

Example:

int a = 10;
double b = a; // int to double
System.out.println(b); // Output: 10.0

2.) Explicit Conversion:

Must be manually done by the programmer when converting a larger type to a smaller type.

Syntax:

dataType2 var = (dataType2) var1; // var1 is of larger type

Example:

double a = 10.5;
int b = (int) a; // double to int
System.out.println(b); // Output: 10

Best Practices:

  • Use implicit conversion when possible.
  • Use explicit casting carefully to avoid unexpected results.
  • Always test for data loss when casting larger to smaller types.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *