What is Type Conversion ?
- Converting a value from one datatype to another.
- It happens when we convert the smaller datatype into larger datatype.
- It happens automatically by java.
- There is no data loss.
- This is called Implicit Type Conversion or Widening.
Example:
public class Main {
public static void main(String[] args) {
int number1 = 10;
double result = number1;
System.out.println(result);
}
}
10.0
- number1 is an integer variable.
- we assigned number1 to result.
- so java automatically converted int to double.
What is Type Casting?
- Converting a value from one data type to another.
- It happens when we convert a larger data type into a smaller data type.
- It is manually performed by the programmer.
- There may be data loss during conversion.
- This is called Explicit Type Casting or Narrowing Conversion.
Example:
public class Main {
public static void main(String[] args) {
double number1 = 10.75;
int result = (int) number1;
System.out.println(result);
}
}
output:
10
- number1 is a double variable.
- We assigned number1 to result using (int).
- So, we manually converted double into int.
- The decimal part .75 is removed.
Top comments (0)