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 7 years, 2 months ago by  Yogesh.
    • This discussion was modified 7 years, 1 month ago by  Forcetalks.
    Nikita replied 7 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

AI in Salesforce

Transform businesses with the power of Artificial Intelligence leveraged through Salesforce Einstein

Blog in

Artificial Intelligence is powering next-generation customer experiences with smart predictions, intelligent recommendations, timely automation and much more. Gartner predicts that by 2020, a staggering 85% of…

Popular Salesforce Videos