Typecasting in Java
Typecasting in Java is assigning a value of one type to a variable of another type. When you assign value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion (Widening ) and if not then they need to be casted or converted explicitly(narrowing).
2 types of Type Casting in java –
- Automatic Type Conversion (Widening – implicit)
- Narrowing (Explicit)
Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens when:
- The two data types are compatible.
- When we assign value of a smaller data type to a bigger data type.
Example Program of Automatic Type Conversion (Widening) –
class Test { public static void main(String[] args) { int i = 100; //automatic type conversion long l = i; //automatic type conversion float f = l; System.out.println("Int value "+i); System.out.println("Long value "+l); System.out.println("Float value "+f); } }
Long value 100
Float value 100.0
Narrowing or Explicit Type Conversion
If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or narrowing.
- This is useful for incompatible data types where automatic conversion cannot be done.
- Here, target-type specifies the desired type to convert the specified value to.
Example Program of Explicit Type Conversion (Narrowing) –
//Java program to illustrate explicit type conversion class Test { public static void main(String[] args) { double d = 100.04; //explicit type casting long l = (long)d; //explicit type casting int i = (int)l; System.out.println("Double value "+d); //fractional part lost System.out.println("Long value "+l); //fractional part lost System.out.println("Int value "+i); } }
Long value 100
Int value 100
I must express my thanks to the writer for bailing me out of such a difficulty. After checking throughout the world-wide-web and seeing tricks which were not helpful, I figured my life was gone. Existing minus the solutions to the issues you have fixed by means of the short article is a critical case, and those that could have badly affected my career if I had not noticed your website. That training and kindness in taking care of the whole thing was important. I’m not sure what I would have done if I had not discovered such a subject like this. I’m able to at this moment look ahead to my future. Thanks for your time very much for your skilled and amazing guide. I will not hesitate to refer your web site to any individual who desires direction about this subject matter.