Can anyone explain what's happening here 🤔 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can anyone explain what's happening here 🤔

https://code.sololearn.com/c29B2waM8V64/?ref=app

20th Jan 2021, 6:56 PM
D_Stark
D_Stark - avatar
6 Answers
+ 3
D_Stark try to read the output and try to understand the stack. https://code.sololearn.com/ca4A24A7a15A/?ref=app
20th Jan 2021, 8:13 PM
Rohit
+ 3
| args = ["a", "b", "c"] | <---------- TOP |---------------------------- | | args = ["-"] | So "abc" is printed when our if statement condition is false. So now the args with value ["a", "b", "c"] is popped. Then again we print the other value from the stack that is args with value ["-"]. Now our TOP is args with value ["-"] | | |---------------------------- | | args = ["-"] | <---------- TOP Then the next Top is popped and gets printed and we have "abc-" as the final output. [Don't mind my English writing skills] :)
20th Jan 2021, 7:42 PM
Rohit
+ 2
The first question we need to ask here is "what is args?" since we are comparing it's length with that of the array a. So basically args contains command-line arguments(array of string objects) which means when we run our program like so - "java Program one two" then our args will contain ["one", "two"] But in our case we are not passing anything while running so it's default value is ["-"]. Coming to your code, the first thing that would execute is the if statement inside the main function. now since the length of the args and array is not the same, our test() gets executed inside of which again the main function is called with a value of type array "a" passed to args which means args contains value ["a", "b", "c"] currently. So the program continues and if statement is executed but this time the length is same and hence the if condition is false and is skipped and instead the for each loop is being executed which prints "abc" since args with value ["a", "b", "c"] is in the top of our stack. contd.
20th Jan 2021, 7:39 PM
Rohit
+ 2
RKK thanks bro, is there away to visual this like somthing were I can see the stack? Thanks
20th Jan 2021, 7:56 PM
D_Stark
D_Stark - avatar
+ 1
Ah I see so arguments are not passed to the main method were inside of it's passed to a diffrent frame, does that frame contain the same data as the main frame were in?
20th Jan 2021, 8:06 PM
D_Stark
D_Stark - avatar
+ 1
The fist time condition doesn't match so "test" method is called. It invokes "main" with the same reference, so this time... the condition pass an then the array is printed also remember that solo learn puts an extra arg that is you will see "-" appended after continue with the stack of 1st recursion https://code.sololearn.com/ci8W7CLlPZ4h/?ref=app
21st Jan 2021, 1:23 AM
David Ordás
David Ordás - avatar