Home Java Java-tips Flow Methods Methods - Declaring

Ask Questions?

View Latest Questions

Advertisement


 
 

Methods - Declaring
Posted on: July 26, 2006 at 12:00 AM
Notation: Everything between square brackets, "[" and "]", is optional.

Java Notes

Methods - Declaring

Declaration syntax

Notation: Everything between square brackets, "[" and "]", is optional.

[access] [static] [type] name( [parameters] ) { body }

access If no scope is given, a method has package scope. Other comon values for scope are public (everyone can see it) and private (can only be seen from within this class). For small programs don't worry about scope. However, for applets you need to declare init() and paintComponent() methods to be public so that the browser and Java GUI code can see them. If you are writing an application, you must declare main(...) to be public so the operating system can call it.
static The static keyword is used to declare class methods -- methods that don't refer to a specific object. The only method that you will probably declare this way is main.
type Any Java type, including arrays, can be written here to tell what data type value the method returns. Use void if the method doesn't return a value.
Note: There are also other, less frequent, modifiers that we won't discuss here (protected, synchronized, final, abstract, native)

Parameters

Formal parameters are the parameters that are written in the method definition. These are the names that you use in your method. Formal parameters are like local variables that get an initial value at the time the method is called.

Actual parameters or arguments are the values that are written in the method call. The actual parameter values are copied into the formal parameters, which are then like initilialized local variables.

Local Variables

Variables that you declare in a method are called local variables. They are created on a call stack when the method is entered, and they are destroyed when the method returns. Because objects (eg Strings and arrays) are allocated in the heap, they are never in the call stack and can be returned from the method.
Copyleft 2003 Fred Swartz MIT License, Last update: 2002-02-07
Advertisement


DMCA.com