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.
John Bonham was stronger, but Keith Moon was faster.
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
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.)
Please ignore post, I have no idea what I am talking about.