• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How Java return statement works?

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If I pass return 0 in the if statement then the factorial return accepts 0 and multiples by 0.

Can someone explain how it works? how is return from if statement is accepted by the factorial return? Is this the same behavior with String return type (in a different type of code)? I'm thinking of testing this with string.

 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think your base case should be 0 and the factorial of 0 is 1.
A return statement abruptly completes the whole of the method; it transfers control back to wherever it was called from. No code after the return statement is therefore executed.
 
joebloggs Bloggs
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well passing return 2 in if statement causes the value of last factorial return wrongly.

like instead of returning 24 it returns 48 for factorial(4).  Something is happening when the "if return is passing other than 1". That's what I'm trying to understand. I'm not sure how the final value is changed or what's happening.

I know how the factorial works btw.
 
Campbell Ritchie
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So when you get to 0! you leave behind the result 1; when you get to 1! yoiu multiply that by 1 and leave the result behind, when you get to 2! you multiply that by 2 and leave the result behind, when etc., etc., when you get to 13! you get an arithmetic overflow error. You could get to about 21! if you used longs.
If you get to 1! or 0! and return 2, you are returning the wrong result, so it's hardly surprising you are getting the other calculations wrong.
reply
    Bookmark Topic Watch Topic
  • New Topic