- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements