Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 36 ยท Apex Basics

Variables and Data Types in Apex

Learn Apex variables and primitive data types (Integer, Long, Decimal, Boolean, String, Id), null handling, constants with final and type conversion.

Apex is statically typed: every variable has a type that is fixed when you declare it, and the compiler checks your code against those types. This catches many mistakes before the code ever runs. If you have used Java or C#, the rules will look familiar, with a few Salesforce-specific types added.

Declaring variables

A declaration gives the type, then the name, and optionally an initial value:

Java
Integer count = 0;
String greeting = 'Hello';
Boolean isActive = true;
Decimal price = 19.99;

Rules to remember:

  • Names can contain letters, digits and underscores, and cannot start with a digit.
  • Names are case-insensitive: Count and count are the same variable, so you cannot declare both in one scope.
  • A variable declared inside { } exists only inside those braces (its scope).
  • A variable you do not initialise holds null, not zero or an empty string.

The primitive types

Type Holds Example
Integer 32-bit whole number 42
Long 64-bit whole number 3000000000L
Double 64-bit floating point 3.14
Decimal Exact decimal, used for currency 19.99
Boolean true, false or null true
String Text, in single quotes 'Ada'
Date A date without time Date.newInstance(2026, 5, 17)
Datetime A date and time Datetime.now()
Time A time of day Time.newInstance(9, 30, 0, 0)
Id An 18-character Salesforce record Id '001xx000003DGb2AAG'
Blob Binary data Blob.valueOf('abc')

Two choices beginners often get wrong:

  1. Use Decimal for money. Double cannot represent values like 0.1 exactly, so sums drift. Decimal is exact and has rounding helpers such as setScale(2).
  2. Id is not a plain string. Salesforce validates that it looks like an Id and treats 15- and 18-character forms as equal. You can assign a valid Id string to an Id variable, but not an arbitrary text.

Why Decimal for money

You can see the difference with a Java stand-in. double accumulates tiny errors; BigDecimal (Java's equivalent of Apex's Decimal) does not.

Java Stand-in (Java): double versus Decimal-style arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

null: the empty value

null means "no value". Using it carelessly is the most common source of runtime errors in Apex: calling a method on a null variable throws System.NullPointerException (shown as "Attempt to de-reference a null object").

Java
String name;                  // null
System.debug(name.length());  // NullPointerException

Integer total;                // null
Integer next = total + 1;     // NullPointerException too

Defensive habits:

Java
if (name != null && name.length() > 0) { /* safe */ }
String safe = String.isBlank(name) ? 'unknown' : name;   // isBlank handles null, '' and spaces
Integer count = (total == null) ? 0 : total;

Salesforce fields are often null: a Number field nobody filled in reads as null, not 0. Always guard before doing arithmetic on field values.

Constants with final

Use final for a value that must not change after it is set. Combine it with static to create a class-wide constant:

Java
public class Pricing {
    public static final Decimal TAX_RATE = 0.2;
    public static final String DEFAULT_CURRENCY = 'USD';
}

By convention constants use UPPER_SNAKE_CASE. Constants avoid "magic numbers" scattered through code and make rules easy to change in one place.

Type conversion

Apex converts some types automatically (an Integer can become a Decimal), but narrowing needs an explicit call:

Java
Integer i = 7;
Decimal d = i;                       // automatic widening
Integer back = d.intValue();         // explicit narrowing
Integer parsed = Integer.valueOf('42');   // text to number
String text = String.valueOf(42);         // number to text

Parsing text that is not a number throws System.TypeException, so check or catch first.

Type inference and Object

Object is the parent of everything and can hold any value, which is useful with JSON and generic code. Cast it back before use:

Java
Object value = 42;
Integer n = (Integer) value;   // explicit cast

If the cast is wrong, Apex throws a System.TypeException, so test with value instanceof Integer first.

Java Stand-in (Java): safe parsing and null checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which type should you use to store a price?

    Decimal is exact, so sums of values like 0.1 do not drift. Double is a binary floating-point type with rounding errors.
  2. 2. What is the default value of an uninitialised Integer variable?

    Uninitialised variables are null in Apex, which is why arithmetic on them throws a NullPointerException.
  3. 3. Are count and COUNT different variables in Apex?

    Apex identifiers are case-insensitive, so both names refer to the same variable.
  4. 4. What does final do?

    A final variable can be assigned once. With static, it becomes a class-wide constant.

Summary

  • Apex is statically typed and case-insensitive.
  • Use Decimal for money, Id for record Ids and String (single quotes) for text.
  • Uninitialised variables and many empty fields are null; guard before using them.
  • final creates constants; explicit conversions like Integer.valueOf turn text into numbers.

Next: Strings, Numbers and Dates