Java: Method FAQs
Q: Do we always have to write a class name in front of static method calls?
A: Yes, but Java allows an exception. If the static method definition is in the same class as the call, you don't have to write it. You could write the following, but I've never actually seen a program use it.
Q: Does the the definition of main have to appear first?
A; No. Methods in a class may be defined in any order, unlike some languages (eg, C++).
Q: Doesn't defining this method make the program more complicated?
For this simple kilometers to miles conversion it isn't worth the effort to write a method. However, if this was a realistically large program, and if this kind of conversion had to be performed in several places in the program, it would be much better to put the conversion in a method so that there would be no errors, for example, when typing the constant 0.621. This small method is just practice.
Are parameters passed by reference or passed by value?
The phrase "pass by reference" means that a reference to the actual parameter *variable* is passed, not the value that the variable contains.
When you pass the value of a variable, even if it's a reference, it's called "pass by value", which is Java's only way of passing parameters.
C++ has both "pass by reference" and "pass by value"; Java only has pass by value (altho those values often happen to be themselves references).
The most dramatic demonstration of this is that it's impossible to define
swap(a, b)
in Java! For you Java programmers, this is a very useful
C++ function that exchanges the values of a and b, which you have to do awkwardly in Java with
temp = a; a = b; b = temp;