Methods

A Method is invoked by a method call. The syntax is as follows:
object. method (argument):
Usually. we start with an instance of a object. The object hands the method some information (arguments) and asks that method to perform a task based on that information. When the task is done, the method returns information back to the object that called it.
return = object.method (arguments);
Example:
Teacher.askasStudent (help);
The OBJECT (Teacher) doses not need to know how the method (student) accomplished the request. When we're writing software, one object is independent of another. How any object implements its own methods is hidden from the outside world. That way, once your method works nobody can mess it up. Hiding the implementation of a method promotes good software engineering. If you can't change how an object performs its methods, then you can't introduce errors. You have to live with the way it works how.
A method can receive as many arguments as you wish. But it can only return ONE thing. A Method also always Receives A copy Of Its Arguments. Since a Method only Receives a duplicate, it can NEVER change the original copy of the parameter it received .
impot java.awt.containere;
import javax.swing.*;
public class squarenInt extends JApplet
{
public void init ( )
{
string output = " ";
JTextArea = new JTextArea (10,20);
container capital = getcontentpane ( );
c.add (oArea) ;
int result;l
for ( int x = 1; x <= 10; x++)
{
result = square (x);
output += "square of " + x +
" is " + result + "/n";
}
outputArea.setText (output);
}
public int square (int y)
{
return y* y;
}
}
Notice this syntax: we are inside method init(). Yet we're calling to another method square() without referring to an object. "Methods in a class definition are allowed to invoke all other methods in the same class this way." Inherited methods can be called this same way.
All variables declared inside a method are local variables. And local variables must be initialized. They live only while the method is being executed and vanish after the method is done.
public double sum ( double x, double y )
{
double sum = 0;
sum = x + y;
return sum;
}
In this example.all three variables are local. The variables x and y declared as parameters in header, and the variable sum declared in the body of the method.
3.1 Coercion of Arguments
public double sum( double x, double y)
{
double sum = 0;
sum = x+ y;
return sum:
}
What would happen if- when we called this method—we passed it integers, rather than the doubles it expects? If it was able to, the compiler would attempt to convert or "coerce" the arguments into the right type. If I passed it an integer and expected a double. the conversion would be no problem converting an integer into a double doesn't lose any information. However if I passed it a double and it was expecting an integer, the conversion from double to integer WOULD lose information, so the compiler would complain unless I used an explicit cast operator to force the argument into the right type.
3.2 Duration of Identifiers
The duration of an identifier is the lifetime of the identifier. Identifiers only while the block they are declared in executes. Static variables exit from the time the class that defines them is loaded into memory until the program terminates.
3.3 Scope Rules
The scope for an identifier is the portion of the program in which the identifier can be referenced. The scopes for an identifier are:
• class
• block
• method
3.4 Method overloading
Method overloading allows a method name to be re-used. To overload a method—or to create another version of method that already exits—the argument lists for the methods must differ in:
• number of arguments
• type of arguments
• order of arguments
• The return type of the method is NOT considered.
3.5 Event Delegation Model
Unlike many other languages—such as visual Basic—when the Java programmer wisher to program responses to an event—such as the enter key being pressed, the event must be entirely programmed.
consider this analogy to the event model:
• Steve jobs decides he wants a bodyguard.
• somebody punches Steve—that's a problem.
• Bill—the bodyguard—notices Steve was punched.
• Bill reacts to the problem
The same thing with specifics attached;
• A Button decides it wants an Action Listener.
• A Button is pressed—an event happens:
• The Listener reacts to the event.
• Fully described in Java Terms:
• A Button adds an Action Listener.
• A Button is pressed—an event happens.
• The method actionperformed is executed, receiving an ActionEvent object.
• The Listener reacts to the event.
An event source is an object that can register listener objects and send those listeners event source can send out event objects to all registered listeners when that event occurs. The listener object(s) will then use the details in event object to decide how to react to the event. A "Listener Object" [an instance of a class] implements a special interface called a "listener interface." When you ask the listener object to pay attention to your event source, that is called registering the listener object with the source object. You do that with the following lines of code:
eventSourceobject.addEventListener ( eventlistenerobject ):
Every event handler requires 3 bits of code:
code that says the class implements a listener interface:
public class Myclass implements actionListener
code that registers a listener on one or more components.
someComponet.addActionListener (Myclass) ;
public voide actionperformed (ActionEvent e)
{
. . . // code that reacts to the action. . .
}
Lets take another Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class carps extends JApplet Implements
ActionListener
{
final int WON = 0, Lost = 1, CONTINUE = 2,
boolean firstRoll = true;
int sumofDice = 0;
int mypoint = 0;
int gamesStatus = CONYINUE;
// GUI components.
JLabel dieiLabel, die2Label, sumLabel, pointLabe1;
JTextField firstDie, secondDie,sum, point;
JButton roll;
First, to respond to events we must import the event class APL:
java.awt.event.*;
This is the first time we have seen a class that "implements" another class. This is called an interface. You see, although we are directly inheriting from the class JApplet,we are getting some functions through the interface from the class ActionListener.
//setup graphical user interface components public void init( )
{
Container capital = getContenpane ( );
c.setLayout (new FlowLayout ( ) );
dielLabel = new JLable ("Die 1" );
c.add ( dielLabel ) ;
firstDie = new JTextField ( 10 );
firstDie.setEditable (true );
c.add (firstDie);
roll = new JButton ( "Roll Dice" );
roll.addActionListener ( this ) ;
c.add (roll );
} // end of method init ( )
Capital is a container object that came from the content pane. Here, we are setting the Layout, or how the objects get stacked on the page. There are many different choices for layouts. We will discuss them later.
Earlier, we declared these JLabels and now we're defining them. Then, we see how the container c is using its method "add" to add the JLabels object dielLabel to its content pane. You can see how we have defined a new Button called "roll". Then we register an Action Listener on the button roll. We want our same JApplet – the one we are inside of now—to listen to for the events. To say that, we use the "this" reference below. It means "this" JApplet will listen for events that happen to the JButton "roll". This is called "registering an Action Listener.;
so, when an event happens to our button—because of the ActionListener—the following method is performed. It receives an actionEvent object. In our example, this method just calls another method,play()
//call method play when button is pressed.
public void actionperformaed ( ActionEvent e)
{
play ( );
}
// process one roll of the dice.
public void play ( )
if ( firstRoll)
{
sumofDice = rolldice ( );
switch ( sumOfDice )
{
case 7: case 11:
gamestatus = WON;
point.setText (" ") ;
break;
case 2: case 3: case 12:
gamestatus = LOST;
point.setText (" ");
break;
} // end of switch
} // end of true if block
else
{
sumOfDice = rollDice ( );
if ( sumofDice = =mypoint )
gamestatus = WON;
else
This method decides what to do when the event happens.

3.6 Interfaces
When we said our program:
imp1ements ActionListener
it was implement the interface ActionListener, it means that you must define a method called:
public void actionPerformed ( ActionEvent e ) in your class.

3.7 Recursion
For any programming problem, there are usually two alternative ways to solve it:
iteration – Interaction means repeating the same thing a certain number of times until the solution is achieved.
recursion – Recursion means having a method call itself. or rather, it is better to think that it calls another copy of itself.
If we choose to call a method recursively, it means we are calling, it's numerous times until we arrive at the solution. Ironically, a recursive method can only actually solve the simplest "base" case. The other, more complex cases wait until the simplest base case is solved and then it work from the inside out until all the cases are solved.
Recursion Example: The Fibonacci series
This is a Fibonacci series:
0.1.1.2.3.5.8.13.21,3,55……..
It makes the next number in the sequence by adding together the previous two numbers.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FibonacciTest extends JApplet Implements ActionListener
{
JLabel numLabel, resultLabel;
JTextField num, result;
public void init ( )
{
container capital = getContenpane ( ) ;
c.setLayout (new FlowLayout ( ) ) ;
nuLabel = new Jlabel ( "Enter and Integer and press Enter" ) ;
c.add (numLabel ) ;
num = new JTextField (10) '
// creates a new JTextField with 10 columns num.addActioListener ( theis ) ;
// makes "this" Applet listen for events.
c.add (num) ;
resultLabel = new JLabel ( "Fibonacci value is " ) ;
c.add (resultLabel ) ;
result = new JTextField (15) ;
result.setEditable ( false ) ;
c.add (result) ;
} // end of method init ( )
public void actionperformed ( ActionEvent e )
{
long number,
fibonacciValue;
number = Long.ParseLong ( num.getText ( ) ) ;
showStatus ( "calculating . . ." ) ; // status area of Applet
fibonaccivalue = Fibonacci ( number ) ;
showStatus ( "Done" ) ;
result.setText ( Long.toString ( fibonacciValue ) ) ;
} // end of method actionperformed ( )
// Recursive definition of method Flbonacci
public long fiboancci ( long n )
{
if ( n == 0 . . n == 1 ) // base case
{
return n:
{
else
{
return fubibaccu ( n- 1) ) + DUVIBxxu ( n-2) ;
} // end of method Fibonacci ( )
} // end of class FibonacciTest
public long Fibonacci ( long n )
{
if ( n == 1 ) // base case
{
return n;
}
else
{
return Fibonacci ( n- 1 ) + Fibonacci ( n – 2 ) ;
}
}
This method is called repeatedly until it reaches the base case. then the previous copies of the method—that had been waiting for the else to fin ish complete their execution from the inside out.