SAVE UP to ₹4999/- OFF On All Salesforce Courses Claim Offer

3

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 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.

Book A 15-Minutes Free Career Counselling Today!