Type Casting Concept: Casting is the explicit process of converting data from one type to another. This is essential when data is received in a format that is incompatible with the intended operation, such as receiving a numeric age as a string from a user input field.
Narrowing vs. Widening: Widening conversion occurs when moving from a smaller type to a larger one (e.g., Integer to Real), which is usually safe. Narrowing conversion (e.g., Real to Integer) often results in data loss, such as the truncation of decimal places.
Syntax for Conversion: Most languages use specific functions or keywords to perform casting. For example, converting a string to an integer might involve a function like , which transforms the text characters into a mathematical value.
Integer vs. Real (Float): Integers are strictly for whole numbers and are used for counting or indexing. Real numbers include fractional parts and are necessary for precise measurements or scientific calculations.
Character vs. String: A character is a single unit of text (like a letter or symbol), while a string is a collection or array of characters. Strings are often treated as objects with properties like 'length', whereas characters are primitive units.
| Feature | Integer | Real (Float) | String | Boolean |
|---|---|---|---|---|
| Content | Whole numbers | Decimals | Text sequences | True/False |
| Example | "Hello" | |||
| Use Case | Counting items | Financial data | Usernames | Toggle states |
Identify the Input Source: Always check where data is coming from. In many exam scenarios, user input is treated as a String by default, meaning you must cast it to an Integer or Real before performing any math.
Check for Data Loss: When asked about converting a Real number to an Integer, remember that the decimal is usually truncated (cut off), not rounded. For example, cast to an integer becomes .
Boolean Logic: For fields that only have two possible states (Yes/No, On/Off, Pass/Fail), always recommend the Boolean data type. It is the most efficient choice and prevents invalid data entry.
Type Mismatch Errors: If a code snippet fails during a comparison (e.g., ), the error is almost always a type mismatch because a string cannot be logically compared to a numeric value without casting.
String Numbers vs. Integers: A common mistake is assuming that the characters "123" behave like the number 123. Without casting, adding "1" to "123" might result in "1231" (concatenation) rather than 124 (addition).
Character vs. String Length: Students often confuse a single-character string with a character type. While they look the same, a string of length 1 may have different memory overhead and available methods compared to a primitive character type.
Boolean as String: Storing "True" as a string instead of a Boolean value makes logical operations (like AND/OR) impossible without complex string comparisons, leading to inefficient and bug-prone code.