What is Casting?
Casting is used when we want to convert on data type to another.
1. Implicit Casting
Implicit Casting is done by the compiler. Good examples of implicit casting are all the automatic widening conversions i.e. storing smaller values in larger variable types.
int value = 100;
long number = value; //Implicit Casting
float f = 100; //Implicit Casting
2. Explicit Casting
Explicit Casting is done through code. Good examples of explicit casting are the narrowing conversions. Storing larger values into smaller variable types;
long number1 = 25678;
int number2 = (int)number1;//Explicit Casting
//int x = 35.35;//COMPILER ERROR
int x = (int)35.35;//Explicit Casting
Explicit casting would cause truncation of value if the value stored is greater than the size of the variable.
int bigValue = 280;
byte small = (byte) bigValue;
System.out.println(small);//output 24. Only 8 bits remain.
No Comments Yet!!