Activity Forums Salesforce® Discussions Why does NULL count as 4 characters in Salesforce Apex?

  • Why does NULL count as 4 characters in Salesforce Apex?

    Posted by Yogesh on August 28, 2019 at 12:41 pm

    If I execute the block of code in the Anonymous window, it returns 8 as the length of the string. Do null string count towards the string length in Apex?

    String s = 'Yosh';
    String e = null;
    String y = s + e;
    System.Debug(y.trim().length()); //Returns 8 characters. Should return 4

    • This discussion was modified 5 years, 2 months ago by  Yogesh.
    • This discussion was modified 5 years, 2 months ago by  Forcetalks.
    Nikita replied 5 years, 2 months ago 2 Members · 1 Reply
  • 1 Reply
  • Nikita

    Member
    August 28, 2019 at 12:55 pm

    Hi Yogesh,

    In Apex Code, null actually doesn't count as any bytes (per se). However, when you add null to a string, it's typed coerced into a string four-characters long-- "null". This behavior seems to be rather specific to Apex Code. In other languages that allow null bytes in a string, null should actually be one byte long.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos