Explicit Type Casting
There are some cases where if the datatype remains unchanged, it can give incorrect output. In such cases, typecasting can help to get the correct output and reduce the time of compilation. In explicit type casting, we have to force the conversion between data types. This type of casting is explicitly defined within the program.
// C program to illustrate the use of
// typecasting
#include <stdio.h>
// Driver Code
int main()
{
// Given a & b
int a = 15, b = 2;
float div;
// Division of a and b
div = (float)a / b; // Typecasting int to float
printf("The result is %f\n", div);
return 0;
}
public class Main {
public static void main(String[] args) {
// Given a & b
int a = 15, b = 2;
float div;
// Division of a and b
div = (float) a / b; // Typecasting int to float
System.out.println("The result is " + div);
}
}
# Function to perform division and print the result
def main():
# Given values of a and b
a = 15
b = 2
# Division of a and b (typecasting int to float for accurate division)
div = float(a) / b
# Printing the result
print("The result is", div)
# Calling the main function
if __name__ == "__main__":
main()
// Given a & b
let a = 15, b = 2;
let div;
// Division of a and b
div = parseFloat(a) / b; // Typecasting int to float
console.log("The result is " + div);
Output
The result is 7.000000
Type Casting in Programming
In programming, variables hold data of specific types, such as integers, floating-point numbers, strings, and more. These data types determine how the computer interprets and manipulates the information. Type casting becomes necessary when you want to perform operations or assignments involving different data types. In this blog, we will explore type casting, its importance, and the various methods used in different programming languages.
Table of Content
- What is Type Casting
- Types of Type Casting
- Implicit Type Casting
- Explicit Type Casting
- Difference between Implicit and Explicit Type Casting
- Type Compatibility and Safety in Programming
- Type Casting between Basic Data Types
- Challenges and Best Practices of Type Casting in Programming