Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0085 Casting Incompatible Types

A narrowing conversion is to explicitly make the value narrower. A cast is an explicit type conversion. It has this general form: (target-type) value target-type specifies the desired type. The following code casts int type value to byte type value. public class Main { public static void main(String[] argv) { int a = 1234; byte b; b = (byte) a; System.out.println("a is " + a); System.out.println("b is " + b); } } The output: a is 1234 b is -46 Truncation happens when assigning a floating-point value to an integer value. For example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. public class Main { public static void main(String args[]) { byte b; int i = 1; double d = 1.123; System.out.println("Conversion of double to int."); i = (int) d; System.out.println("d: " + d + " i: " + i); System.out.println("Conversion of double to byte."); b = (byte) d; System.out.println("d: " + d + " b: " + b); } } This program generates the following output: Conversion of double to int. d: 1.123 i: 1 Conversion of double to byte. d: 1.123 b: 1