The static Keyword
You can have a local variable retain its value through multiple invocations of a method by placing the keyword static in front of the variable’s declaration. For example, the following declares the integer hitCount to be a static variable:
static int hitCount = 0;
Unlike other local variables, which are basic data types, a static variable does have an initial value of 0, so the initialization shown previously is redundant. Furthermore, they are initialized only once when program execution begins and retain their values through successive method calls.
The following code sequence might appear inside a showPage method that wanted to keep track of the number of times it was invoked (or, in this case, perhaps the number of pages ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access