Free Salesforce Developers Tutorials >

Chapter 3 - Apex Datatypes and Operators >

What is the Rule of Conversions in Apex?

What is the Rule of Conversions in Apex?

What You’ll Learn

S2 Labs

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

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *