• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Method Return Value relating to Call Tree  RSS feed

 
bruce tidehunter
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, i would like to know why the output of the following method is 16?
if i work through the code it should show 12? shouldn't it?



also the method was declared 'public int func1(int num)' but had to change it to 'static int func1(int num) because of the print statement.
could this have an impact on the output?
 
Raymond Tong
Ranch Hand
Posts: 255
2
IntelliJ IDE Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your method added "static" modifier didn't change what it is doing.
It is needed because its caller "main" is "static".

The answer wasn't 12 because "func1" is a recursive function.
Try to add a println statement to print "num" before the if statement inside your "func1" method could help you understand what is recursive.
 
bruce tidehunter
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raymond Tong wrote:your method added "static" modifier didn't change what it is doing.
It is needed because its caller "main" is "static".

The answer wasn't 12 because "func1" is a recursive function.
Try to add a println statement to print "num" before the if statement inside your "func1" method could help you understand what is recursive.


aah yes that makes sense! so everytime it goes through the method it will only stop if it meets the if condition of 'if(num <= 2) return 1;'
then the total from each iteration would be added to get 16, like so:

7
5
3
1
16
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!