Sub topic 3
Declaring and initializing variables
This chapter assumes you know what a variable is and have run anonymous Apex in the Developer Console or an IDE. It also assumes you can name the primitive types from the previous chapter.
The declaration syntax
Apex is statically typed. Every variable declaration names its type first, then the variable name, and optionally an initial value.
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 pattern is Type name = value;. The compiler checks the type when you save the code. Assigning a String to an Integer variable fails at compile time, not at run time.
Apex has no var keyword, so you cannot ask the compiler to infer the type. You always write it out.
A few rules apply to names:
- Names are case-insensitive.
countandCOUNTrefer to the same variable. - You cannot reuse a name in the same scope. A second
Integer countin the same block is a compile error. - Reserved words such as
classorstaticcannot be variable names.
Declaring without a value
You can declare a variable and assign it later. Until you assign a value, the variable holds null.
String note;
System.debug(note == null);
Integer total = null;
System.debug(total == null);Both lines print true. This applies to every type, including Integer, Boolean, and Decimal. Apex does not default numbers to 0 or booleans to false, as some other languages do.
diagram mermaidWhy null matters at declaration time
Reading a null variable is legal. Operating on it is not. The following code compiles, then fails when it runs:
Integer attempts;
attempts += 1;This throws a System.NullPointerException, because attempts is null and null + 1 has no meaning. The fix is to initialize at declaration:
Integer attempts = 0;
attempts += 1;
System.debug(attempts);Initializing from expressions
The right-hand side can be any expression that produces a compatible type: a literal, another variable, a method call, or a calculation.
Integer base = 10;
Integer doubled = base * 2;
String greeting = 'Hello, ' + 'Apex';
Date tomorrow = Date.newInstance(2026, 11, 30).addDays(1);
System.debug(doubled + ' ' + greeting + ' ' + tomorrow);Apex evaluates the right side first, then stores the result in the variable. Implicit widening is allowed. For example, you can assign an Integer to a Long. Narrowing is not allowed without an explicit conversion, which a later chapter covers.
Exercise
What does this code do, and why? Boolean ready; if (ready) { System.debug('go'); }
Show answer
It compiles but throws a System.NullPointerException at run time. The variable ready is declared without a value, so it holds null rather than false. A null Boolean cannot be used as a condition. Initialize it with Boolean ready = false;.