This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# Methods......

Steve Jensen
Ranch Hand
Posts: 126
Before i go back to the cattledrive assignments, I want to cover 2 more chapters, namely on Methods and Classes.
Found this dead neat book called "Programming with Java", published by Schaums. I think they are an American publisher, as I haven't seen them in England before, and the price of the book is in \$'s, this book is very useful. It cuts out the waffle, and just demonstrates Java by examples.
But i have a query. Forgive my naivety, please.
Below is a program which makes use of a method.
The program finds the cube of a number, utilising a method called cube() that returns the cube of the integer passed to it:

Thing is, we call the cube method by saying:-
cube(i) - passing to the method the integer i.
Right, but the actual cube method itself is defined as:-
int cube(int n)

OK, we have said here that the cube method is an integer method (???), which accepts a variable n, of type int. But the variable we are passing TO the cube method, is of type int, but is called 'i'. How does the method work? Considering the variable we are passing to it is called i, and the actual method accepts an int variable called 'n'.
Daft question I know, but I am confused.
I'll get my coat.

Layne Lund
Ranch Hand
Posts: 3061
That is actually a very good question. Names can sometimes be confusing. The key to method parameters is that the value is copied. The name of the variable itself is irrelevant. So in your example, the value of i in main() is copied into the variable n in cube(). That's all there is to it. This technique is called pass-by-copy or pass-by-value. Just realize that n and i have the same value to start with, but they are two separate variables with their own space in memory.
HTH
Layne

William Barnes
Ranch Hand
Posts: 986
Right. The name of the variable in the calling code doesn't have to be the same as the name in the method.
It sounds strange but you will actually find it useful in the future. (If the variable names had to be the same it would make calling the same method from different parts of your code difficult.)

Michael Matola
whippersnapper
Ranch Hand
Posts: 1817
4
Steve, it might help you to take a look at the Campfire Stories
Cup Size
and

Steve Jensen
Ranch Hand
Posts: 126
Originally posted by Michael Matola:
Steve, it might help you to take a look at the Campfire Stories
Cup Size
and