• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return values in methods

 
Christopher Laurenzano
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just wondering --

I'm reading about return values in methods, but I'm confused about something. Take this code as an example ( I've included it all, even if it isn't all necessary -- it's from Head First Java):



My question is: where is the value returned to, if that's the right way to phrase it?
 
Ranveer K Kumar
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
GoodDog two = new GoodDog();
two.setSize(8)
System.out.println ("Dog one: " + one.getSize ());
System.out.println ("Dog two "+ two.getSize ());
one.bark;
two.bark;


here creating object name two of GoodDog

and setting the size of the GoodDog
now
System.out.println ("Dog two "+ two.getSize ());
will call two.getSize(); (will return value of size).
which is set erlier bye two.getSize();

this is simple bean (POJO) getter and setter.
 
Gavi jadz Grandea
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Java requires that a method declare the data type of the value that it returns. If a method does not return a value, it must be declared to return void.

In your case,
setSize() method is declared with returntype void, so no return value required.

getSize() method is declared with returntype int, that's why it should return an object of an integer.

where is the value returned to?

value is returned to an intance that called it...


regards,
-Jadz
 
Christopher Laurenzano
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, just to be clear, return means 'compute the value of this variable (or whatever), using this method and tell me what is'. Did I get that right?
 
Campbell Ritchie
Sheriff
Posts: 48381
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but the method doesn't know whether you ever do anything with the result. For example in this post from a few minutes ago, I have actually used the boolean return value from the addAll method, which the original code ignored.
 
Campbell Ritchie
Sheriff
Posts: 48381
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Notice also that the "addAll" method does something, then returns "true" or "false" to show whether that "something" worked.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic