Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine whether a method has been called the first or the second time?

Tags:

java

I want to implement a method which has a different behavior when called for the first time, and then when it is called for the second time.

How to do that?

like image 482
Bionix1441 Avatar asked Dec 11 '22 12:12

Bionix1441


2 Answers

Instance methods in Java have access to the state of the class. Add a variable to indicate whether or not the methods has been called before, and use it to decide between two paths to take inside the method:

class FirstTimeCaller {
    private boolean isFirstTime = true;
    void methodWithState() {
        if (isFirstTime) {
            ... // Do first-time thing
            isFirstTime = false;
        } else {
            ... // Do the other thing
        }
    }
}

This works for instance methods of the same object: first-time call will be executed the first time you call methodWithState on each new object of FirstTimeCaller class.

If you wish to implement the same behavior for a static method, or you'd like to have the first invocation on any instance to do a different thing, and all subsequent calls to do something else, make isFirstTime field static.

like image 89
Sergey Kalinichenko Avatar answered Jun 04 '23 09:06

Sergey Kalinichenko


You can simply create a variable

int counter = 0; // This means the method has not been called yet

And when the method is called then just do this code in it:

counter++; // Increment by 1 for each new call

And you have a number of method calls stored in a variable "counter" so you can choose what to do with it.

like image 32
Zdeněk Bednařík Avatar answered Jun 04 '23 10:06

Zdeněk Bednařík