0
0
Javaprogramming~5 mins

Type casting in Java

Choose your learning style9 modes available
Introduction

Type casting helps you change a value from one type to another so your program can work with different kinds of data easily.

When you want to convert a number with decimals to a whole number.
When you need to store a bigger number into a smaller type carefully.
When you want to treat a value as a different type temporarily.
When you want to convert between compatible types like int to double or double to int.
Syntax
Java
targetType variable = (targetType) value;

The targetType is the type you want to convert to.

The value after the cast operator is the original value you want to cast.

Examples
This converts the decimal number 3.14 to the whole number 3 by cutting off the decimal part.
Java
int x = (int) 3.14;
This converts the whole number 5 to a decimal number 5.0.
Java
double y = (double) 5;
This converts the number 130 to a byte, which may cause overflow because byte can only hold -128 to 127.
Java
byte b = (byte) 130;
Sample Program

This program shows how to cast a double to an int and an int to a double. It prints the values before and after casting.

Java
public class Main {
    public static void main(String[] args) {
        double pi = 3.99;
        int wholeNumber = (int) pi;
        System.out.println("Double value: " + pi);
        System.out.println("After casting to int: " + wholeNumber);

        int number = 100;
        double decimalNumber = (double) number;
        System.out.println("Int value: " + number);
        System.out.println("After casting to double: " + decimalNumber);
    }
}
OutputSuccess
Important Notes

Casting from a bigger type to a smaller type can lose data or cause unexpected results.

Automatic casting (called widening) happens when going from smaller to bigger types, like int to double.

Explicit casting (called narrowing) is needed when going from bigger to smaller types, like double to int.

Summary

Type casting changes a value from one type to another.

Use explicit casting when converting from bigger to smaller types.

Be careful of data loss when casting to smaller types.