Cast Double to Float

This program demonstrates type casting from a double to a float.

Problem Statement

Write a Java program that casts a double to a float and prints both values.

Source Code

1 public class DoubleToFloat {
2 public static void main(String[] args) {
3 double value = 123.456;
4 float result = (float) value;
5 System.out.println("Double: " + value + ", Float: " + result + " - Eduinq");
6 }
7 }

Program Output

Double: 123.456, Float: 123.456 - Eduinq

Explanation

A double variable value is declared with a decimal value, and (float) value explicitly casts it to a float, after which both the original double and the casted float are printed, demonstrating explicit type casting from double to float and how larger precision types can be converted into smaller precision types, which may lead to rounding differences in certain cases.

Quick Links to Explore