Calling methods:
Any java statement that looks like someWord() is a method.
This means find the segment of code that looks like someWord() { ... } and run the code in the { }.
When execution is transferred to a method, we say that the method is CALLED. (Some languages require you to write "call someWord()")
Once the method is finished it RETURNS. This means that execution goes back to line of code that called the method.
You CANNOT put one method inside another method.
How to define a method:
____❶___ ___❷_____ methodName( ❸ ) { ...❹... }
- ❶ are optional modifiers. The most common are static, public, private
- ❷ is the return value. It is mandatory. You have to say what the method returns or else put void
- ❸ are optional parameters or arguments. They list the data type and what you are going to call it in this method.
If you put stuff here, the calling program MUST supply the correct type and number of arguments.
- ❹ is the method body. This is the code block that runs when you execute the method.
A method can only ever return 1 thing. You cannot return two different pieces of information. If you have to do this, you must make an object that contains the
information and return a single object.
How do you recognize a method?
- when a program calls a method it will look like pppppp().
Examples:
drawGraphics();
System.out.print("Print me") ;
c.setColor(Color.RED);
myMethod(x,y,z);
- A method definition is NEVER inside another method. It is always just inside a class.
- Look for these three things to recognize method definitions. ALL METHODS HAVE THESE!
- i. methodName( )
-
- ii. a return value: either void or a data type like int, double, String, Rectangle, ...
- iii. and { }
Examples void drawBox(int x, int y) { ... }
double findArea(double length, double width) { ... }
Also ...
- iv. If there are parameters, you'll see the type of parameter listed:
e.g. int myMethod (int x, int y, int z) { }
instead of just int myMethod(x,y,z) { }