Methods, similar to functions in other languages, are a mechanism for program decomposition. They provide a way to group together statements that perform a particular operation. If your program executes the operation repeatedly, you need only call method that executes that operation rather than repeatedly writing several statements to perform the operation.
Each method has a signature that specifies its name and the type, number, and order of its parameters. Parameters are the inputs to a method.
A method header includes the information provided in the signature, along with the return value of the method. It may also (optionally) specify a visibility modifier. This indicates from where the method can be called. The modifier public indicates that the method may be called from anywhere. The modifier private indicates that the method may only be called from other methods in the same class.
Example: public int addOne(int input)
Typically, a call to a method that returns a value should appear on the right hand side of an equals sign. This is because you typically want to save the value returned and do something with it later. You can also pass the value as a parameter to another method. For example: System.out.println(s.length()) passes the result of calling the length method on s (which will be the size of the string in the example above) to the printlin method called on the object System.out.
If a method does not return anything its return type is void. If a method's return type is something other than void, it must return a value of that type. You will get a compiler error if the method does not return a value.
A return statement is simply the keyword return followed by the value you wish to return.
Java uses pass-by-value semantics. That means, when a method is called, the values of the actual parameters are copied into the memory cells holding the formal parameters in the new activation record. For primitive types, this means that copies of the variables are created. However, for reference types, this means that there are now two references to the same object. Changes made to the object from within the method will be reflected after the method returns.
In the example above, there are two copies of x, one in the activation record for main and one in the activation record for addOne.
In the example above, there are two references to the Name object. When the method changes the contents of the object, the changes are seen by the reference in the main method.