• Lessons Home
Topics
Community
  1. Lessons
  2. Strings and Dates in Depth
  3. String Methods
  4. Inspecting Strings

      Inspecting Strings

      Inspecting Strings

      A String can tell you a lot about itself before you change anything. Apex gives you a set of inspection methods that answer simple questions: how long is it, is there anything in it, does it hold a certain piece of text.

      How Long Is It

      length() returns the number of characters:

      String code = 'LC-1234';
      System.debug(code.length()); // 7
      

      Is There Anything In It

      isEmpty() is true only when the string has zero characters. isBlank() is true when the value is null, empty, or only whitespace, which makes it the safer everyday check:

      System.debug(String.isEmpty('')); // true
      System.debug(String.isBlank('   ')); // true
      System.debug(String.isBlank(null)); // true
      

      Both are static methods on String, so they accept a null value without throwing.

      Does It Contain This

      String fileName = 'quarterly-report.pdf';
      System.debug(fileName.contains('report')); // true
      System.debug(fileName.startsWith('quarterly')); // true
      System.debug(fileName.endsWith('.pdf')); // true
      

      Where Is It

      indexOf() returns the position of the first match, counting from zero, or -1 when there is no match at all:

      System.debug(fileName.indexOf('.')); // 16
      System.debug(fileName.indexOf('zzz')); // -1
      

      Common Mistakes

      Calling an instance method such as length() on a null string throws a null pointer exception. Guard with String.isBlank(value) first, because that static method handles null safely.

      Why This Matters

      Validation is inspection. Nearly every check on user input starts by asking whether the text is present, long enough, and shaped the way you expect.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In