What is Typecasting in Java and how does it work? What is typecasting in Java?
In this blog , I will talk about the fundamentals of Type Casting and there its topics in Java.
- What is type casting
- How many types of casting are there in Java?
- What is the difference between explicit and implicit casting in Java?
- What are implicit and explicit casting explain with the help of example Java?
There are two types of typecasting in java:-
1. Implicit type Casting in Java
2.Explicit type casting in Java
1. Implicit type Casting in Java
In implicit typecasting , low rang datatype value is automatically convert in to high range datatype values. It is also known as Widening Casting.
For example-
public class Main
{
public static void main(String args[])
{
int num1 = 200;
double num2 = num1; // Automatic casting: short to int
System.out.println(num1);
System.out.println(num2);
}
}
byte
-> short
-> char
-> int
-> long
-> float
-> double
2. Explicit type casting in Java
In this type of typecasting high range datatype value is converted in to low range datatype value explicitilly by the programmers.
In other words If we want to assign a value of a larger data type to a smaller data type we perform explicit type casting. It is also known as Narrowing casting. It must be done manually by placing the type in parentheses in front of the value.
For example-
public class Main
{
public static void main(String args[])
{
double num1 = 200.75;
int num2 = (int) num1; // Explicit casting: double to int
System.out.println(num1);
System.out.println(num2);
}
}
double
-> float
-> long
-> int
-> char
-> short
-> byte
I hope you know What is Typecasting in Java and how does it work? What is typecasting in Java? Must have understood very well. If you have any doubts in this blog, then you can write for it in the below comment box. There is one more request from you that you must tell your friends about this blog and share it on as many social media accounts as Facebook, What's app or others.
What is Typecasting in Java and how does it work? What is typecasting in Java?
By- Today Gyan
Learn more:-