Explicit Type Casting Examples
Explicit type casting, also known as type conversion, requires a manual instruction from the programmer to convert a value from one type to another. Here are some examples:
Floating Point to Integer:
C#
double pi = 3.14159; int approx_pi = ( int )pi; // Explicitly converts double to int |
Integer to Character:
Python
num = 65 letter = chr (num) # Explicitly converts int to char |
Integer to String:
Java
int number = 123 ; String str = Integer.toString(number); // Explicitly converts int to String |
String to Integer:
C++
std::string str_num = "123" ; int num = std::stoi(str_num); // Explicitly converts string to int |
Char to Integer:
C
char ch = '7' ; int digit = ch - '0' ; // Explicitly converts char to int |
Implicit and Explicit type casting
In programming, type casting is a way to convert data from one type to another. Implicit type casting happens automatically, while explicit type casting requires manual intervention. This article explores the differences between implicit and explicit type casting, their uses, benefits, and considerations in programming.
Table of Content
- What is Type Casting?
- Implicit Type Casting
- Explicit Type Casting
- Implicit Type Casting Syntax
- Explicit Type Casting Syntax
- Implicit Type Casting Examples
- Explicit Type Casting Examples
- Best Practices for Type Casting
Contact Us