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).
Converting one primitive data type into another is known as type casting. There are two types of casting −
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.
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); } }
Enter a double value: 102.365 byte value: 102