• 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

Basic understanding of 'return'

 
Ranch Hand
Posts: 53
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys,

I still do not fully understand what the return command does. I would like someone to explain to me what the function of it is. I provide an example from a book I am currently reading about java:



So could anyone explain to me what a return means, and how it is used in this example? The book's explanation does not really do it for me
 
Saloon Keeper
Posts: 27763
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the JavaRanch, Sander!

In traditional programming, there were 2 types of code modules: subroutines and functions. Functions get their name because they operate in an analogous way to mathematical functions - you feed values in, you get a value out.

In Java, since it's Object-oriented, we refer instead to methods, and a method, depending on how you design it, may act like a subroutine or like a function. Every method definition includes a return type (except for constructors, where the whole mechanism is assumed). A "subroutine" returns void, which is a way of saying it returns no value. There's no such thing as a "void" object, so you simply don't return a value. If you wish to exit the method before you've reached the final line of code in that method, you just use a "return;" statement.

For function-type methods, all return statements must return a value and that value must be of the type indicated in the method declaration. In this case, the method must have at least one return statement, since it must always return a value (unless it terminates abnormally, via an Exception).

Note that just because a method returns a value, you don't have to do anything with that returned value. Your main() method in your example doesn't use the returned values of the objects being enumerated.

Here's an example that does use the returned values:
 
Sheriff
Posts: 5555
326
IntelliJ IDE Python Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Sander, welcome to the Ranch!

Firstly, please can you say what book you have gotten that code from? Correct attribution is a matter of copyright.

Now, to your question: Methods have inputs and outputs. Take this example from the code you provide.


The method signature says that the method called frighten takes a single input parameter of type int, and returns as output something of type boolean. The return statement defines what that output is, as well as defining the exit point of the method.
 
Ronald Hoovenaar
Ranch Hand
Posts: 53
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok. Thank you guys for your replies.
The book I got it from is: Head First Java
by Kathy Sierra & Bert Bates.

So, in my example the return values do not have any effect and do not mean anything? Could I make it a void and would it still work?
 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome again. Yes, you can remove the return statements and change those methods to void. Then you lose the information returned. As it is you can writeYou do not have to use any returned values. You can simply write m.frighten(); and the returned value disappears into cyber‑Limbo never to be seen again. But changing the methods to void loses you that flexibility.

Another more serious example: The Set#add() method does not have void type. You often don't need that return value but it can be useful:-
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was reading through the 2nd edition of HFJ just now and I thought the example given of the vending machine was pretty good. I'm not sure if you have the 1st edition though and how different that is from the 2nd edition because I couldn't find anything that mentioned Monsters or any of the other creatures you have. I thought the explanation that I read about return in HFJ was pretty straightforward though so let me use the same vending machine analogy.

Pressing buttons on a vending machine to choose an item you want to buy is like passing in a parameter to a method of a vendingMachine object (let's ignore the fact that you have to put in money, too, for now).

You're basically saying, "Hey vending machine, give me one of those items that's marked J2".

In code, that might look something like this:

See how it can translate into a conversation or a description of what is happening in your program? The vendingMachine is the object, the giveMe() method is a command that the object responds to, or you could also look at is as a behavior or capability the object has, and "J2" is a parameter that is a detail that's relevant to your specific request for the object to do something. That detail can be different each time you make a request and the object will adjust accordingly. Like if you say "D1" instead, you'll get back a different item, the one that's marked "D1".

When the vendingMachine gives you back something based on your request and the detail that you gave it, that's ultimately because of a return statement. The vendingMachine made some kind of determination that when you asked it to give you a "J2" item, it needed to spit out a candy bar, for example. It would use the same logic to make a determination that it needed to spit out some chips if you had asked it to give you a "D1" item instead. In code, that determination might have looked something like this:

For now, don't pay attention to the fact that this example shows a very naive implementation, I'm just trying to make it as simple as possible so you can relate to what's happening. The point is that there is code that somehow figures out which particular item needs to be spit out (returned) based on the specific information you passed in when you called the giveMe method. If you're wondering what those ellipses are (the ... things), don't worry about that stuff for now. That just means that the giveMe() method probably does a few other things to make sure it's doing the right thing. That's not relevant to this discussion so ignore it for now.

Now, back in the outside world, the bought variable will receive the value that the giveMe method returned, specifically, the "candy bar" Item. In that way, the bought variable essentially becomes the Item that was returned by the vendingMachine when you asked it to give you the item marked "J2". You can then go off and enjoy the Item (a candy bar) that you just bought.

Are you with me so far?

Now, you could have also just written this:

This time, you didn't assign the returned value to anything. That means that the Item that the vendingMachine returned wasn't received by anything. It's just sitting there. It's like you pressed the button and just walked away without taking your candy bar with you. I'll do that sometimes, especially when I see that the electronics department has some new items on display. I'm old and absentminded, what can I say.

What happens to the Item that the vendingMachine returned, the one that you just left there?

Well, there's a guy walking around the store and he's waiting to pick up garbage that people leave laying around, things that they don't use anymore. This guy is called, very appropriately, the "Garbage Collector". When you walk away from an Item like that, sooner or later, and you don't really know or have to care when because he tries to stay as inconspicuous as possible, the Garbage Collector guy will come around and notice that there's an Item (oooh, a candy bar!) that's just sitting there unclaimed by anybody. He'll look around the store to make sure that nobody has a sign that says "That's my candy bar!" and then picks it up and throws it out. Yeah, I know, I hate putting a good candy bar to waste but that's how the Garbage Collector guy keeps the store free from clutter.

So you see, you can treat your program like it's just one big story about what's happening between the people using the program and what's happening inside the computer.

Context Matters when Choosing Names

Notice how I picked names that make sense in the context that they're used?

On the outside of the vendingMachine, I used the variable name bought, as in "the Item that the customer bought" -- yes, I know, we didn't literally buy anything because no money changed hands but you get what I mean, right?

Inside the vendingMachine, I used the name selected, as in "the item that the customer selected". That's because from the vendingMachine's point of view, that's what the item represents. I use a name that properly represents the thing that it refers to in the context that the name is being used.

It's like if you were with your father and I was introducing you to some other people, I would say something like, "This is Sander, and he is the son of Mr Koorevaar." Now, if you were with your uncle, I would introduce you differently, right? I might say something like "This is Sander, he is the nephew of Mr Koorevaar". I wouldn't introduce you as your uncle's son, right? The label "son" would not be the right term to use in that situation. This what is meant by "semantics" and "context". Semantics refers to what the word means and Context refers to the situation in which that particular meaning applies. You always want a name/label to convey a meaning that fits the situation. In the example, the same person/thing (You, Sander) will be given different labels/names (son/nephew) depending on the context/situation (relation to father/uncle).

It's important to choose semantically correct names that fit the context in which they are used. This makes your program make sense when someone reads it. In other words, it clarifies the intent of your program. It's important to take care and spell things out and be clear about what you're saying, otherwise, other people reading your program will be confused as to what's going on. But maybe I've said too much already with regard to your original question so I'll save that stuff for another post and another example.

Does this help?

(EDIT: looking back at the HFJ 2nd Ed again, it appears I misinterpreted the picture that I saw earlier this morning. In the section called You can get things back from a method, there's a picture of a lady standing in front of what is appears now to be an ATM, not a vending machine. My mistake. Ah well, what's done is done, and I think the vending machine works just as well anyway)
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I forgot to explain the void return.

Staying with the vending machine example, void just means that you don't really care or expect the object to give you back anything when you ask it to do something by calling a method (a capability) it has. The method you're calling is purely a command. This is why this kind of programming is sometimes referred to as imperative programming, as opposed to functional programming. In grammar, a sentence that gives some kind of command like "Run!" or "Give me a candy bar" is an imperative sentence. Yeah, I have an imperative wife. She tells me to do things all the time. She's also very exacting, but again, that's another story.

Coming back to our void return method example, it's like telling the vending machine to cancel your transaction and give you back your money. In code, that might look like this:

and in the vendingMachine:

Notice how there's no return statement in that method? That's because of the void return type that is declared in the method signature. You could have also written this with a return statement but that would be redundant because it's understood that once all the statements inside a method are executed, it will give back, i.e. return, control of the program flow to whoever called the method.

You can't have anything after the return keyword though. You're basically saying "Go back, but give back nothing, not even null."

That last part is an important distinction to make. The null value is still just that, a value. In contrast, void is just that, void. It's nothing. Like what you find in space, a void, a vacuum, emptiness, nothing. It's like what you will find in a certain political aspirant's head and in the heads of ... well, I'll leave that kind of talk for the Rattlesnake Pit... just one of my more recent pet peeves

So anyway, the final thing I can think of regarding void methods is that you can't use them on the right side of an assignment statement. That is, you can't try to make something receive the nothing that a void method returns because there is nothing to receive. You can't use it as part of an expression either. It doesn't make sense.

In normal conversation, you might think that saying something like, "I'd like a candy bar and ... oh, well, just forget about it" makes perfect sense but it doesn't make sense in Java-speak. You can't write this:

Java doesn't like it when you try to play mind games like that. Unlike other people, ... oops, there I go again. I need to go to the Rattlesnake Pit later and vent

You would have to stop and change your mind in an entirely different part of the conversation. Let's say, we actually did have some way to feed the vending Machine some money. That might look like this:

This says that when you deposited $2.00 into the vending machine, it took your money and told you whether or not it accepted the money and recorded the amount correctly. Later on, instead of making your selection by calling the giveMe() method, you decide that you want to stick to your diet after all and resist the temptation to sneak in a candy bar. So, you tell the machine that you're going to be strong today and just walk away. Good for you!

Again, in code that might look like this:

Java will not be fooled by something like this either:

Java will tell you that you're not making sense when you say you want nothing to be assigned to the bought variable. Java will say that you need to assign something to the Item you bought, even if it's null, which is something that just happens to represent, in essence, nothing. I know, it's kind of messed up but to Java, that's what makes sense. I guess it's good that Java can't vote, otherwise it might get confused too... Gah! I really need to stop doing that.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I like real world analogies. I think of methods as like people with specific skills.

So I could go to Bob and say "Cleveland, Celsius", and he'd tell me the current temp. in Cleveland in Celsius. Or I could say "Juno, Kelvin" and I'd get the temp in Juno in Kelvin. When he tells me, I write it down so I don't forget.

Now, there's also Peter. He paints houses. I can say to him "1748 James avenue, blue". He'll go to that address and paint that house blue. He doesn't need to tell me when he's done, because I don't care. I just send him off and he does his thing.

Susan I call on the phone and tell her "I need to know how old <this person> is". She will research, find their age, and tell me...but sometimes, I hang up the phone before she can answer. She doesn't KNOW I hung up, so she speaks the age into her phone anyway, but I don't get it, so that data is lost.


this first example is a method that returns something (the temp) to the calling method (me), and I keep it.

the second example is a method that is void - it does something, but the calling method doesn't really know much about the results.

The third is a method that returns something, but the calling method doesn't save it (to a variable of some kind, usually). So the data is returned, but basically lost.
 
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

Junilu Lacar wrote:. . . (let's ignore the fact that you have to put in money, too, for now).

You're basically saying, "Hey vending machine, give me one of those items that's marked J2". . . .
In code, that might look something like this:
. . .

Our local vending machine would charge me 90p for a 52 (it doesn't have letters), so I could invoke its giveMe method like this:-If I tried this sort of thingthe machine would insist on charging me an extra 10p before giving me the food. So adding money is quite simple .
 
permaculture is a more symbiotic relationship with nature so I can be even lazier. Read tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic