Thursday, January 30, 2025
HomeProgrammingWhat is type conversion in Java with examples

What is type conversion in Java with examples

In Java, type conversion refers to the process of converting a variable of one data type into another. This is commonly used when different types of data need to be processed together. Java supports two main types of type conversion:


1. Implicit Type Conversion (Widening)

  • Definition: Automatic conversion of a smaller data type to a larger data type.
  • Key Points:
    • Happens automatically (no explicit cast is needed).
    • No data loss occurs because the larger data type can hold all possible values of the smaller type.

Examples of Widening

java
public class ImplicitTypeConversion {
public static void main(String[] args) {
int num = 50; // Integer (4 bytes)
double result = num; // Converted to double (8 bytes)

System.out.println("Integer value: " + num); // Output: 50
System.out.println("Converted to double: " + result); // Output: 50.0

char letter = 'A';
int asciiValue = letter; // Implicitly converts char to int
System.out.println("ASCII value of 'A': " + asciiValue); // Output: 65
}
}

Widening Type Conversion Hierarchy

arduino
byteshortintlongfloatdouble

2. Explicit Type Conversion (Narrowing)

  • Definition: Conversion from a larger data type to a smaller data type.
  • Key Points:
    • Must be explicitly performed by the programmer using type casting.
    • Risk of data loss or truncation if the target type cannot accommodate the value.

Syntax:

java
(targetType) value

Examples of Narrowing

java
public class ExplicitTypeConversion {
public static void main(String[] args) {
double num = 99.99; // Double (8 bytes)
int result = (int) num; // Explicitly converting double to int

System.out.println("Original double value: " + num); // Output: 99.99
System.out.println("Converted to integer: " + result); // Output: 99 (fractional part lost)

long largeNumber = 100000L; // Long (8 bytes)
short smallNumber = (short) largeNumber; // Explicit narrowing
System.out.println("Converted to short: " + smallNumber); // May lose data if out of range
}
}


Wrapper Class Conversion (Autoboxing and Unboxing)

Java automatically converts between primitive types and their corresponding wrapper classes. This is a form of type conversion called autoboxing (primitive → wrapper) and unboxing (wrapper → primitive).

Example of Autoboxing and Unboxing

java
import java.util.ArrayList;

public class WrapperConversion {
public static void main(String[] args) {
// Autoboxing: int → Integer
int num = 10;
Integer boxedNum = num;
System.out.println("Autoboxed Integer: " + boxedNum);

// Unboxing: Integer → int
Integer wrappedValue = 20;
int unboxedValue = wrappedValue;
System.out.println("Unboxed int: " + unboxedValue);
}
}


Type Conversion with Non-Primitive Types

Upcasting (Widening):

Converting a subclass type to a superclass type. This is done implicitly.

Example of Upcasting

java
class Animal {}
class Dog extends Animal {}

public class UpcastingExample {
public static void main(String[] args) {
Dog dog = new Dog();
Animal animal = dog; // Upcasting (implicit)
System.out.println("Upcasting successful.");
}
}

Downcasting (Narrowing):

Converting a superclass type back to a subclass type. This must be done explicitly.

Example of Downcasting

java
class Animal {}
class Dog extends Animal {}

public class DowncastingExample {
public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
Dog dog = (Dog) animal; // Downcasting (explicit)
System.out.println("Downcasting successful.");
}
}


Key Points to Remember

  1. Widening (Implicit Conversion):
    • Safe and automatic.
    • No data loss occurs.
    • Converts smaller to larger types (e.g., intdouble).
  2. Narrowing (Explicit Conversion):
    • Programmer must explicitly cast.
    • May lead to data loss (e.g., doubleint truncates decimals).
  3. Wrapper Classes:
    • Autoboxing and unboxing simplify conversions between primitives and objects.
  4. Object Conversion:
    • Upcasting (safe) is implicit.
    • Downcasting (risky) is explicit.
  5. Use Case: Type conversion is essential when dealing with arithmetic operations, method overloading, or working with collections.

Let me know if you’d like more detailed examples or clarification!

4o
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x