• Post Reply Bookmark Topic Watch Topic
  • New Topic

returning a value from a method  RSS feed

 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys

have this code:



and this class:



im still having a problem with returning a value from a method...

return totalCakes; - this is returning it to the code that called the method,but i cant print out the value in the factory class.
i have no access to totalCakes from the Factory class as the access modifier isnt static...so what is it returning,to where? and how can i use it.

thanks for reading



 
jon ninpoja
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i know i can just print that total out in the method,im just trying to see how return values in methods work etc
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
are you saving the value returned by the method?

edit - that's meant as a hint, not an actual question...
 
Jerry Ye
Greenhorn
Posts: 25
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It returns as the value of your line 4. You just need something to store it and to print it. If you don't store it, it just might appear somewhere in the memory and disappear immediately.
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jerry Ye wrote:If you don't store it, it just might appear somewhere in the memory and disappear immediately.

You're on the right track. Return values are placed on the stack. This applies to both primitive values like int and reference values (pointers to objects). If you do not assign the return value to something in the calling code, the value on the stack simply gets overwritten by the next operation that involves the stack. If the return value was a reference to an object, the object that was referenced will become eligible for garbage collection. So, there is no "might" about it: the value definitely will be in memory. If you don't assign the value to something or use it in an expression, then the value will eventually be discarded.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!