Can someone please help me to know why I am getting below value in debug log:

The values for below debug log are: 'A','B','C' null

public class TestingClass{

public void myfunc1(){
List<String> stringList1 =  new List<String>{'A','C','B'};
List<String>  stringList2 = sortStringList(stringList1);

public List<String> sortStringList(List<String> stringListVal){
stringListVal = null;
return stringListVal;
  • 2
    This is fully covered in the documentation. See this blog entry for more.
    – Phil W
    Aug 9, 2020 at 11:07

1 Answer 1


In addition to the blog post mentioned in @Phil W's comment, understanding the following line from your code snippet could be helpful.

stringListVal = null;

null is neither an object nor a type, but just a special value that can be assigned to any reference type. When you assign null to any variable, you are telling the underlying engine to remove the reference to the existing object and point it to null reference (which is also synonymous to the variable pointing to nothing). In apex, any variable declared but not initialized automatically points to null reference [like this code: List<String> ls;].

In your code, stringList1 from myfunc1 & stringListVal from sortStringList, both point to the same memory location or object until stringListVal = null; is executed. As soon as this code is executed, the existing object reference for stringListVal is removed and a null reference is assigned. But the memory location (where the list actually resides) itself is not cleared, implying that stringList1 is still pointing to the same location. In the next line return stringListVal;, you are returning an object with null reference which is assigned to List<String> stringList2 [Note that this is same as executing List<String> stringList2; or List<String> stringList2 = null;]

Now, if you replaced stringListVal = null; with stringListVal.clear();, you'll see that both the debug statements are returning an empty list i.e., (). This is because the clear method is actually deleting the list entries from the memory location.

  • Thanks Arut, after phil and your comments, it has been so much easier to understand.
    – Sukruti
    Aug 9, 2020 at 15:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .