What is the Rule of Conversions in Apex?
Chapter Topics
- Apex Data Types
- Integer Data Type in APEX
- Floating Point Data Type in APEX
- String Data Type in APEX
- Date Datatypes in APEX
- Time and DateTime Data Types in APEX
- Boolean Datatype in Salesforce
- ID & Blob Datatypes in APEX
- What is the Rule of Conversions in Apex?
- Enums in APEX
- sObjects in Salesforce
- Generic sObjects in Salesforce
- Collections in APEX
- Lists in APEX
- List Array Notation in APEX
- Lists Initialization in APEX
- Nested Lists in APEX
- Sets in APEX
- Sets Initialization And Methods
- Maps in APEX
- Map Initialization Methods in APEX
- Operators in Apex and Their Types
- Shorthand Operator
- Equality Operator
- Relational Operators(<,>,<=,>=)
In general, apex requires explicit conversion from one datatype to another; however, a few datatypes can be implicitly converted, such as variables of lower numeric type to higher types.
For example, a variable of the Integer data type cannot be implicitly converted to a String. You must use the string. format method. However, a few data types can be implicitly converted without using a method.
There is a hierarchy of types in numbers. It is always possible to assign variables of lower numeric types to higher types without the need for explicit conversion. The following is the hierarchy for numbers, from lowest to highest:
- Integer
- Long
- Double
- Decimal
Once a value has been passed from a number of lower types to a number of higher types, it is converted to the higher type of number.
Things to Keep in Mind
- Ids can always be assigned to strings.
- Strings can be assigned to IDs; however, at runtime, the value is checked to ensure that it is a legitimate ID; if it is not, a runtime error is thrown.
- If the numeric value on the right-hand side exceeds the maximum value for an integer, you get a compilation error. In this case, the solution is to append L or l to the numeric value so that it represents a long value with a wider range.
- Arithmetic computations that produce values more significant than the max values of the current type are set to overflow.
Example of Rule of Conversion
Double d = 2.355;
Integer i = d; // Compile time error
Integer i = (Integer)d; // Will work
Integer i2 = 5;
Double d =I;
Integer i3 = d; // Will not work compile time error
Next Topic
Need more support?
Get a head start with our FREE study notes!
Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.