What is implicit casting
Answer : Implicit casting also known as java automatic conversions. When one type of data is assigned to another type of variable, an automatic type conversion will occur if below two conditions is met:
- The two types are compatible.
- The destination type is larger than the source type.
When these two conditions are met, a implicit casting (widening conversion) takes place. Lets take example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required.
For implicit casting or widening conversions numeric types including integer and floating-point types,
are compatible with each other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not compatible with each other then Java performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char. Please have example below:
package com.javahonk.implicitCasting; public class ImplicitCastingTest { public static void main(String[] args) { // initialize byte byte a = 100; // implicit or widening or automatic conversion to short short b = a; // implicit or widening or automatic conversion to int int c = b; // implicit or widening or automatic conversion to long long d = c; // implicit or widening or automatic conversion to float float e = d; // implicit or widening or automatic conversion to double double f = e; System.out.println("All value implicitely 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); // char to int implicit conversion char g = 'f'; int i = g; // Please note when java promotes from char to int // it will print ASCII value of char System.out.println("char to int implicit conversion value: " + i); } }
Output:
All value implicitely converted: byte: 100 shot: 100 int: 100 long: 100 float: 100.0 double: 100.0 char to int implicit conversion value: 102
Please click this link if want to see ASCII code of all characters : ASCII Codes