- 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 you cast a Byte object to a double value 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 (“( )”).
For every primitive variable a wrapper class is available, the objects of these wrapper classes wraps their respective primitive variable.
- Autoboxing− The implicit conversion of a primitive variable to its wrapper class object is known as autoboxing.
Integer i = 20;
- Unboxing− In the same way the conversion of a wrapper class object to a primitive variable is known as unboxing.
int i = new Integer(400);
Casting Byte object to double
Yes, you can cast Byte object to a double value, to do so, you just need to assign byte object to byte variable, internally it will be −
- Unboxed as primitive byte value.
- And, implicitly casted to double (widening).
Example
import java.util.Scanner; public class CastingExample { public static void main(String args[]){ //Reading a byte value form user Scanner sc = new Scanner(System.in); System.out.println("Enter a byte value: "); byte by = sc.nextByte(); //Creating a Byte object using the obtained value Byte byteObject = new Byte(by); //Converting the byte object into a double double d = byteObject; //Printing the result System.out.println("double value: "+d); } }
Output
Enter a byte value: 24 double value: 24.0
Advertisements