Member-only story

Casting in Java

Rishi
3 min readDec 31, 2024

Casting is an essential concept in Java that allows developers to convert one type of data into another. This operation is particularly useful when working with variables of different data types and is a fundamental feature of Java’s type system. In this blog, we will delve into the concept of casting, its types, and practical use cases.

What is Casting?

Casting in Java is the process of converting a variable from one data type to another. It can be broadly categorized into two types:

  1. Implicit Casting (Widening Conversion)
  2. Explicit Casting (Narrowing Conversion)

1. Implicit Casting (Widening Conversion)

Implicit casting happens automatically when a smaller data type is assigned to a larger data type. This type of casting does not require any explicit syntax because there is no loss of information.

Example:

public class ImplicitCasting {
public static void main(String[] args) {
int intValue = 42;
double doubleValue = intValue; // Implicit casting

System.out.println("Integer Value: " + intValue);
System.out.println("Double Value: " + doubleValue);
}
}

Output:

Integer Value: 42
Double Value: 42.0

--

--

Rishi
Rishi

Written by Rishi

Tech professional specializing in Java development and caching logic with expertise in SaaS and automation. https://rishi-preethamm.blogspot.com

No responses yet