Can we cast a double value to a byte in java?


Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects).

Casting in Java

Converting one primitive data type into another is known as type casting. There are two types of casting −

  • Widening− Converting a lower datatype to a higher datatype is known as widening. It is done implicitly.
  • Narrowing− Converting a higher datatype to a lower datatype is known as narrowing. You need to do it explicitly using the cast operator (“( )”).

Casting double to byte

Double is a higher datatype compared to byte. Therefore, double value will not be converted into byte implicitly, you need to convert it using the cast operator.

Example

 Live Demo

import java.util.Scanner;
public class CastingExample {
   public static void main(String args[]){
      //Reading a double value form user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a double value: ");
      double d = sc.nextDouble();
      //Converting the double value to byte
      byte by = (byte) d;
      //Printing the result
      System.out.println("byte value: "+by);
   }
}

Output

Enter a double value:
102.365
byte value: 102

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements