This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes return values in methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "return values in methods" Watch "return values in methods" New topic
Author

return values in methods

Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
It's been a while since I've been here, but I'm reading HFJ and I have a question about return values in methods. This example is the code from chap 5, and it's the simple guessing game "simple dot com" (for those of you who have read the book). It ranodmly chooses three consecutive cells from a 7 cell row, and asks the user to guess what the location of the cells are, noting whether it's a hit or a miss, and a kill when the user guesses all three cells, and displays how many guesses it took to kill the DotCom.

Here's the code for both classes: first the SimpleDotCom class, then the game class which actually asks for the user guesses.


and the game class:


my question has to do with the return value of the checkyourself () method. The method takes the user's guess and sees if there's a hit, but where is the result actually used? (Not sure if I'm asking that correctly), or maybe I should ask where is the resulting String value used? The method prints the result, so why return it back to the method? I also noticed that if I change the name of the String 'result' in the SimpleDotComGame class to 'answer', the program still runs. So I'm guessing that the String 'result' in the Game class is a separate one from the String result checkyourself() method, even though they both have the same name. Or what am I missing?


Sorry guys, but as it's been a while, I forgot that I asked a similar question in Mid September. My apologies -- although I'm still a bit unclear about this

Or, maybe I could ask this, if the method prints out the result, why not just make the method 'void'?
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Christopher:

Take a look at Lines 17 and 19 of your game class. Ask yourself what's going on. That should answer your question.

John.
Christopher Laurenzano
Ranch Hand

Joined: Jul 25, 2009
Posts: 85
Okay, I think I get it, but I'll sate it here just to be sure:

Line 17 initializes a String variable named 'result' and assigns it the value based on the checkyourself() method, which is also a String. What confuses me is the name of the String here, which is 'result' in both this class and the checkyourself() method. Does it refer to the same variable, or two different variables with the same name, and if so, how is that possible? if the string 'result' in the checkyourself () method is the same as the one in the game class' while loop, why does it need to be compared? They will always be the same.

Line 19 then compares the value of 'result' in the game class's while loop and asks if it's 'kill,' etc.

But what I still don't get is that if I change the name from 'result' in the while loop to, say, 'answer', the program still compiles and runs. So could you explain how that works, because I'm still not clear -- and I apologize if I'm asking something obvious, but I'm just starting out learning this. Feel free to correct me -- I welcome all help from the more experienced and professionals, and as I said before, I'm not sure exactly how to ask my question -- or what I need even to ask.

I'm not a professional programmer, by the way -- I'm learning this for the fun and intellectual excercise.



Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1659
    
  11

Let me start by saying I LOVE HFJ and the Dot Com game was my favorite app I've played with so far.

Christopher Laurenzano wrote:Okay, I think I get it, but I'll sate it here just to be sure:

Line 17 initializes a String variable named 'result' and assigns it the value based on the checkyourself() method, which is also a String. What confuses me is the name of the String here, which is 'result' in both this class and the checkyourself() method. Does it refer to the same variable, or two different variables with the same name, and if so, how is that possible? if the string 'result' in the checkyourself () method is the same as the one in the game class' while loop, why does it need to be compared? They will always be the same.


Let's try saying it this way... Line 17 sets the String with a remote controller named result to the RETURN VALUE of the checkYourself() method with the parameter of guess. That "guess" gets passed to the checkYourself() method, processed accordingly, and the "result" is passed back. Even though the Strings have the same name to us, they have different locations on the heap. Strings are objects. I suppose good practices would be to name each thing in each method something different (like answer, result, or whatever) to limit confusion.

Line 19 then compares the value of 'result' in the game class's while loop and asks if it's 'kill,' etc.

But what I still don't get is that if I change the name from 'result' in the while loop to, say, 'answer', the program still compiles and runs. So could you explain how that works, because I'm still not clear -- and I apologize if I'm asking something obvious, but I'm just starting out learning this. Feel free to correct me -- I welcome all help from the more experienced and professionals, and as I said before, I'm not sure exactly how to ask my question -- or what I need even to ask.


This works because while you're inside that class, That String named "result" could be named "fooBar" and would work. You're declaring a separate object with a separate remote controller... think back to like chapter 2 or 3 when they talk about the remotes and the objects. THAT result String (while confusing) is originally set to "miss", then "hit" or "kill" based on the comparison of the guess (which is just an Integer version of the stringGuess that got passed as the String guess). They are two separate objects. Remember, if it's not a primitive, it's an object of some sort. If you're dealing with objects, you're not dealing with their names, just remote controllers that need to talk to the object on the heap to get their information.

Let me know where you get with that....
-Janeice

P.S. I can only know this so well because the ranchers beat this into my brain several weeks back.... so kudos to them! I got it!


When you do things right, people won't be sure you've done anything at all.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

Christopher Laurenzano wrote:... What confuses me is the name of the String here, which is 'result' in both this class and the checkyourself() method. Does it refer to the same variable, or two different variables with the same name, and if so, how is that possible? if the string 'result' in the checkyourself () method is the same as the one in the game class' while loop, why does it need to be compared? They will always be the same.


A String is an Object, and has an Address somewhere in space. A Variable is simply a reference to the String - it holds the Address, but not the String itself. Variables are defined by scope - they only exist inside the block of code they are defined in - that is the code between the nearest curly braces { }. So, inside the SimpleDotCom class there is a method called checkYourself. As a method it has curly braces - { }, so any variable defined in the method only exists inside those braces, and does not exist outside the method. One such Variable is the one named result. Similarly, inside the SimpleDotComGame there is a main method which also has a variable declared which has a name of result. Because the two variables are defined inside blocks that never overlap there is no overlap or crosstalk between them, they are completely different things that happen to have the same name.

In this case, both variables end up referring to the same Object, because the checkYourself result variable initially stores the String's address, then the checkYourself method returns a copy of the String's address. In the main method a String variable named results takes that copy of the String's address to do more work on. So the value of those two variables happens to be related only because of how they are used, but the variables themselves are not related at all.

Steve
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1659
    
  11

Steve Luke wrote:
In this case, both variables end up referring to the same Object, because the checkYourself result variable initially stores the String's address, then the checkYourself method returns a copy of the String's address.


I agree. I suppose I was taking the question a little differently. I was thinking of the second pass and beyond.

Once it's passed-by-reference back to the main method, you can never do anything to the "result" String object inside the SimpleDotCom Class ever again. Once the method is over, the variable in that class is useless (because it's not an instance variable) and can't be used to manipulate that String any longer. You need to manipulate it in the main method, right?

So when you call the method again in the next pass, it makes a NEW result String object. So then you effectively have two String objects (one in main, one in checkYourself)with variables named "result" that point to different objects.

Am I off my rocker?
Janeice
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38025
    
  22
Janeice DelVecchio wrote:Once it's passed-by-reference back to the main method . . .
What's pass-by-reference? I have heard of it, but it doesn't happen in Java.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
So when you call the method again in the next pass, it makes a NEW result String object. So then you effectively have two String objects (one in main, one in checkYourself)with variables named "result" that point to different objects.


No, you don't. It makes a new String reference. The checkYourself() method creates three String objects, one for each of the possible messages. Those String objects go into the String pool, and are reusable until the JVM exits. So, every time that method is run, a new reference points to an existing String object.

John.

Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

Janeice DelVecchio wrote:
Steve Luke wrote:
In this case, both variables end up referring to the same Object, because the checkYourself result variable initially stores the String's address, then the checkYourself method returns a copy of the String's address.


I agree. I suppose I was taking the question a little differently. I was thinking of the second pass and beyond.

Once it's passed-by-reference back to the main method, you can never do anything to the "result" String object inside the SimpleDotCom Class ever again. Once the method is over, the variable in that class is useless (because it's not an instance variable) and can't be used to manipulate that String any longer. You need to manipulate it in the main method, right?

So when you call the method again in the next pass, it makes a NEW result String object. So then you effectively have two String objects (one in main, one in checkYourself)with variables named "result" that point to different objects.

Am I off my rocker?
Janeice



No you aren't off your rocker - you are real close, but for this example, just a little bit off. Let's ignore the fact that the Strings being passed are String constants and live in the String pool for a second.

Inside the SimpleDotComGame class, in the main method, the String variable result is defined inside the while loop's block. Which means that each iteration of the loop in the while loop a String result variable is made - initially pointing at nothing. Then the checkYourself method gets called, and inside that a different, completely independent String variable named result is made and given a value. A copy of that value is passed back to the caller (at which point the checkYourself's result variable goes out of scope and essentially 'goes away'). Back in the main method, the result variable gets a copy of the reference to the String, the loop does some work with it, and the and at the end of the loop iteration the String result variable goes out of scope and doesn't exist anymore.

So when the loop comes back to the point where String result = theDotCom.checkYourself(guess);, BOTH result variables are brand new, fresh references, and all references to the previous result have gone away. If you wanted to keep a reference to the results for longer than one iteration of the loop you would need to define the variable OUTSIDE the loop.
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1659
    
  11

Thanks for clairifying .... now where the heck is the OP?

Janeice
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1659
    
  11

I knew you'd chime in here sometime, Campbell....

I quote, from the JavaRanch Campfire:
For primitives, you pass a copy of the actual value.

For references to objects, you pass a copy of the reference (the remote control).


Passing by reference is the same as passing by copy/value, right? I mean you're not passing the OBJECT..... just the REFERENCE to the object. Meaning, if you do something to an object whose references exist in more than one class, you're effectively changing the object and the next time you refer to it from anywhere the object returns the new information.

Maybe all this project management is making me crazy.....
Janeice
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1659
    
  11


John de Michele wrote:
So when you call the method again in the next pass, it makes a NEW result String object. So then you effectively have two String objects (one in main, one in checkYourself)with variables named "result" that point to different objects.


No, you don't. It makes a new String reference. The checkYourself() method creates three String objects, one for each of the possible messages. Those String objects go into the String pool, and are reusable until the JVM exits. So, every time that method is run, a new reference points to an existing String object.

John.



Congrats on winning that book, John.

HOLD ON A SEC.

so saying:


isn't analogous to:


I thought any time you declare a new String it's like saying: please create a new String with a reference named carColor for me, "yellow" is it's value (and if you don't define one, it's null). I thought strings were objects. I thought it was the same as saying: please create a new Animal with a reference named giraffe for me, it has no other information.

Now I know I'm crazy.
Janeice
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

Janeice DelVecchio wrote:I knew you'd chime in here sometime, Campbell....

I quote, from the JavaRanch Campfire:
For primitives, you pass a copy of the actual value.

For references to objects, you pass a copy of the reference (the remote control).


Passing by reference is the same as passing by copy/value, right?


No, pass by references is the opposite of passing by value. Java doesn't support it, some other languages do. Java only passes by value. There is a big difference between passing a reference by value (which Java does) and passing a reference. For example, in a language which allows a pass by reference if I did this:

Then the outcome would be "Hoho" being printed because both foo() and bar() have the same reference, so if you change the reference in one method the other method sees that change. In Java this can't happen, "Haha" will always be printed, regardless of what bar does.

Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

Janeice DelVecchio wrote:
John de Michele wrote:
So when you call the method again in the next pass, it makes a NEW result String object. So then you effectively have two String objects (one in main, one in checkYourself)with variables named "result" that point to different objects.


No, you don't. It makes a new String reference. The checkYourself() method creates three String objects, one for each of the possible messages. Those String objects go into the String pool, and are reusable until the JVM exits. So, every time that method is run, a new reference points to an existing String object.

John.



Congrats on winning that book, John.

HOLD ON A SEC.

so saying:


isn't analogous to:


I thought any time you declare a new String it's like saying: please create a new String with a reference named carColor for me, "yellow" is it's value (and if you don't define one, it's null). I thought strings were objects. I thought it was the same as saying: please create a new Animal with a reference named giraffe for me, it has no other information.

Now I know I'm crazy.
Janeice


Strings are Objects, but Strings are special because they are used so often. One such speciality is that there is a place in memory called the String Pool. When you refer to a String constant (with quotes like "yellow" or "hit") those constants get loaded into the String Pool (actually they can get put in the String Pool much earlier). Then when you assign a reference to that constant it goes to the String Pool and points to that String rather than make a new one. This makes using Strings faster and makes using lots of Strings more memory efficient. An effect is that if you have two String variables set to the same constant:

then they are actually pointing to the same String Object, rather than separate Strings.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Congrats on winning that book, John.

Thanks!

You're not crazy (yet ). Strings get some special handling behind the scenes. Take this fragment:

Assuming when 'one' is defined that "This is a String" hasn't been used before, a new String object will be created in the String pool. When 'two' is defined, it will point to that very same String object. You can force 'two' to point to a different String object like this:

However, you should consider that doing so will unnecessarily create more Strings in the String pool, and is considered bad practice.

Hope that helps.

John.
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1659
    
  11

So, to get back on the original topic,

The two "result"s are the same object/String in the pool, but the reference (and usefulness) to both get lost rather quickly, because the declarations are inside the loop and method. It is only coincidence they have the same name/variable, and either or both could be renamed without effect on the rest of the app. HFJ sould have named them something different to limit confusion.

The OP is gonna be thrilled with he gets back!
-Janeice
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: return values in methods
 
Similar Threads
Hi All, While working with Head first java, I got into a problem, please help me to solve this.....
Head First Java - pg 135 - ArrayList and Compile Errors
Chapter 5 Head First Java - problem with SimpleDotCom Gamehelper SimpleDotComGame
Head First Java SimpleDotCom program
HFJ 2nd - Problem with SimpleDotCom