What is Down-casting
Answer : Though java automatic type conversions are helpful, they could not fulfill all our needs. Lets say for example if you want to assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is smaller than an int. This kind of conversion is called an explicit or narrowing conversion because you are explicitly making the value narrower so that it will fit into the target type.
To do explicit conversion between two incompatible types, you would need to use a cast. A cast is simply an explicit type conversion. Below is its general form:
(target-type) value
Please have example below:
package com.javahonk.implicitCasting; public class ExplicitCastingExample { public static void main(String[] args) { // initialize double double f = 100; // explicit or narrow conversion from double to float float e = (float) f; // explicit or narrow conversion from float to long long d = (long) e; // explicit or narrow conversion from long to int int c = (int) d; // explicit or narrow conversion from int to short short b = (short) c; // explicit or narrow conversion from short to byte byte a = (byte) b; System.out.println("All value explictely converted:"); System.out.println("byte: " + a); System.out.println("shot: " + b); System.out.println("int: " + c); System.out.println("long: " + d); System.out.println("float: " + e); System.out.println("double: " + f); } }
Output:
All value explictely converted: byte: 100 short: 100 int: 100 long: 100 float: 100.0 double: 100.0