Java method executes last print statement three times even though the method is only called once









up vote
0
down vote

favorite












I'm trying to figure out why this mystery method in Java prints out "43211234". I understand how the program reaches "43211" but I'm not sure how the last System.out.print(x % 10) after the "if" is ran 3 times and for each time, it brings the value of x back to the value it was previous to its current one until it reaches "1234" as the value of x. Could this have something to do with recursion since the method is being called in the "if" 3 times? I'm guessing it's something along those lines because the last executes exactly 3 times as well. I would greatly appreciate your help. Thanks.



class Main 
public static void main(String args)
mystery(1234);

public static void mystery(int x)
System.out.print(x % 10);
if((x / 10) != 0)
mystery(x / 10);

System.out.print(x % 10);











share|improve this question





















  • Remove line no. 10 System.out.print(x % 10); & it would be a fine program to reverse the digits of a given number.
    – Abhinav
    Nov 10 at 14:19














up vote
0
down vote

favorite












I'm trying to figure out why this mystery method in Java prints out "43211234". I understand how the program reaches "43211" but I'm not sure how the last System.out.print(x % 10) after the "if" is ran 3 times and for each time, it brings the value of x back to the value it was previous to its current one until it reaches "1234" as the value of x. Could this have something to do with recursion since the method is being called in the "if" 3 times? I'm guessing it's something along those lines because the last executes exactly 3 times as well. I would greatly appreciate your help. Thanks.



class Main 
public static void main(String args)
mystery(1234);

public static void mystery(int x)
System.out.print(x % 10);
if((x / 10) != 0)
mystery(x / 10);

System.out.print(x % 10);











share|improve this question





















  • Remove line no. 10 System.out.print(x % 10); & it would be a fine program to reverse the digits of a given number.
    – Abhinav
    Nov 10 at 14:19












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm trying to figure out why this mystery method in Java prints out "43211234". I understand how the program reaches "43211" but I'm not sure how the last System.out.print(x % 10) after the "if" is ran 3 times and for each time, it brings the value of x back to the value it was previous to its current one until it reaches "1234" as the value of x. Could this have something to do with recursion since the method is being called in the "if" 3 times? I'm guessing it's something along those lines because the last executes exactly 3 times as well. I would greatly appreciate your help. Thanks.



class Main 
public static void main(String args)
mystery(1234);

public static void mystery(int x)
System.out.print(x % 10);
if((x / 10) != 0)
mystery(x / 10);

System.out.print(x % 10);











share|improve this question













I'm trying to figure out why this mystery method in Java prints out "43211234". I understand how the program reaches "43211" but I'm not sure how the last System.out.print(x % 10) after the "if" is ran 3 times and for each time, it brings the value of x back to the value it was previous to its current one until it reaches "1234" as the value of x. Could this have something to do with recursion since the method is being called in the "if" 3 times? I'm guessing it's something along those lines because the last executes exactly 3 times as well. I would greatly appreciate your help. Thanks.



class Main 
public static void main(String args)
mystery(1234);

public static void mystery(int x)
System.out.print(x % 10);
if((x / 10) != 0)
mystery(x / 10);

System.out.print(x % 10);








java






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 14:10









Sahil Bagga

52




52











  • Remove line no. 10 System.out.print(x % 10); & it would be a fine program to reverse the digits of a given number.
    – Abhinav
    Nov 10 at 14:19
















  • Remove line no. 10 System.out.print(x % 10); & it would be a fine program to reverse the digits of a given number.
    – Abhinav
    Nov 10 at 14:19















Remove line no. 10 System.out.print(x % 10); & it would be a fine program to reverse the digits of a given number.
– Abhinav
Nov 10 at 14:19




Remove line no. 10 System.out.print(x % 10); & it would be a fine program to reverse the digits of a given number.
– Abhinav
Nov 10 at 14:19












4 Answers
4






active

oldest

votes

















up vote
1
down vote



accepted











I understand how the program reaches "43211"




so you know what recursion is.

Everytime mystery() is called, the 1st print is called and then it calls (recursively) itself, before the 2nd print.

When the recursion stops because (x / 10) != 0 is false, the 2nd print is called for the 1st time and then goes back to the previous unfinished recursive calls and executes the remaining print for each one.






share|improve this answer






















  • This was what I suspected was happening. Thank you!
    – Sahil Bagga
    Nov 10 at 14:35

















up vote
2
down vote













Not sure if my answer will be any more useful than the previous ones, but I'll try. So, basically, your program uses 2 types of recursion: backward recursion and forward recursion. My answer here is not to describe them to you, but to give you a starting point for more information on them.



Let's trace your program's execution:
mystery(1234) -> print(4) -> mystery(123); At this point, the System.out.print(x % 10); at the end of the method has not been called yet since your program has gone further in the recursion. It will be executed once the program returns from deep inside your recursion, and will be executed with whatever's left.



mystery(1234):
print(4);
mystery(123):
print(3);
mystery(12):
print(2);
mystery(1);
print(1);
print(1); //This is the first System.out.print(x % 10); from the end of the method, that is executed
print(2);
print(3);
print(4);





share|improve this answer



























    up vote
    1
    down vote













    Your mystery() method does the following:



    • print the final digit of the input number (num % 10 gives the last digit)

    • make a recursive call mystery(x / 10), assuming x / 10 is not zero

    • then on the way out from the recursion, print the final digit of the input again

    Putting this together, with an input of 1234, it means we would print those digits in reverse, then print them again in order.



    If this answer still leaves you with doubts, I suggest running your code, beginning with a two digit input like 12, until it is clear what is happening.






    share|improve this answer






















    • But for the last print statement, the value of x goes from 1 (I know it reaches the last line because 1 / 10 == 0) to 12 to 123 to 1234. How and why does it execute the last print statement 3 and build up the value of x again?
      – Sahil Bagga
      Nov 10 at 14:25










    • It prints 4, 3, 2, 1, and when 1 gets printed, the input is also 1, which is zero when divided by 10. So, no subsequent calls to mystery are made, and instead, everything backs out, starting with printing 1 again, then 2, etc.
      – Tim Biegeleisen
      Nov 10 at 14:27










    • @TimBiegeleisen I agree with that.
      – forpas
      Nov 10 at 14:46

















    up vote
    0
    down vote













    This is your recursion stack. This is perfectly fine.



     mystery(x / 10); input 1234 prints 4
    -> mystery(x / 10); input 123 prints 3
    -> mystery(x / 10); input 12 prints 2
    -> mystery(x / 10); input 1 prints 1


    Just make sure your remove the second sysout that you that you in your code. That is the reason it is printing the same numbers in again.






    share|improve this answer




















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239788%2fjava-method-executes-last-print-statement-three-times-even-though-the-method-is%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote



      accepted











      I understand how the program reaches "43211"




      so you know what recursion is.

      Everytime mystery() is called, the 1st print is called and then it calls (recursively) itself, before the 2nd print.

      When the recursion stops because (x / 10) != 0 is false, the 2nd print is called for the 1st time and then goes back to the previous unfinished recursive calls and executes the remaining print for each one.






      share|improve this answer






















      • This was what I suspected was happening. Thank you!
        – Sahil Bagga
        Nov 10 at 14:35














      up vote
      1
      down vote



      accepted











      I understand how the program reaches "43211"




      so you know what recursion is.

      Everytime mystery() is called, the 1st print is called and then it calls (recursively) itself, before the 2nd print.

      When the recursion stops because (x / 10) != 0 is false, the 2nd print is called for the 1st time and then goes back to the previous unfinished recursive calls and executes the remaining print for each one.






      share|improve this answer






















      • This was what I suspected was happening. Thank you!
        – Sahil Bagga
        Nov 10 at 14:35












      up vote
      1
      down vote



      accepted







      up vote
      1
      down vote



      accepted







      I understand how the program reaches "43211"




      so you know what recursion is.

      Everytime mystery() is called, the 1st print is called and then it calls (recursively) itself, before the 2nd print.

      When the recursion stops because (x / 10) != 0 is false, the 2nd print is called for the 1st time and then goes back to the previous unfinished recursive calls and executes the remaining print for each one.






      share|improve this answer















      I understand how the program reaches "43211"




      so you know what recursion is.

      Everytime mystery() is called, the 1st print is called and then it calls (recursively) itself, before the 2nd print.

      When the recursion stops because (x / 10) != 0 is false, the 2nd print is called for the 1st time and then goes back to the previous unfinished recursive calls and executes the remaining print for each one.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 10 at 14:33

























      answered Nov 10 at 14:21









      forpas

      5,8831217




      5,8831217











      • This was what I suspected was happening. Thank you!
        – Sahil Bagga
        Nov 10 at 14:35
















      • This was what I suspected was happening. Thank you!
        – Sahil Bagga
        Nov 10 at 14:35















      This was what I suspected was happening. Thank you!
      – Sahil Bagga
      Nov 10 at 14:35




      This was what I suspected was happening. Thank you!
      – Sahil Bagga
      Nov 10 at 14:35












      up vote
      2
      down vote













      Not sure if my answer will be any more useful than the previous ones, but I'll try. So, basically, your program uses 2 types of recursion: backward recursion and forward recursion. My answer here is not to describe them to you, but to give you a starting point for more information on them.



      Let's trace your program's execution:
      mystery(1234) -> print(4) -> mystery(123); At this point, the System.out.print(x % 10); at the end of the method has not been called yet since your program has gone further in the recursion. It will be executed once the program returns from deep inside your recursion, and will be executed with whatever's left.



      mystery(1234):
      print(4);
      mystery(123):
      print(3);
      mystery(12):
      print(2);
      mystery(1);
      print(1);
      print(1); //This is the first System.out.print(x % 10); from the end of the method, that is executed
      print(2);
      print(3);
      print(4);





      share|improve this answer
























        up vote
        2
        down vote













        Not sure if my answer will be any more useful than the previous ones, but I'll try. So, basically, your program uses 2 types of recursion: backward recursion and forward recursion. My answer here is not to describe them to you, but to give you a starting point for more information on them.



        Let's trace your program's execution:
        mystery(1234) -> print(4) -> mystery(123); At this point, the System.out.print(x % 10); at the end of the method has not been called yet since your program has gone further in the recursion. It will be executed once the program returns from deep inside your recursion, and will be executed with whatever's left.



        mystery(1234):
        print(4);
        mystery(123):
        print(3);
        mystery(12):
        print(2);
        mystery(1);
        print(1);
        print(1); //This is the first System.out.print(x % 10); from the end of the method, that is executed
        print(2);
        print(3);
        print(4);





        share|improve this answer






















          up vote
          2
          down vote










          up vote
          2
          down vote









          Not sure if my answer will be any more useful than the previous ones, but I'll try. So, basically, your program uses 2 types of recursion: backward recursion and forward recursion. My answer here is not to describe them to you, but to give you a starting point for more information on them.



          Let's trace your program's execution:
          mystery(1234) -> print(4) -> mystery(123); At this point, the System.out.print(x % 10); at the end of the method has not been called yet since your program has gone further in the recursion. It will be executed once the program returns from deep inside your recursion, and will be executed with whatever's left.



          mystery(1234):
          print(4);
          mystery(123):
          print(3);
          mystery(12):
          print(2);
          mystery(1);
          print(1);
          print(1); //This is the first System.out.print(x % 10); from the end of the method, that is executed
          print(2);
          print(3);
          print(4);





          share|improve this answer












          Not sure if my answer will be any more useful than the previous ones, but I'll try. So, basically, your program uses 2 types of recursion: backward recursion and forward recursion. My answer here is not to describe them to you, but to give you a starting point for more information on them.



          Let's trace your program's execution:
          mystery(1234) -> print(4) -> mystery(123); At this point, the System.out.print(x % 10); at the end of the method has not been called yet since your program has gone further in the recursion. It will be executed once the program returns from deep inside your recursion, and will be executed with whatever's left.



          mystery(1234):
          print(4);
          mystery(123):
          print(3);
          mystery(12):
          print(2);
          mystery(1);
          print(1);
          print(1); //This is the first System.out.print(x % 10); from the end of the method, that is executed
          print(2);
          print(3);
          print(4);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 14:33









          Rakirnd

          714




          714




















              up vote
              1
              down vote













              Your mystery() method does the following:



              • print the final digit of the input number (num % 10 gives the last digit)

              • make a recursive call mystery(x / 10), assuming x / 10 is not zero

              • then on the way out from the recursion, print the final digit of the input again

              Putting this together, with an input of 1234, it means we would print those digits in reverse, then print them again in order.



              If this answer still leaves you with doubts, I suggest running your code, beginning with a two digit input like 12, until it is clear what is happening.






              share|improve this answer






















              • But for the last print statement, the value of x goes from 1 (I know it reaches the last line because 1 / 10 == 0) to 12 to 123 to 1234. How and why does it execute the last print statement 3 and build up the value of x again?
                – Sahil Bagga
                Nov 10 at 14:25










              • It prints 4, 3, 2, 1, and when 1 gets printed, the input is also 1, which is zero when divided by 10. So, no subsequent calls to mystery are made, and instead, everything backs out, starting with printing 1 again, then 2, etc.
                – Tim Biegeleisen
                Nov 10 at 14:27










              • @TimBiegeleisen I agree with that.
                – forpas
                Nov 10 at 14:46














              up vote
              1
              down vote













              Your mystery() method does the following:



              • print the final digit of the input number (num % 10 gives the last digit)

              • make a recursive call mystery(x / 10), assuming x / 10 is not zero

              • then on the way out from the recursion, print the final digit of the input again

              Putting this together, with an input of 1234, it means we would print those digits in reverse, then print them again in order.



              If this answer still leaves you with doubts, I suggest running your code, beginning with a two digit input like 12, until it is clear what is happening.






              share|improve this answer






















              • But for the last print statement, the value of x goes from 1 (I know it reaches the last line because 1 / 10 == 0) to 12 to 123 to 1234. How and why does it execute the last print statement 3 and build up the value of x again?
                – Sahil Bagga
                Nov 10 at 14:25










              • It prints 4, 3, 2, 1, and when 1 gets printed, the input is also 1, which is zero when divided by 10. So, no subsequent calls to mystery are made, and instead, everything backs out, starting with printing 1 again, then 2, etc.
                – Tim Biegeleisen
                Nov 10 at 14:27










              • @TimBiegeleisen I agree with that.
                – forpas
                Nov 10 at 14:46












              up vote
              1
              down vote










              up vote
              1
              down vote









              Your mystery() method does the following:



              • print the final digit of the input number (num % 10 gives the last digit)

              • make a recursive call mystery(x / 10), assuming x / 10 is not zero

              • then on the way out from the recursion, print the final digit of the input again

              Putting this together, with an input of 1234, it means we would print those digits in reverse, then print them again in order.



              If this answer still leaves you with doubts, I suggest running your code, beginning with a two digit input like 12, until it is clear what is happening.






              share|improve this answer














              Your mystery() method does the following:



              • print the final digit of the input number (num % 10 gives the last digit)

              • make a recursive call mystery(x / 10), assuming x / 10 is not zero

              • then on the way out from the recursion, print the final digit of the input again

              Putting this together, with an input of 1234, it means we would print those digits in reverse, then print them again in order.



              If this answer still leaves you with doubts, I suggest running your code, beginning with a two digit input like 12, until it is clear what is happening.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 10 at 14:54

























              answered Nov 10 at 14:16









              Tim Biegeleisen

              212k1384132




              212k1384132











              • But for the last print statement, the value of x goes from 1 (I know it reaches the last line because 1 / 10 == 0) to 12 to 123 to 1234. How and why does it execute the last print statement 3 and build up the value of x again?
                – Sahil Bagga
                Nov 10 at 14:25










              • It prints 4, 3, 2, 1, and when 1 gets printed, the input is also 1, which is zero when divided by 10. So, no subsequent calls to mystery are made, and instead, everything backs out, starting with printing 1 again, then 2, etc.
                – Tim Biegeleisen
                Nov 10 at 14:27










              • @TimBiegeleisen I agree with that.
                – forpas
                Nov 10 at 14:46
















              • But for the last print statement, the value of x goes from 1 (I know it reaches the last line because 1 / 10 == 0) to 12 to 123 to 1234. How and why does it execute the last print statement 3 and build up the value of x again?
                – Sahil Bagga
                Nov 10 at 14:25










              • It prints 4, 3, 2, 1, and when 1 gets printed, the input is also 1, which is zero when divided by 10. So, no subsequent calls to mystery are made, and instead, everything backs out, starting with printing 1 again, then 2, etc.
                – Tim Biegeleisen
                Nov 10 at 14:27










              • @TimBiegeleisen I agree with that.
                – forpas
                Nov 10 at 14:46















              But for the last print statement, the value of x goes from 1 (I know it reaches the last line because 1 / 10 == 0) to 12 to 123 to 1234. How and why does it execute the last print statement 3 and build up the value of x again?
              – Sahil Bagga
              Nov 10 at 14:25




              But for the last print statement, the value of x goes from 1 (I know it reaches the last line because 1 / 10 == 0) to 12 to 123 to 1234. How and why does it execute the last print statement 3 and build up the value of x again?
              – Sahil Bagga
              Nov 10 at 14:25












              It prints 4, 3, 2, 1, and when 1 gets printed, the input is also 1, which is zero when divided by 10. So, no subsequent calls to mystery are made, and instead, everything backs out, starting with printing 1 again, then 2, etc.
              – Tim Biegeleisen
              Nov 10 at 14:27




              It prints 4, 3, 2, 1, and when 1 gets printed, the input is also 1, which is zero when divided by 10. So, no subsequent calls to mystery are made, and instead, everything backs out, starting with printing 1 again, then 2, etc.
              – Tim Biegeleisen
              Nov 10 at 14:27












              @TimBiegeleisen I agree with that.
              – forpas
              Nov 10 at 14:46




              @TimBiegeleisen I agree with that.
              – forpas
              Nov 10 at 14:46










              up vote
              0
              down vote













              This is your recursion stack. This is perfectly fine.



               mystery(x / 10); input 1234 prints 4
              -> mystery(x / 10); input 123 prints 3
              -> mystery(x / 10); input 12 prints 2
              -> mystery(x / 10); input 1 prints 1


              Just make sure your remove the second sysout that you that you in your code. That is the reason it is printing the same numbers in again.






              share|improve this answer
























                up vote
                0
                down vote













                This is your recursion stack. This is perfectly fine.



                 mystery(x / 10); input 1234 prints 4
                -> mystery(x / 10); input 123 prints 3
                -> mystery(x / 10); input 12 prints 2
                -> mystery(x / 10); input 1 prints 1


                Just make sure your remove the second sysout that you that you in your code. That is the reason it is printing the same numbers in again.






                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  This is your recursion stack. This is perfectly fine.



                   mystery(x / 10); input 1234 prints 4
                  -> mystery(x / 10); input 123 prints 3
                  -> mystery(x / 10); input 12 prints 2
                  -> mystery(x / 10); input 1 prints 1


                  Just make sure your remove the second sysout that you that you in your code. That is the reason it is printing the same numbers in again.






                  share|improve this answer












                  This is your recursion stack. This is perfectly fine.



                   mystery(x / 10); input 1234 prints 4
                  -> mystery(x / 10); input 123 prints 3
                  -> mystery(x / 10); input 12 prints 2
                  -> mystery(x / 10); input 1 prints 1


                  Just make sure your remove the second sysout that you that you in your code. That is the reason it is printing the same numbers in again.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 10 at 14:36









                  janardhan sharma

                  2537




                  2537



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53239788%2fjava-method-executes-last-print-statement-three-times-even-though-the-method-is%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Use pre created SQLite database for Android project in kotlin

                      Darth Vader #20

                      Ondo