Type Casting
Swipe to show menu
In Java, every value has a specific type, and sometimes we need to convert a value from one type to another. This is called type casting.
There are two types of casting:
- Implicit casting;
- Explicit casting.
Implicit Casting
Implicit casting happens when Java automatically converts a smaller type into a larger type. This is safe because no data is lost:
int lattePrice = 5;
double priceDecimal = lattePrice; // becomes 5.0
This works because a larger type like double can easily hold everything a smaller type like int can.
Explicit Casting
Explicit casting happens when a larger type is manually converted into a smaller type. This is required because data might be lost during conversion:
double lattePrice = 4.99;
int roundedPrice = (int) lattePrice; // becomes 4
Java removes the decimal part and stores only 4. Unlike implicit casting, this must be written manually using (type).
A simple way to remember:
- small → big = automatic;
- big → small = manual.
Example
Main.java
1234567891011121314151617package com.example; public class Main { public static void main(String[] args) { int lattePrice = 5; // implicit casting double priceDecimal = lattePrice; System.out.println(priceDecimal); // 5.0 // explicit casting double realPrice = 4.99; int roundedPrice = (int) realPrice; System.out.println(roundedPrice); // 4 } }
The example first implicitly casts int to double — Java does this automatically and the result becomes 5.0. Then we explicitly cast double to int using (int), which drops the decimal and prints 4.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat