Download Method Calls - Illinois Institute of Technology

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Methods of computing square roots wikipedia , lookup

Horner's method wikipedia , lookup

Newton's method wikipedia , lookup

Root-finding algorithm wikipedia , lookup

False position method wikipedia , lookup

Transcript
CS115
OBJECT ORIENTED PROGRAMMING I
LECTURE 4_4
GEORGE KOUTSOGIANNAKIS
Copyright: 2016 Illinois Institute of TechnologyGeorge Koutsogiannakis
1
METHOD CALLS
• Topic: Calling methods from another method
2
METHOD CALLS
• A java class can have many methods in it.
• It is not a requirement that one of the
methods is the main method but
– It is a requirement to have a main method if that
class is intended for execution (run it).
3
METHOD CALLS
• Suppose a class has a main method and
another method:
– We can call the second method from within the
main method and ask for its execution. As a result
of its execution it is possible that the second
method produces some value that needs to be
accessed by the main method.
• We say that the method “returns a value” of a
particular data type.
4
METHOD CALLS
•
public class CalculateSR
{
public static void main(String[] args)
{
double a=0.0;
double b=100;
a=squareRoot(b);
System.out.println(“the square root of b is”+” “+a);
}
public static double squareRoot(double x)
{
double y=Math.sqrt(x);
return y;
}
}
5
METHOD CALLS
• In program CalcualateSR:
– Execution of a program in Java always starts with the code inside the
main method, regardless how many other methods are in the same
class 9program).
– The code is executed one line at a time starting with the
declarations/initializations (in our example):
double a=0.0;
double b=100;
– When the following line of code is executed
a=squareRoot(b);
The program does the following:
6
METHOD CALLS
– The code for each method (the main method and the square Root method) is
kept in different parts of memory.
1. The program goes to where the code for square Root method is located and
provides a copy of the value held in memory location b (100 in our example).
This is the so value that the method squareRoot takes as argument (the input
value).
2. The code for method squareRoot is now executed usingteh value 100
3. When the square root of 100 is calculated the result is store din memory
location y.
4. The main method is notified that the result is in memory location y.
5. The main method finishes the execution of the line a=squareRoot(b); (called
generacally “a method call”) by copying the result from memory location y to
memory location a.
6. The main method proceeds now with the execution of its last line of code:
System.out.println(“the square root of b is”+” “+a);
Program terminates after that.
7