Java Methods

 

 

Methods Basics

Methods: The procedures or functions of a class.

System.out.println(Math.sqrt(c*d+1));

Java is very rich with class definitions and complete sets of methods. 

Defining methods in classes shown well in the text.

 

 

 


Math class

abs(float|int|long)
ceil(float)  floor(float)
cos(float)  sin(float) tan(float)
exp(float)  log(float)  pow(float,float)
max(int|long|float, int|long|float)  min(int|long|float, int|long|float)
sqrt(float)
random()

 

 

 


Promotions

There are various numeric types.  Having the exact type match the parameter types can be tedious.  Promotions are provided:

Type Allowed promotions
double None
float double
long float, double
int long, float, double
char int, long, float, double
short int, long, float, double
byte short, int, long, float, double
boolean None

Type casting

There are times the programmer must force a type to become another type.  This is called "type casting" or "coercion".

(type) valueExpression

dieValue = ((int) Math.random() * 6) + 1;

 

 

 


Identifier Scope and Duration

Identifiers have duration or lifetime.

Scope refers to the range of code that can access the identifier

Recursion

 

 

 

 


JApplet Methods

public void init() -- called once when the applet is start.  Meant for initialization code that must be run once and only once.

public void start()-- called after init() is completed.  This routine is rerun every time the user of the browser returns to the HTML page that holds the applet, after viewing another page.

public void paint (Graphics g) -- called after init() is completed and start() is started but not necessarily completed.  start() and paint(g) are run as separate threads.  Each time the applet is uncovered paint(g) is called.  This routine is called also by the repaint() routine.

public void stop() -- called when the user of the browser leaves the HTML page.

public void destroy() -- called when the browser is exited. (Note applets often remain resident and are not reloaded)

 

 

 

 

 

 


First example of event driven programming

This is the Craps.java program of Example 06-09.  Its associated html file is craps.html

Consider the following: