Difference between revisions of "Overview"
From CompSciWiki
(→Main Method) |
|||
Line 22: | Line 22: | ||
</pre> | </pre> | ||
− | The ''main'' method is a special type of user-defined method. When you tell Java to run your program, Java will look for a method called ''main'' within your class and run it if | + | The ''main'' method is a special type of user-defined method. When you tell Java to run your program, Java will look for a method called ''main'' within your class and run it if found. Try running a program without a ''main'' method and see what the result is. |
Revision as of 20:09, 13 March 2007
A user-defined method is a section of code which is declared once in a program, then used by other code sections.
A method does three things:
- Accepts input values, called parameters.
- Performs some action which may use the parameters.
- Gives a return value, or output value, to the code which called the method.
Instead of writing an entire program in the main method, you can separate program functionality into separate user-defined methods. Doing so has two main benefits:
- Code becomes easier to read. When a complex code segment is placed in a user-defined method and called by the main method, a programmer who reads the main method will only need to understand what the user-defined method does, and not how it is implemented.
- Code becomes easier to reuse. When a program consists of only a main method, the only way to reuse sections of code is to copy and paste code sections. On the other hand, if a program separates its logic into a number of user-defined methods, the programmer can call these methods from other programs.
Main Method
Up until now, you have placed all code inside the main method:
public static void main(String[] args) { // Code is written here }
The main method is a special type of user-defined method. When you tell Java to run your program, Java will look for a method called main within your class and run it if found. Try running a program without a main method and see what the result is.