Integers are one of the fundamental primitive data types in Apex. They represent whole numbers without decimal points and are used for counting, indexing, and mathematical calculations.
In Apex, you can declare integer variables using the Integer keyword:
Integer myNumber = 42; Integer count = 0; Integer negativeValue = -10;
Unlike some other programming languages, you don't need to specify different integer types based on size - the Integer type in Apex handles a wide range of values.
The Integer data type in Apex can store values from -2,147,483,648 to 2,147,483,647 (32-bit signed integer). If you need to work with larger numbers, you can use the Long data type instead.
// This is the maximum value an Integer can hold Integer maxValue = 2147483647; // This is the minimum value an Integer can hold Integer minValue = -2147483648;
You can perform various arithmetic operations with integers:
Integer a = 10; Integer b = 3; // Addition Integer sum = a + b; // 13 // Subtraction Integer difference = a - b; // 7 // Multiplication Integer product = a * b; // 30 // Division Integer quotient = a / b; // 3 (note: integer division truncates decimal values) // Modulus (remainder) Integer remainder = a % b; // 1
Sometimes you'll need to convert between integers and other data types:
// String to Integer String numText = '25'; Integer convertedNum = Integer.valueOf(numText); // Decimal to Integer (truncates decimal portion) Decimal price = 29.95; Integer approxPrice = price.intValue(); // 29 // Long to Integer Long largeNumber = 1000L; Integer normalNumber = largeNumber.intValue();
The Integer class in Apex provides several useful methods:
// valueOf() converts other types to Integer
Integer num1 = Integer.valueOf('42');
Integer num2 = Integer.valueOf(42.5); // Truncates to 42
// abs() returns the absolute value
Integer negative = -25;
Integer positive = Math.abs(negative); // 25
// max() and min() find the larger or smaller of two numbers
Integer larger = Math.max(10, 20); // 20
Integer smaller = Math.min(10, 20); // 10
Integers are commonly used in collections like Lists and Maps:
// List of integers
List<Integer> numberList = new List<Integer>{1, 2, 3, 4, 5};
// Adding to the list
numberList.add(6);
// Accessing elements (indexing starts at 0)
Integer thirdNumber = numberList[2]; // 3
// Map with Integer keys
Map<Integer, String> employeeIds = new Map<Integer, String>();
employeeIds.put(1001, 'John Doe');
employeeIds.put(1002, 'Jane Smith');
customerId instead of just id).