Hello everyone! It's a new year and the first Friday of this year, so time for another blog.
Today on the table, we have an exciting and relatively unheard topic in Java - "Typecasting."
What is Typecasting?
Typecasting is When we assign a value of one primitive data type to another type—for example, converting from int to double or byte to short.
There are two types of typecasting:-
Widening or Automatic Type Conversion- As the name suggests, automatic type conversion happens when two types are compatible. In this case, the most important is that the destination type's size is larger than the source type.
Narrowing or Explicit Type Conversion- When we need to assign a larger type value to a variable of a smaller type, we need to perform explicit typecasting.
Let us understand the above two concepts with a sample code:
public static void main(String[] args)
{
int i=100;
long l1=i; // automatic typecasting where long is converted to int
double d=100.3;
long l2=(long)d; //explicit typecasting
System.out.println(i);
System.out.println(l1);
System.out.println(d);
System.out.println(l2);
}
Output:
100
100
100.04
100
Did you find this article valuable?
Support Ayush Agarwal by becoming a sponsor. Any amount is appreciated!