{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

methods - Methods Why Write Methods Many times when we are...

Info icon This preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Methods Why Write Methods? Many times when we are writing programs we find that we want to repeat the same set of actions multiple times. When we put all the code in a single Main method, we must just write the same lines of code over and over. This leads to programs that are longer than they need to be and “ugly” code. A method is a section of code that does a particular job. When we want to execute those lines of code, we call the method. This means that instead of repeating a bunch of lines of code when we want to perform an action, we just need to include one line to call the appropriate method. This makes our code much easier to read. Declaring a Method This section will discuss the format for declaring a method. All methods must have a return type (if the method is performing a calculation and giving back a result), a name , and a number of parameters (pieces of data that the method needs to perform its calculations). Syntax Methods are declared inside the brackets for the class, but outside the brackets for the main method. For example: public class Example { public static void main(String[] args) { } //Declare method here //Can declare as many methods as you want } Here is the syntax for declaring a method: public static returnType name(params) { //code for method goes here } For now, don’t worry about what the public static part means – just put that at the beginning of all your methods. Next, the returnType is the type of data you want this method to give back. For example, if we were writing a method that computed the area of a square with integer sides, then we would
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon