function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AnshulVermaAnshulVerma 

Static variables not acting as static

Hi,

As I see static variables (in Java, C/C++, C# etc.) static variables are values that remain persistent throughout the application, it can be read/set in all sessions and would access the same variable(the value would persist across the whole application). But, when I was working with the static members of Apex classes I found that their values do not persist and

Please refer the following code

//Static class
Class ABC
{
public static Integer myVal;
static
{
myVal = 0;
System.debug('static constructor is called');
}
}

Visualforce page


All

value = {!val}





Apex Page Controller

Class SampleCon
{
public PageReference test()
{
System.debug('----------------val='+ ABC.myval);
CommonHelper.myval = CommonHelper.myval + 2;
System.debug('----------------val='+ ABC.myval);

CommonHelper.myval = CommonHelper.myval + 2;
System.debug('----------------val='+ ABC.myval);

CommonHelper.myval = CommonHelper.myval + 2;
System.debug('----------------val='+ ABC.myval);
return null;
}
}


Now, what happens is that each time test is initiated ABC.myval comes as zero. As far as my experience with other technologies (.NET, Java etc.), i think that statics should persist their values.

Please suggest if there is something that i'm missing.

Thanks in advance,
Anshul Verma
SuperfellSuperfell
Statics are scoped to the lifetime of the request, their values do not persist longer than a single request. I believe this is covered in the apex docs.
hemantgarghemantgarg

is there any way if we can persist a value throughout one login session ?