Sub topic 3
Declaring and Initializing Variables
This chapter covers how to declare a variable in Apex, how to give it a value, and what state it holds before you do. It assumes you know basic programming ideas (variables, expressions, conditionals) and can run anonymous Apex in the Developer Console or an IDE. Scope, constants, and null get their own chapters, so they appear here only where they affect declarations.
The declaration syntax
Apex is statically typed. Every variable has a declared type, and that type cannot change. The type comes first, then the name, then an optional initializer.
Integer count = 5;
Long population = 8000000000L;
Double ratio = 0.5;
Decimal price = 19.99;
String name = 'Acme';
Boolean isActive = true;
Date today = Date.newInstance(2026, 11, 30);
System.debug(name + ' ' + count);The general form is:
Type variableName [= expression];A few rules apply to every declaration:
- Names are case-insensitive.
count,Count, andCOUNTall refer to the same variable. By convention, variable names use camelCase. - A name must start with a letter, and it cannot be a reserved word such as
classorstatic. - Strings use single quotes. Double quotes are a syntax error.
- Statements end with a semicolon.
- Apex has no
varkeyword, so the type is always written out. Type inference does not exist in the language.
Declaring without initializing
You can declare a variable and assign it later. You can also declare several variables of the same type in one statement.
Integer a, b = 2, c;
a = 1;
c = a + b;
System.debug(c);Be careful with the default value of an uninitialized variable. Apex does not leave a local variable undefined, and it does not set numbers to zero. Every uninitialized variable starts as null.
String note;
System.debug(note == null);
Integer total = null;
System.debug(total == null);Both lines print true. This matters most for Integer, Decimal, and Boolean. In some languages these types default to 0 or false. In Apex they default to null, and using them in arithmetic or in an if condition throws a System.NullPointerException.
Integer total;
total += 1; // throws System.NullPointerExceptionInitialize numeric accumulators explicitly:
Integer total = 0;
total += 1;
System.debug(total);Choosing a type for the initializer
The value you assign must be compatible with the declared type. Apex converts some values automatically, such as an Integer to a Long or Decimal, but it will not convert in the other direction without help. The next example shows the difference between literals.
Long big = 8000000000L; // L suffix marks a Long literal
Decimal exact = 19.99; // a decimal literal fits Decimal
Double approx = 19.99; // also valid, but stored as binary floating point
Integer whole = 42;Two details are worth knowing:
- An integer literal without
Lthat is larger than 2,147,483,647 is a compile error. AddLto make it aLong. Decimalis the usual choice for currency, because it stores exact base-10 values.Doubleis subject to ordinary floating-point rounding.
Initializing collections and sObjects
Collections and sObjects are also variables, and they are declared the same way. For collections, a new expression creates the object, and an initializer in braces can fill it.
List<Integer> numbers = new List<Integer>{ 1, 2, 3 };
Set<String> tags = new Set<String>{ 'a', 'b' };
Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 10 };
System.debug(numbers.size());
System.debug(stock.get('pens'));
System.debug(stock.get('missing'));The last line prints null, because Map.get returns null for a key that is not present. It does not throw an error.
A collection variable that you declare but do not create is null, and calling a method on it fails.
List<String> names;
// names.add('x'); // would throw System.NullPointerException
names = new List<String>();
names.add('x');
System.debug(names);The same rule applies to an sObject variable. Account acc; is null until you write new Account() or assign a query result.
Account acc = new Account(Name = 'Acme');
System.debug(acc.Name);Initialization and the declared type
Because the declared type controls what you can do with a variable, the type you pick affects later code. A wider type can hold a narrower value, and a generic type can hold a more specific one.
Integer small = 7;
Long widened = small;
Decimal asDecimal = widened;
Object anything = 'text';
System.debug(asDecimal);Going the other way requires a conversion, which the chapter on type conversion covers. For now, remember that assignment checks the types at compile time. If the types do not fit, the code does not compile.
Redeclaring a name
You cannot declare two variables with the same name in the same scope, and Apex also rejects a nested block that reuses the name of a variable from an enclosing block.
Integer x = 1;
if (true) {
// Integer x = 2; // compile error: duplicate variable x
}This is stricter than in Java, where the same restriction applies, but it differs from languages such as JavaScript that allow shadowing. Choose distinct names when you nest blocks.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Assuming `Integer total;` is `0` | `NullPointerException` on `total += 1` | Write `Integer total = 0;` |
| Using a null `Boolean` in `if` | `NullPointerException` | Initialize to `false` or compare with `== true` |
| Calling `add` on an uninitialized `List` | `NullPointerException` | Create it with `new List<T>()` |
| Writing `String s = "text";` | Compile error | Use single quotes |
| Writing a large number without `L` | Compile error | Use `Long x = 8000000000L;` |
| Expecting `Count` and `count` to differ | Duplicate variable error | Use distinct names |
How declaration relates to the type system
Practice
Exercise
What do the following lines print, and why? Integer count; Boolean ready; System.debug(count == null); System.debug(ready == null);
Show answer
Both lines print true. Apex sets every uninitialized variable to null, including Integer and Boolean. It does not use 0 or false as the default.
Exercise
This code throws an exception. Fix it with the smallest change. Integer total; for (Integer i = 1; i <= 3; i++) { total += i; } System.debug(total);
Show answer
Initialize total to 0 with Integer total = 0;. The loop then adds 1, 2, and 3, and the code prints 6. Without the initializer, total is null and total += i throws a NullPointerException.
Exercise
Which declaration is valid: Long big = 8000000000; or Long big = 8000000000L;? Why?
Show answer
The second. Without the L suffix, the literal is treated as an Integer, and 8,000,000,000 is larger than the Integer maximum of 2,147,483,647, so the first line does not compile.