Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 36 ยท Apex Basics

Strings, Numbers and Dates in Apex

Work with Apex Strings, Decimals and the Math class, and build, compare and format Date and Datetime values, with runnable Java stand-ins for the logic.

Almost every Apex class manipulates text, numbers or dates: building a message for a customer, rounding an invoice, working out when a contract renews. Apex has rich built-in classes for all three. This lesson tours the ones you will use every day.

Strings

A String is immutable text in single quotes. Escape a quote or special character with a backslash:

Java
String s = 'It\'s a "great" day';
String multi = 'Line one\nLine two\tTabbed';

Common methods (all are called on the string or on the String class):

Java
String name = '  Ada Lovelace  ';
name.trim();                       // 'Ada Lovelace'
name.toUpperCase();                // '  ADA LOVELACE  '
name.contains('Love');             // true
name.startsWith('  Ada');          // true
name.substring(2, 5);              // 'Ada'
name.replace('Ada', 'Grace');      // '  Grace Lovelace  '
name.split(' ');                   // list of pieces (empty strings included)
name.length();                     // 16
String.join(new List<String>{'a','b','c'}, '-');   // 'a-b-c'
String.isBlank(name);              // false; also true for null and ''
String.isNotBlank(name);           // true

Equality: == on strings is case-insensitive in Apex, which surprises Java developers. Use equals() for an exact, case-sensitive comparison:

Java
'Ada' == 'ADA';            // true
'Ada'.equals('ADA');       // false
'Ada'.equalsIgnoreCase('ADA');  // true

Building strings with values: concatenate with +, or use String.format with numbered placeholders:

Java
String msg = String.format('Hello {0}, you have {1} new cases', new List<Object>{ 'Ada', 3 });

For large concatenation in loops, build a List<String> and String.join it at the end; it is cheaper than repeated +.

A Java stand-in for string tasks

Java's String is close enough to show the ideas. Notice the one real difference: we must call equalsIgnoreCase to copy Apex's ==.

Java Stand-in (Java): text clean-up

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.

Numbers and the Math class

Integer, Long, Double and Decimal support the usual operators + - * /. Apex has no % operator: use Math.mod(a, b) for remainders. Integer division truncates: 7 / 2 is 3. Divide by a Decimal or Double to keep fractions. Dividing by zero throws System.MathException.

Java
Decimal price = 19.999;
price.setScale(2);                          // 20.00 (default mode is HALF_EVEN)
price.setScale(2, RoundingMode.HALF_UP);    // 20.00
Math.abs(-5);        // 5
Math.max(3, 9);      // 9
Math.pow(2, 10);     // 1024.0
Math.mod(17, 5);     // 2
Math.round(2.5);     // 3
Math.floor(2.7);     // 2
Math.ceil(2.1);      // 3
Math.sqrt(16);       // 4.0

Always pass a rounding mode to setScale for money so the result is explicit. For percentages, a pattern like (part / total * 100).setScale(1) works as long as total is not zero or null, so test that first.

Dates and Datetimes

Apex has three date and time types: Date (a day), Time (a time of day) and Datetime (both, stored in UTC, displayed in the user's time zone).

Java
Date today = Date.today();
Date launch = Date.newInstance(2026, 9, 1);
Integer days = today.daysBetween(launch);
Date nextWeek = today.addDays(7);
Date nextMonth = today.addMonths(1);
Boolean sameDay = today.isSameDay(Date.today());
Integer year = today.year();
Datetime now = Datetime.now();
String formatted = now.format('yyyy-MM-dd HH:mm');
Date parsed = Date.valueOf('2026-05-17');     // from yyyy-MM-dd text

Date.today() uses the running user's time zone; Datetime.now() is the exact moment. Use Datetime when the time matters (a meeting) and Date when only the day matters (a birthday).

Adding months is safer than adding 30 days, because Apex clamps to the end of a short month: adding one month to January 31 gives the last day of February.

A stand-in for date arithmetic

Java's LocalDate behaves the same way as Apex's Date, which lets us check the month-end rule.

Java Stand-in (Java): date 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.

Putting it together

A typical Apex task: "the invoice is due 30 days after it is issued, and late fees are 1.5% per full month overdue". You would store dates as Date, money as Decimal, compute daysBetween, divide by 30 using integer division to get full months, and round the fee with an explicit RoundingMode.

Common mistakes

  • Comparing strings with == when case matters.
  • Integer division where you expected a fraction (1 / 2 is 0).
  • Forgetting that Datetime is stored in UTC, so a "midnight" value may show a different day for a user in another time zone.
  • Calling substring with out-of-range numbers, which throws System.StringException.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 'Ada' == 'ADA' return in Apex?

    String == is case-insensitive in Apex. Use equals() for a case-sensitive comparison.
  2. 2. What is 7 / 2 when both are Integers?

    Integer division truncates the fraction, giving 3.
  3. 3. Which method adds one month to a Date?

    Date.addMonths(1) handles different month lengths for you.
  4. 4. Which check handles null, empty and whitespace-only strings?

    String.isBlank returns true for null, empty and whitespace-only values.

Summary

  • Strings use single quotes; == ignores case, equals does not.
  • Use String.isBlank, join, split, substring, replace and format for everyday text work.
  • Integer division truncates; use Decimal with an explicit rounding mode for money.
  • Date, Time and Datetime have methods for adding, comparing and formatting; Datetime is stored in UTC.

Next: Collections: Lists, Sets and Maps