Experience Salesforce

What is the Rule of Conversions in Apex?

What You’ll Learn

  • What is the Rule of Conversions in Apex?

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:

  1. Integer
  2. Long
  3. Double
  4. 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
Salesforce Business Analyst Career Training
Next Topic

Need Extra Support? Our FREE study materials have got you covered.

Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.

cts-img
Rakshabandhan Sale