program flow in recursive method in java - java

class Test {
int i=0;
void method2() {
if(i==6) return;
System.out.print("before");
i++;
method2();
System.out.println("after"):
}
}
If I call method2() from another class then I want to know how the program will flow here or why the output that's executed.

In depth knowledge of recursion can be found here
https://en.m.wikipedia.org/wiki/Recursion_(computer_science)
As far as your program is concerned it will stop when i=6
Otherwise it will keep on printing before.
This is because in programming the flow of control is never skipped it follows the flow of control but it is not that it leaves the rest statement so whenever a new call to a function is generated the previous status of the functioning is being pushed in stack one by one and so the stack is kept on increasing and when finally the end condition is reached it pops all function calls one by one from the activation record and does the required processing is done and thus recursion works.
It takes help of a stack for doing operations.
The program flow always follows it's order wheather you call it from anywhere.
So the program flow remains same.
You will easily understand the working if you run it and add some more print statement with also the values of i.

Related

for loop execute only once

Code only executes once.
Disclaimer: Well aware this is an infinite loop, wrote it this way as part of troubleshooting the problem.
update: There was an exception in my error log that got fixed and the problem is still the same, code only executes once
I tried using the same for loop in the same code for a different task (printing a sentence) and it worked fine, problem must be with my JS code.
for(int i=0; i<i+1;i++) {
((JavascriptExecutor)driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("https://www.google.com");
}
Code is executing only once because of an exception being thrown, OR maybe one or more of the network calls you are making is taking too long that makes you believe that the code is executing only once.
To confirm that the value i + 1, which you are using in the for-loop isn't getting replaced by 1, I ran the following loop on my machine:
for (int i = 0; i < i + 1; i++) {
System.out.println(i);
}
...and it goes on to print numbers starting from 0.
I'm just going to clarify this point as an answer, as I expect the question will be removed.
The for loop isn't your problem. You are writing code which has an exception or is blocking the running thread. If you're using another thread to run this, a lack of an UncaughtExceptionHandler can allow it to skip being logged. Similarly the use of Callable<T> can result in exceptions being swallowed from personal experience (perhaps for the same reason?).
If you are blocking the thread running it, then that thread won't run anything else until the blocking method returns control to the context of where you called it.
Given you said you had cases where the loop "ran once" but still printed after, I'm going to go with it being an exception, and the way that you are running your test is flawed. This can be from an uncountable number of reasons, such as a folly System#exit/Runtime#halt call, threads, using a service to run the tests, or running them in some production environment like a game server or a phone (or... A browser?). For future cases, your questions should ideally be reproducible with nothing other than a main method and the code you provide. If you cannot make such an example, at minimum you should provide how you are testing it.
If you do all of that and still have the issue, I think it will either be obvious to you, or the people reading your question here will have a much easier time answering it for you.

Execution of a program

I have a question about execution of program. In C++ for example, the program is being executed line by line until it reaches the end (return 0; or just reaches the end of the scope of the main function). In a program with a text interface if I want to repeat the program until a user for instance hits the [Esc] key I put it in the loop that is being executed until that specific one situation occurs. Same happens in a GUI program (precisely: WinAPI), program is looping through the event loop until for example user hits 'X' and then the program is reaching the end of the main function, so the execution of the program stops. So far so good.
What is surprising me and is keeping me up at night is the fact that when I create a JFrame object, initialize it and make it happen just to show it, when the program execution reaches the end of the scope of the main function, the window still exists. I've also checked it in a debugger that it's not showing a line that is actually being executed. It clearly states that the thread execution has been finished. I am sure that the execution is not being frozen so something has to be happening under the hood, cause I still can resize, close the window and so on. So here's my question: where is actually the execution of a program 'moving to' when a window in Java is being displayed?
Same thing is happening in VBA. I've created a main function in a module, then in that one module i've forced one non-modal form to show and once the execution of the function has finished, the window did not disappear, but the variables declared in the function did, so the access to them vanished as well.
In both examples in C/C++ those situations would mean, that program was finished, but there's that window visible, so the application actually didn't stop, right?

java-JNA call a native loop from Java and stop it from an other function

I want to start a loop coded in C++ that is run untill I ask it (from Java) to stop.
IE:
(in c++)
void loop(){
while(!stop){
// do something
}
}
in Java:
MyLib.INSTANCE.loop();
then call something like :
MyLib.INSTANCE.stop = true;
Is it possible ?
While you can access a shared library's globals (NativeLibrary.getGlobalVariableAddress()), it's preferable to define a dedicated function which does what you want (i.e. MyLib.stop()).
You also need to take care that your code is multi-thread aware, so that the compiler doesn't think your loop's stop cannot be changed and thus optimizes it away. You also need to ensure that your loop doesn't monopolize the CPU; it needs to yield from time to time if you want your "stop" code to be able to run.

Waiting till previous function is completely executed

I have a series of IF statements in order of execution, my dilemma is if one of the IF statements is entered I would like the calling method to wait till the called function is finished. The thing is my called function is recursive so I have no idea when it's going to end. Here's the calling method's code.
if(log.isChecked())
{
runlog(sdPath.getAbsolutePath());
}
if(tmp.isChecked())
{
runtmp(sdPath.getAbsolutePath());
}
if(txt.isChecked())
{
runtxt(sdPath.getAbsolutePath());
}
if(bf.isChecked())
{
runbf(sdPath.getAbsolutePath());
}
if(ed.isChecked())
{
runed(sdPath.getAbsolutePath());
}
If log.isChecked() is entered, I would like the calling function(the code I've shown here, that function) to wait till it checks the next condition which is tmp.isChecked()
As I mentioned before ALL the called functions runlog, runtmp, runtxt, runbf, runed are recursive. How do I achieve what I want?
I think recursion can is best explained with the movie "Inception". You have 3 things you want to do.
Go to sleep.
Dream.
Wake up and eat a bowl of cereal.
Imagine you are dreaming and then have a dream within that dream. You now can't wake up and eat until you exit out of the deeper dream and finish the current dream.
That is basically what is happening in your example except instead of dreaming you ran the first if and you can't exit it until it reaches its return condition then you get to wake up and eat (enter the second if).
This should happen by default. The nested functions being recursive makes no difference here.
Each if block will only be executed after one the previous one has completed unless your nested functions are starting threads or something of that sort.

exiting functions in main

I am relatively new to Stackoverflow and Java, but I have a little experience in C. I liked the very clean way of C exiting the programs after a malfunction with the 'exit()' function.
I found a similar function System.exit() in Java, what differs from the C function and when should I use a 'System.exit()' best instead of a simple 'return' in Java like in a void main function?
System.exit() will terminate the jvm initilized for this program, where return; just returns the control from current method back to caller
Also See
when-should-we-call-system-exit-in-java ?
System.exit() will exit the program no matter who calls it or why. return in the main will exit the main() but not kill anything that called it. For simple programs, there is no difference. If you want to call your main from another function (that may be doing performance measurements or error handling) it matters a lot. Your third option is to throw an uncaught runtime exception. This will allow you to exit the program from deep within the call stack, allow any external code that is calling your main a programmatic way to intercept and handle the exit, and when exiting, give the user context of what went wrong and where (as opposed to an exit status like 2).
System.exit() may be handy when you're ready to terminate the program on condition of the user (i.e. a GUI application). return is used to return to the last point in the program's execution. The two are very different operations.

Categories

Resources