In: Computer Science
L4 (0.4 marks) Code a calling and called method that tries to demonstrate that a called method cannot remember how many times it has been called if it’s limited to only using its formal parameters and local variables. For technical reasons this cannot be demonstrated. You will discover why in your attempt. Now use a class-level variable to do the job properly.
public class CallingMethod {
private static void fun() {
// here declaring the local
variable
int count = 0;
//increasing the count
count++;
//printing the count
System.out.println(count + " time
Called..");
}
public static void main(String[] args) {
//calling the method
fun();
//calling the method
fun();
//calling the method
fun();
}
}
In the above we can see every time it seeing as only 1 because local variable will be created every time when a function is called.
To change this we need to use class level variable so that it will not be created everytime
public class CallingMethod {
static int count = 0;
private static void fun() {
// here declaring the local
variable
//increasing the count
count++;
//printing the count
System.out.println(count + " time
Called..");
}
public static void main(String[] args) {
//calling the method
fun();
//calling the method
fun();
//calling the method
fun();
}
}
Now we are able to find the correct count of callings
Note : If you like my answer please rate and help me it is very Imp for me